Docsity

WGU D522 Python for IT Automation | Network Automation, Socket Programming & Connectivity, Exams of Information Technology

Partial preview of the text

Download WGU D522 Python for IT Automation | Network Automation, Socket Programming & Connectivity and more Exams Information Technology in PDF only on Docsity!

WGU D522 Python for IT Automation |

Network Automation, Socket Programming &

Connectivity Diagnostics Workbook | 20 Python

Labs + Practice Questions with Rationales + 5

Projects | 2026/2027 update | with complete

solutions

Section 1: Network Automation Fundamentals (1–15)

  1. A network administrator needs to automate the detection of unreachable hosts and record the results. Which Python capability is most appropriate? A. String formatting only B. Network socket operations C. HTML rendering D. File compression Answer: B Rationale: Socket-based operations allow Python to communicate with network endpoints and can be used to test connectivity and collect network-related results.
  2. A remediation script should continue processing the remaining devices when one device produces an exception. Which approach is most appropriate? A. Terminate the program immediately B. Use exception handling around the individual device operation C. Remove all error checking D. Restart the operating system Answer: B Rationale: Handling exceptions at the device-operation level allows the script to record the failure and continue processing other devices.
  1. Which Python feature allows reusable remediation logic to be encapsulated into a named block? A. Variable B. Function C. Comment D. Loop Answer: B Rationale: Functions encapsulate reusable logic into a named, callable block that can be invoked multiple times.
  2. Which module is best suited for reading a CSV device inventory file? A. json B. csv C. xml.etree D. pickle Answer: B Rationale: The csv module is purpose-built for reading and writing comma-separated value files, the standard format for device inventory lists in network automation.
  3. In Python's csv.DictReader, what does each row become? A. A tuple of values B. A list of strings C. A dictionary keyed by column headers D. A namedtuple with fixed fields Answer: C Rationale: DictReader treats the first row of the CSV as field names and returns each subsequent row as a dictionary where keys are the column headers and values are the corresponding cell contents.
  4. Why should a port field from a CSV be converted to an integer before use? A. CSV files cannot store numeric values B. Socket and connection libraries expect an integer port number C. Integer conversion encrypts the port value D. It reduces file size Answer: B Rationale: When CSV data is read, all values arrive as strings. Python's

socket library and libraries like Paramiko require port numbers as integers, not strings. Failing to convert will raise a TypeError.

  1. What exception should be caught when converting a CSV string to an integer port? A. KeyError B. IndexError C. ValueError D. TypeError Answer: C Rationale: int() raises ValueError when the string cannot be parsed as a number, such as "abc" or an empty string. Catching ValueError allows the script to report a clear, row-specific validation error.
  2. What is the risk of not validating inventory records before using them? A. The script will run faster than expected B. Invalid records can cause runtime exceptions that halt the audit C. The CSV file will be deleted D. DNS servers will change automatically Answer: B Rationale: If malformed records—such as non-numeric ports, empty hostnames, or missing fields—are passed directly into connection functions, the script will raise unhandled exceptions and terminate.
  3. Which data structure is most appropriate for storing a collection of device dictionaries? A. A list of dictionaries B. A set of integers C. A tuple of booleans D. A string Answer: A Rationale: A list of dictionaries is the natural Python structure for a collection of records where each record has named fields. Lists preserve order and allow iteration, while dictionaries provide key- based access to each device's attributes.
  4. What is the purpose of a device inventory in network automation? A. To physically label network devices

D. The port number Answer: B Rationale: gethostbyname() resolves a hostname to its IPv4 address.

  1. An automation script uses socket.gethostbyname_ex() to resolve 500 hostnames. It intermittently hangs for minutes. Which approach best mitigates this while preserving per-host resolution results? A. Set socket.setdefaulttimeout(5) and catch socket.timeout per host B. Replace gethostbyname_ex with a single call to socket.getaddrinfo for all hosts C. Run all resolutions in one thread to avoid GIL contention D. Use dnspython with a custom resolver and per-query lifetime, falling back to system resolver Answer: D Rationale: dnspython allows explicit per-query timeouts and retries without global socket state, and can fall back to the system resolver. setdefaulttimeout affects all sockets globally and may not cover all resolver paths; getaddrinfo does not accept multiple hosts; single- threading worsens latency.
  2. When using subprocess.run() to execute a shell command that may produce large output, which combination of parameters prevents deadlocks and captures output safely? A. stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True B. capture_output=True, text=True, timeout= C. stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT D. shell=True, stdout=subprocess.PIPE, universal_newlines=True Answer: B Rationale: capture_output=True redirects both stdout and stderr to pipes, text=True decodes to strings, and timeout prevents indefinite hangs. This is the recommended high-level approach in Python 3.7+.
  3. A script uses subprocess.run(['rsync', '-av', src, dest], capture_output=True, text=True). The command fails with a non-zero exit code, but the script continues silently. Which modification ensures the script raises an exception on failure while preserving stdout/stderr for logging? A. Add check=True to the subprocess.run call B. Wrap the call in try/except subprocess.CalledProcessError and re-raise

C. Set stderr=subprocess.PIPE and inspect the return code manually D. Use subprocess.Popen instead and call communicate() Answer: A Rationale: check=True causes subprocess.run to raise CalledProcessError on non-zero exit, while still capturing output if capture_output=True. It is the minimal, idiomatic fix.

  1. Which HTTP method is normally used to retrieve information from an API without requesting a modification? A. GET B. POST C. DELETE D. PATCH Answer: A Rationale: GET is conventionally used to retrieve resources. POST creates, PATCH partially modifies, and DELETE removes.
  2. Which Python library is commonly used to make HTTP requests to REST APIs? A. requests B. math C. json D. os Answer: A Rationale: The requests library provides a convenient interface for sending HTTP requests such as GET, POST, PUT, PATCH, and DELETE.
  3. Which approach correctly handles a JSON API response that may contain missing fields? A. data = response.json(); value = data['field'] (direct access) B. data = response.json(); value = data.get('field', default_value) C. value = response.json()['field'] D. value = response.json().field Answer: B Rationale: dict.get('field', default) returns a default value if the key is missing, avoiding a KeyError. Direct indexing would raise an exception if the field is absent.
  1. You need to list all files with the extension .log in /var/log and print their absolute paths. Which snippet accomplishes this? A. print(glob.glob('.log')) B. print(glob.glob('/var/log/.log')) C. print(os.listdir('/var/log')) D. print(glob.glob('/var/log/', recursive=True)) Answer: B Rationale: glob.glob('/var/log/*.log') matches all .log files in the directory and returns their full paths. Option A lacks the directory path, and Option C lists all files regardless of extension.
  2. A script must archive all .log files older than 30 days from a directory tree while preserving relative paths. Which pathlib-based approach correctly identifies and processes only those files? A. Use Path.rglob('.log') and filter by st_mtime B. Use os.walk and check file extensions manually C. Use glob.glob('/.log', recursive=True) and filter by os.path.getmtime D. Use Path.glob('.log') with a recursive flag Answer: A Rationale: Path.rglob('.log') recursively searches for .log files, and st_mtime from stat() provides modification time. This combines pathlib's recursive glob with file metadata, which is the most Pythonic and correct approach.
  3. Which function is commonly used to retrieve an environment variable in Python? A. os.getenv() B. os.file() C. sys.variable() D. env.read() Answer: A Rationale: os.getenv() retrieves the value of a specified environment variable and can optionally return a default value when the variable is absent.
  4. Why should API credentials generally NOT be hard-coded directly into a Python script? A. Python cannot process strings containing credentials B. Hard-coded credentials increase the risk of credential exposure

C. API credentials cannot be stored in variables D. APIs require credentials to be entered manually each time Answer: B Rationale: Credentials embedded in source code can be exposed through repositories, backups, logs, or shared files. Environment variables or secure secret-management mechanisms are generally safer.

  1. Which method of handling sensitive credentials avoids hardcoding and aligns with current security best practices for IT automation? A. Store credentials in environment variables and access via os.environ B. Encrypt credentials with a symmetric key stored in the script C. Use a configuration file with base64-encoded credentials D. Prompt the user for credentials at runtime and cache in memory Answer: A Rationale: Environment variables are a standard way to inject secrets without hardcoding. Base64 is not encryption, and storing keys in scripts is insecure. Prompting at runtime is not suitable for automation .
  2. What is the purpose of socket.setdefaulttimeout()? A. To set the default timeout for all new sockets B. To set the maximum number of connections C. To set the default port number D. To set the default IP address Answer: A Rationale: setdefaulttimeout() sets the default timeout value (in seconds) for all new sockets created after the call.
  3. A connectivity test must determine whether a TCP port is open on a remote host. Which approach is most appropriate? A. Use socket.create_connection((host, port), timeout=5) B. Use socket.gethostbyname(host) C. Use subprocess.run(['ping', host]) D. Use requests.get(f'http://{host}:{port}') Answer: A Rationale: socket.create_connection() attempts to establish a TCP connection to the specified host and port, raising an exception if the port is closed or unreachable. It directly tests TCP connectivity.

A. A list of server strings B. A dictionary mapping device names to approved DNS server lists C. A tuple of device names D. An integer Answer: B Rationale: A dictionary allows O(1) lookup of approved DNS servers by device name, making the comparison efficient during the audit.

  1. What is the purpose of the resolvectl command in Linux network diagnostics? A. To configure firewall rules B. To query and manage DNS resolution settings C. To compress files D. To manage user accounts Answer: B Rationale: resolvectl (part of systemd-resolved) is used to query and manage DNS resolution configuration on Linux systems.
  2. Which logging level is most appropriate for recording successful connectivity checks during a network audit? A. DEBUG B. INFO C. ERROR D. CRITICAL Answer: B Rationale: INFO is used for routine operational messages, such as successful connectivity checks and audit progress.
  3. Which logging level should be used when a device fails a connectivity check? A. DEBUG B. INFO C. ERROR D. CRITICAL Answer: C Rationale: ERROR is appropriate for recording failures that affect individual operations but do not halt the entire script.
  1. What is the purpose of a RotatingFileHandler in Python logging? A. It encrypts log files B. It rotates log files when they reach a certain size, managing disk usage C. It sends logs to a remote server D. It compresses log files Answer: B Rationale: RotatingFileHandler automatically rotates log files when they reach a specified size, creating backups and preventing unbounded growth.
  2. Why is it important to redact sensitive information (passwords, tokens) from logs in automation scripts? A. To make logs smaller B. To prevent credential leakage that could lead to security breaches C. To speed up log processing D. To comply with Python syntax rules Answer: B Rationale: Logging credentials exposes them to anyone with log access, creating a major security risk. Secrets should never be logged; redaction or omission is essential.
  3. A remediation script must send an email notification when a device fails remediation. Which Python module is commonly used for SMTP email? A. smtplib B. http C. socket D. json Answer: A Rationale: smtplib is the standard library module for sending email via SMTP.
  4. Which data format is most commonly used for structured log output that can be easily parsed by log aggregation tools? A. Plain text B. JSON C. XML D. CSV

B. for key, value in dict.items(): C. for value in dict: D. for item in dict: Answer: B Rationale: dict.items() returns key-value pairs, allowing iteration with for key, value in dict.items():.

  1. A network automation script needs to store the results of connectivity tests for multiple devices. Which data structure is most appropriate? A. A list of dictionaries, where each dictionary represents one device's results B. A single string containing all results C. A set of integers D. A tuple of booleans Answer: A Rationale: A list of dictionaries allows each device's results (hostname, IP, status, error message) to be stored as a structured record and iterated for reporting.
  2. What is the primary purpose of exception handling in a network automation script? A. To eliminate all syntax errors B. To prevent the script from ever terminating C. To handle unexpected runtime conditions gracefully and continue processing D. To increase CPU utilization Answer: C Rationale: Exception handling allows a script to respond appropriately to problems such as unreachable devices, timeouts, or authentication errors, recording the failure and continuing with remaining devices.

Section 2: Data Structures, Strings & File I/O (Continued)

  1. A script must read a JSON file config.json and return the value associated with key "host". Which code correctly loads the file and retrieves the value?

A. with open('config.json') as f: return f.read()['host'] B. with open('config.json') as f: return json.load(f)['host'] C. return json.loads('config.json')['host'] D. with open('config.json','w') as f: return json.dump(f)['host'] Answer: B Rationale: json.load(f) deserializes a file object into a Python dictionary. json.loads() expects a string, not a filename, and opening in 'w' mode would truncate the file.

  1. You want to append the string "DONE\n" to a file tasks.txt. Which snippet performs this correctly? A. open('tasks.txt','w').write("DONE\n") B. with open('tasks.txt','a') as f: f.write("DONE\n") C. open('tasks.txt','r').append("DONE\n") D. with open('tasks.txt','x') as f: f.write("DONE\n") Answer: B Rationale: The 'a' mode opens the file for appending without overwriting existing content. 'w' would overwrite, 'r' is read-only, and 'x' creates a new file exclusively.
  2. A script must create a backup copy of folder /home/user/data to /home/user/data_backup. Which shutil call accomplishes this? A. shutil.copy('/home/user/data','/home/user/data_backup') B. shutil.copytree('/home/user/data','/home/user/data_backup') C. shutil.move('/home/user/data','/home/user/data_backup') D. os.rename('/home/user/data','/home/user/data_backup') Answer: B Rationale: shutil.copytree() recursively copies an entire directory tree. copy() is for single files, move() relocates the original, and os.rename() renames rather than copies.
  3. Which pathlib approach most efficiently finds all .log files modified in the last 24 hours without loading the entire tree into memory? A. [p for p in Path('.').rglob(".log") if p.stat().st_mtime > time.time() - 86400] B. list(Path('.').rglob(".log")) then filter by os.path.getmtime C. for p in Path('.').rglob("*.log"): if p.stat().st_mtime > time.time() - 86400: yield p D. Path('.').walk() and check p.suffix == '.log' Answer: C Rationale: A generator expression (via yield) processes files lazily,