






















































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!























































































Q1. What is the primary purpose of a device inventory in network automation?
A. To physically label network devices B. To maintain a structured record of network assets and their attributes C. To replace network monitoring tools D. To encrypt device configurations Answer: B Rationale: A device inventory serves as a centralized, structured record containing device names, IP addresses, ports, credentials, and other attributes needed for automation workflows. It does not replace monitoring tools, encrypt configurations, or involve physical labeling. Accurate inventory data is foundational because every subsequent automation task — connectivity checks, configuration audits, DNS validation — depends on knowing which devices exist and how to reach them. Q2. Which Python 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, which is the standard format for device inventory lists in network automation. It provides DictReader and DictWriter classes that map rows to dictionaries, simplifying field access. The json module handles JSON, xml.etree handles XML, and pickle handles Python object serialization — none of these are designed for CSV parsing. Q3. 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
Q6. 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. Validating each record up front lets the script skip or flag bad entries while continuing the audit for valid devices. Validation does not affect speed positively, delete files, or alter DNS configuration. Q7. Which data structure is most appropriate for storing a collection of device dictionaries? A. A single string B. A list of dictionaries C. A set of integers D. A tuple of booleans Answer: B 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. Strings, sets of integers, and tuples of booleans cannot represent multi-field records. Q8. What does the newline="" argument accomplish when opening a CSV file? A. It removes all newlines from the file B. It prevents newline translation issues on different platforms C. It converts the file to binary mode D. It appends a newline to every row
Answer: B Rationale: The csv module documentation recommends opening files with newline="" so that newline handling is delegated to the csv reader rather than the underlying platform. Without it, embedded newlines within quoted fields can be misinterpreted on Windows, producing broken rows. It does not remove newlines, switch to binary mode, or append anything. Q9. What does encoding="utf-8" specify when opening a CSV file? A. The file is compressed B. The character encoding used to decode the file's bytes C. The file is encrypted D. The delimiter is a comma Answer: B Rationale: The encoding parameter tells Python how to decode the raw bytes of the file into text. UTF-8 is the most common encoding and handles international characters. It has nothing to do with compression, encryption, or delimiters. Specifying it explicitly avoids platform-dependent defaults that can cause UnicodeDecodeError. Q10. Which method correctly counts the rows read from a DictReader? A. reader.count() B. len(reader) C. Iterate and increment a counter D. reader.size() Answer: C Rationale: A DictReader is an iterator, not a sized container, so len() and count() do not work. The idiomatic approach is to iterate over the reader and increment a counter, or convert to a list first with list(reader) and then call len(). size() is not a method on DictReader at all.
Rationale: By default Paramiko raises an exception when connecting to a host whose key is not in known_hosts. AutoAddPolicy automatically accepts and stores unknown host keys, which is convenient in lab environments but weakens security in production. It does not encrypt the session, disable authentication, or set ports. Q14. Why is AutoAddPolicy considered a security risk in production? A. It slows down connections B. It accepts any host key, enabling man-in-the-middle attacks C. It requires a password D. It blocks port 22 Answer: B Rationale: AutoAddPolicy trusts any presented host key, so an attacker performing a man-in-the-middle attack can impersonate the target device and capture credentials or commands. In production, administrators should pre- populate known_hosts or use RejectPolicy with a managed key database. AutoAddPolicy does not affect speed, require passwords, or block ports. Q15. What does client.exec_command() return in Paramiko? A. A single string of output B. A tuple of stdin, stdout, stderr file-like objects C. A boolean success flag D. An integer exit code Answer: B Rationale: exec_command returns a 3-tuple of (stdin, stdout, stderr), each being a file-like object. The caller reads stdout with .read() or iterates lines, and can read stderr separately for diagnostics. The exit code is obtained from the channel via recv_exit_status(), not returned directly by exec_command. Q16. How do you obtain the exit status of a remote command in Paramiko?
A. stdout.read() B. channel.recv_exit_status() C. client.get_exit_code() D. stderr.read() Answer: B Rationale: After exec_command, the underlying channel object is accessible via the stdout (or stdin) object's .channel attribute, and recv_exit_status() blocks until the remote command completes and returns its exit code. stdout.read() and stderr.read() return output text, and get_exit_code() is not a Paramiko method. Q17. What does the timeout parameter in Paramiko's connect() control? A. The time to wait for DNS resolution only B. The TCP connection timeout in seconds C. The maximum session duration D. The time between keepalive packets Answer: B Rationale: The timeout parameter sets the TCP socket connection timeout — how long Paramiko waits for the underlying socket to connect before raising an exception. Session duration is not limited by this parameter, DNS resolution is part of the connection attempt, and keepalives are configured via set_keepalive() on the transport. Q18. Which Linux command is commonly used to display DNS resolver configuration on modern systemd systems? A. ifconfig B. resolvectl status C. netstat - rn D. df - h Answer: B
Q21. In the regex r"DNS Servers?:\s([0-9.]+)", what does the? after "Servers" do? A. Makes the preceding character optional B. Makes the preceding s optional, matching both "Server" and "Servers" C. Repeats the group zero or more times D. Escapes the s character Answer: B Rationale: The? quantifier makes the immediately preceding token optional. Here it follows "s", so the pattern matches both "DNS Server:" and "DNS Servers:". It does not repeat the whole group (that would require * or + after a group) and does not escape characters. Q22. What does \s match in a regular expression? A. Zero or more whitespace characters B. One or more digits C. A literal asterisk D. A newline only Answer: A Rationale: \s matches any whitespace character (space, tab, newline), and * means zero or more repetitions. Together, \s matches any amount of whitespace including none, which is useful for tolerating variable spacing after colons in command output. It does not match digits or literals.* Q23. What does the character class [0-9.]+ match? A. One or more characters that are digits or dots B. Exactly one digit C. A single dot D. Any character except digits and dots Answer: A Rationale: [0-9.] defines a character class containing digits 0-9 and the dot. The
is commonly used to capture IPv4 addresses, though it also matches malformed strings like "1.2.3." which is why additional validation is recommended. Q24. Why might a regex-based parser miss DNS servers on some devices? A. Regex cannot match IP addresses B. Output format may vary between distributions or versions C. Python does not support regex D. DNS servers are encrypted Answer: B Rationale: Different Linux distributions and resolvectl versions may format output differently — using "DNS Server:" versus "Current DNS Server:", different indentation, or IPv6 addresses. A regex tuned to one format may fail on another, which is why parsers should be tested against real output and made tolerant of variations. Q25. What should a DNS audit script do when a device is unreachable? A. Crash immediately B. Record the device as unreachable and continue with remaining devices C. Retry forever D. Delete the device from inventory Answer: B Rationale: Robust automation isolates failures per device. When a device is unreachable, the script should log the failure with a timestamp and continue processing the rest of the inventory. Crashing or retrying forever wastes time; deleting from inventory is destructive and removes the record needed for follow-up. Q26. Which Python construct best isolates per-device failures in an audit loop?
Unix service, log is not a standard module, and print is a built-in function, not a logging framework. Q29. What does logging.basicConfig(filename="audit.log", level= logging.INFO ) do? A. Prints logs to the console only B. Configures logging to write INFO and above to audit.log C. Deletes audit.log D. Encrypts audit.log Answer: B Rationale: basicConfig with filename directs log records to the specified file, and level= logging.INFO sets the threshold so INFO, WARNING, ERROR, and CRITICAL are recorded while DEBUG is suppressed. It does not delete or encrypt the file, and specifying filename overrides console output unless a StreamHandler is also added. Q30. Why should credentials not be hardcoded in source code? A. It slows the script B. It exposes secrets in version control and to anyone with repo access C. Python cannot read hardcoded strings D. It causes syntax errors Answer: B Rationale: Hardcoded credentials end up in Git history, where they persist even after removal and are visible to anyone with repository access. Best practice is to supply credentials at runtime via environment variables, getpass, or a secrets manager. Hardcoding does not affect speed or cause syntax errors. Q31. Which function prompts for a password without echoing it to the terminal? A. input() B. getpass.getpass()
C. raw_input() D. sys.stdin.read() Answer: B Rationale: getpass.getpass() reads a line from the terminal with echo disabled, so the password is not displayed. input() echoes characters, raw_input() is Python 2 only, and sys.stdin.read() reads until EOF with echo enabled. Using getpass protects credentials during interactive runs. Q32. What is the recommended way to pass credentials to a script in CI/CD? A. Hardcode them in the script B. Use environment variables or a secrets manager C. Commit them to a private repo D. Email them to the team Answer: B Rationale: CI/CD systems provide environment variables and secret stores (such as GitLab CI variables or Vault) that inject credentials at runtime without exposing them in code. Hardcoding, committing to a repo — even private — or emailing are all insecure practices that risk credential leakage. Q33. What does a CLEAN classification mean in a DNS audit? A. The device has no DNS servers configured B. Observed DNS servers exactly match the approved baseline C. The device is unreachable D. The device has partial DNS configuration Answer: B Rationale: CLEAN means the set of DNS servers observed on the device equals the approved set with no extras and no missing entries. No DNS servers configured would be a misconfiguration, unreachable is a separate status, and partial describes a different classification.
changes, the raw output reveals what actually appeared, enabling the parser to be fixed. It is not a Python requirement and does not encrypt anything. Q37. What does the subprocess.run() function do? A. Runs a Python function in a thread B. Executes an external command and waits for it to complete C. Compiles Python source D. Opens a network socket Answer: B Rationale: subprocess.run() launches an external program, waits for it to finish, and returns a CompletedProcess object containing returncode, stdout, and stderr. It does not run Python functions, compile source, or open sockets — though the executed command may itself use sockets. Q38. What does capture_output=True do in subprocess.run()? A. Redirects output to a file B. Captures stdout and stderr into the returned object C. Suppresses all output D. Encrypts output Answer: B Rationale: capture_output=True (equivalent to setting stdout=PIPE and stderr=PIPE) captures the child process's standard output and standard error into the CompletedProcess object's stdout and stderr attributes. It does not redirect to a file, suppress output entirely, or encrypt anything. Q39. What does text=True do in subprocess.run()? A. Writes output as bytes B. Decodes output as text using the default encoding
C. Sends text to the terminal D. Enables text-to-speech Answer: B Rationale: text=True (or universal_newlines=True) decodes stdout and stderr from bytes to str using the platform's default encoding, so the caller receives strings instead of bytes. Without it, output is bytes and must be decoded manually. It does not send text to the terminal or enable speech. Q40. What does subprocess.run() return? A. A string B. A CompletedProcess object C. An integer D. A boolean Answer: B Rationale: subprocess.run() returns a CompletedProcess instance with attributes returncode, args, stdout, and stderr. The returncode is an integer accessed via that object, not returned directly. A boolean is not returned; success is determined by checking returncode. Q41. Why is check=True sometimes dangerous in subprocess.run()? A. It disables output capture B. It raises CalledProcessError on non-zero exit, halting the script C. It encrypts the command D. It runs the command twice Answer: B Rationale: With check=True, a non-zero exit code raises CalledProcessError, which — if unhandled — terminates the script. In an audit loop, a single ping failure would abort the entire run. Most audit scripts instead inspect returncode manually or catch the exception per device.
subprocess.run's timeout parameter, or both — ensures the script proceeds even when a host is down. Q45. What exception does subprocess.run(timeout=N) raise when the command exceeds N seconds? A. TimeoutError B. subprocess.TimeoutExpired C. socket.timeout D. KeyboardInterrupt Answer: B Rationale: subprocess.run raises subprocess.TimeoutExpired when the timeout elapses, and it kills the child process before raising. TimeoutError is a broader built-in, socket.timeout is socket-specific, and KeyboardInterrupt is user- initiated. Catching TimeoutExpired lets the script mark the device unreachable and continue. Q46. Which module is used for DNS resolution in Python's standard library? A. dns B. socket C. http D. ssl Answer: B Rationale: The socket module provides gethostbyname(), getaddrinfo(), and related functions for resolving hostnames. The dnspython library (imported as dns) is third-party and not part of the standard library. http and ssl handle different concerns. Q47. What does socket.gethostbyname(" example.com ") return?
A. A list of all IPs B. A single IPv4 address as a string C. The MX record D. The hostname Answer: B Rationale: gethostbyname returns one IPv4 address as a string, raising socket.gaierror if resolution fails. For all addresses including IPv6, use getaddrinfo. It does not return MX records — that requires a DNS library like dnspython. Q48. What exception does socket.gethostbyname raise when resolution fails? A. socket.error B. socket.gaierror C. ValueError D. NameError Answer: B Rationale: socket.gaierror (getaddrinfo error) is raised for DNS resolution failures such as unknown hosts or temporary resolver failures. socket.error is a deprecated alias, ValueError is for type/conversion issues, and NameError is for undefined variables. Q49. Why should an audit script avoid resolving the same hostname repeatedly? A. It causes memory leaks B. It wastes time and may trigger rate limiting C. It changes the DNS server D. It corrupts the inventory Answer: B Rationale: Repeated resolution is inefficient and, in some environments, can trigger DNS rate limiting or caching anomalies. Caching results within a run or resolving once per device reduces load and speeds up the audit. It does not cause memory leaks, change DNS servers, or corrupt inventory.