In the modern network, automation isn't a luxury—it's a necessity. Cisco's CCNA 200-301 exam objective 6.5 introduces Python network automation, reflecting the industry's shift toward programmable infrastructure. This chapter equips you with the Python skills to interact with network devices via SSH, parse structured data, and automate repetitive tasks. Mastering these concepts not only helps you pass the exam but prepares you for real-world network engineering where manual CLI entry is being replaced by scripts and APIs.
Jump to a section
Imagine you're the head chef at a busy restaurant. Every morning, you must prepare 50 identical salads. Doing each one manually—washing, chopping, dressing—takes forever and risks inconsistency. Now, you hire a robot chef. The robot doesn't know how to make a salad by itself, but it can follow a recipe card precisely. You write one recipe card: 'Step 1: Wash lettuce. Step 2: Chop tomatoes. Step 3: Add dressing. Step 4: Toss.' The robot executes these steps on command, every time, without boredom or mistakes.
In network automation, the network device (switch, router) is the robot. It can execute commands but doesn't know the 'recipe' for a configuration. Python acts as the chef who writes the recipe and sends instructions to the robot. The robot's 'hands' are SSH or APIs—the methods by which it receives commands. Just as the robot needs a power source and a way to read the recipe card (e.g., a USB stick), the network device needs an IP connection and a transport protocol (SSH, NETCONF, RESTCONF) to receive instructions.
If the robot's recipe card has a typo—'Chop tomatos' instead of 'tomatoes'—the robot might fail or produce a weird result. Similarly, if your Python script has a syntax error or sends a malformed command, the device might reject it or misconfigure. The robot chef doesn't taste the salad; it just follows orders. Likewise, network automation scripts don't 'understand' the network state—they execute commands based on what you programmed. So you must build in verification steps (like having the robot check that the bowl isn't empty) to ensure the desired outcome. This analogy captures the essence: automation is about delegating repetitive, precise tasks to a program that executes reliably, freeing you to focus on design, troubleshooting, and innovation.
What is Python Network Automation?
Python network automation refers to using the Python programming language to interact with network devices programmatically. Instead of typing commands one by one into a terminal, you write scripts that connect to devices, execute commands, and process the output. This is part of the broader DevOps and NetOps movement, where infrastructure is managed as code.
For the CCNA 200-301 exam, objective 6.5 specifically covers: "Interpret basic Python scripts using the following:
Variables - Strings - Numbers - While loops - For loops - If/else - Dictionaries - Lists - Functions - Libraries (paramiko, netmiko, requests)". The exam expects you to read and understand simple Python scripts that automate network tasks, not to write complex programs from scratch. You must know how to use common libraries like paramiko (SSH), netmiko (simplified SSH for network devices), and requests (HTTP for REST APIs).
Why Python for Networking?
Python is the de facto language for network automation because of its readability, extensive library support, and large community. Key libraries include: - paramiko: Low-level SSH implementation. You handle authentication, channel, and command execution manually. - netmiko: Built on paramiko, it simplifies SSH connections to network devices. It handles SSH negotiation, authentication, and command execution with a consistent interface across vendors. - requests: Used for REST API calls (e.g., to Cisco DNA Center, Meraki, or NX-API). - json: Parses JSON data, commonly returned by APIs. - re: Regular expressions for parsing unstructured text output.
How Python Interacts with Network Devices
At the packet/frame level, Python scripts typically use SSH (TCP port 22) to connect to a device's management IP. The script opens a socket, performs SSH key exchange, authenticates, and opens a shell channel. Commands are sent as strings over the encrypted channel, and the device's response (usually text) is read back. For example, a netmiko script sends "show ip interface brief" and captures the output as a string.
For API-based automation, the script sends HTTP/HTTPS requests (e.g., GET, POST) to the device's REST API endpoint. The device responds with structured data (JSON or XML). This is more efficient than screen-scraping because the data is machine-readable.
Key Python Constructs for CCNA
Variables: Store data like strings, numbers, lists, dictionaries. Example: hostname = "R1"
Strings: Text enclosed in quotes. Used for commands and device responses. Methods like .strip(), .split() are common.
Numbers: Integers and floats. Used for counters, timeouts.
While loops: Repeat a block while a condition is true. Often used to keep a script running until a condition is met.
For loops: Iterate over a sequence (list, string). Used to apply commands to multiple devices.
If/else: Conditional execution. Used to check command output for errors.
Dictionaries: Key-value pairs. Often used to store device credentials or parsed data.
Lists: Ordered collections. Used to store multiple device IPs or command outputs.
Functions: Reusable blocks of code. Used to organize tasks like connecting to a device.
Libraries: Imported modules that add functionality. import paramiko, from netmiko import ConnectHandler.
Example: Simple SSH Script with Netmiko
from netmiko import ConnectHandler
device = {
'device_type': 'cisco_ios',
'host': '192.168.1.1',
'username': 'admin',
'password': 'cisco123',
}
connection = ConnectHandler(**device)
output = connection.send_command('show ip interface brief')
print(output)
connection.disconnect()This script imports the ConnectHandler class, defines device parameters in a dictionary, establishes an SSH connection, sends a command, prints the output, and closes the connection. The send_command() method waits for the device prompt before returning.
Parsing Output
Raw text output from show commands is often messy. To extract specific data, you can use string methods or regular expressions. For example, to get the IP address of an interface:
import re
output = connection.send_command('show ip interface brief')
match = re.search(r'GigabitEthernet0/1\s+(\S+)', output)
if match:
ip = match.group(1)
print(ip)Alternatively, use textfsm (not in CCNA scope but useful) or structured output from APIs.
API Example with requests
import requests
url = "https://192.168.1.1/api/interface"
headers = {"Accept": "application/json"}
response = requests.get(url, auth=("admin", "cisco123"), verify=False)
data = response.json()
print(data)Note: verify=False disables SSL certificate verification (common in lab environments). In production, use proper certificates.
Key IOS CLI Verification Commands
While Python is the automation tool, you still need to verify device connectivity and configuration manually. Use:
- show ip ssh: Verify SSH server status.
- show ip interface brief: Check interface IPs.
- show running-config | include username: Confirm user accounts.
- debug ip ssh: Troubleshoot SSH connections (use with caution).
Interaction with Related Protocols
Python automation relies on underlying protocols like SSH (for secure CLI access), SNMP (for monitoring), and NETCONF/RESTCONF (for model-driven programmability). The CCNA exam expects you to understand that Python can leverage these protocols via libraries. For example, pysnmp is a Python library for SNMP, but it's not covered in CCNA; focus on SSH and HTTP-based APIs.
Install Python and Libraries
Before writing scripts, ensure Python 3.x is installed. On Windows, download from python.org. On Linux/Mac, use package manager. Install required libraries via pip: `pip install paramiko netmiko requests`. The CCNA exam does not test installation, but you must know that libraries are imported at the top of scripts. For example: `import paramiko` or `from netmiko import ConnectHandler`. If a library is missing, the script will fail with ImportError.
Define Device Credentials
Create a dictionary with device connection parameters. For netmiko, required keys: `device_type`, `host`, `username`, `password`. Optional: `port` (default 22), `secret` (enable password). Example: `device = {'device_type': 'cisco_ios', 'host': '192.168.1.1', 'username': 'admin', 'password': 'cisco'}`. The `device_type` tells netmiko which terminal driver to use (e.g., `cisco_ios` for IOS, `cisco_ios_telnet` for telnet). Using a dictionary makes it easy to loop over multiple devices.
Establish SSH Connection
Use `ConnectHandler(**device)` to open an SSH connection. The double asterisk unpacks the dictionary as keyword arguments. The connection object (e.g., `connection`) represents the SSH session. Behind the scenes, netmiko handles SSH key exchange, authentication, and enters the device's CLI. If authentication fails, it raises `NetMikoAuthenticationException`. If the host is unreachable, `NetMikoTimeoutException`. Always wrap connection attempts in try/except blocks for production scripts.
Send Commands and Capture Output
Use `connection.send_command('show command')` to execute a single command. The method returns the output as a string. For multiple commands, use `send_config_set(['command1', 'command2'])` for configuration mode. Example: `output = connection.send_command('show ip interface brief')`. The method waits for the device prompt before returning. To handle pagination (e.g., `show running-config`), netmiko automatically uses appropriate terminal length settings.
Parse and Process Output
Raw output can be parsed using string methods like `.splitlines()`, `.find()`, or regular expressions. For example, to extract all interface names: `for line in output.splitlines(): if 'GigabitEthernet' in line: print(line.split()[0])`. Alternatively, use `textfsm` (not in CCNA scope) or structured data from APIs. The exam may ask you to identify what a given script does, so practice reading scripts that parse show command output.
Close the Connection
Always close the SSH connection with `connection.disconnect()`. This frees up resources and avoids leaving stale sessions. In scripts that loop over devices, disconnect after each device or use a context manager (`with ConnectHandler(**device) as connection:`). The exam may present incomplete scripts missing `disconnect()` and ask you to identify the error.
In enterprise networks, Python automation is used for numerous tasks. One common scenario is bulk configuration changes. Imagine you need to update the NTP server on 200 switches. Manually SSHing to each device and typing ntp server 10.10.10.1 would take hours and risk typos. A Python script using netmiko can loop over a list of device IPs, connect, enter config mode, apply the command, and save the config. The script can also verify the change by sending show ntp status and logging any failures.
Another scenario is compliance auditing. A network engineer must ensure all devices have the same ACL applied. Instead of manually checking each device, a script can connect to every device, run show access-lists, and compare the output to a baseline. If a device is missing an entry, the script can log it or even apply the missing ACL automatically. This is often part of a Continuous Compliance pipeline.
A third scenario is backup automation. Every night, a Python script connects to all network devices, runs show running-config, and saves the output to a file named with the device hostname and date. This provides a historical record and aids in disaster recovery. The script can also check for changes by comparing the new backup with the previous one using difflib.
Performance considerations: SSH sessions are resource-intensive. For large networks (thousands of devices), use threading or asynchronous libraries (e.g., asyncio, netmiko's ConnectHandler is not thread-safe, so use a connection pool). Also, be mindful of SSH rate limiting on devices. Misconfigured scripts can lock out administrators by failing authentication repeatedly. Always include error handling and logging. A common mistake is not handling NetMikoTimeoutException for unreachable devices, causing the script to hang. Also, forgetting to set secret for enable mode can leave the device in user exec mode, causing commands to fail silently.
The CCNA 200-301 exam objective 6.5 focuses on interpreting basic Python scripts—not writing them from scratch. You will be given a short script and asked to determine its output, identify an error, or select what it does. The exam expects you to understand the following constructs: variables, strings, numbers, while loops, for loops, if/else, dictionaries, lists, functions, and libraries (paramiko, netmiko, requests).
Common wrong answers and why candidates choose them:
1. Confusing netmiko and paramiko: Candidates often think paramiko is easier because it's lower-level. But netmiko is simpler for network devices. The exam may show a paramiko script with manual channel handling; candidates might misidentify it as netmiko.
2. Misreading loop logic: A for loop over a list of devices might be assumed to run sequentially, but candidates forget that SSH connections can fail, and the script may not handle that. The exam might ask: 'What happens if device 2 is unreachable?' The correct answer is usually 'The script raises an exception and stops' unless there's a try/except.
3. Ignoring the `send_config_set` vs `send_command` difference: send_config_set enters config mode automatically, while send_command stays in exec mode. A script that uses send_command to apply config commands will fail. Candidates often assume any command can be sent with send_command.
4. Forgetting to import libraries: A script that uses ConnectHandler without importing it will raise a NameError. The exam may show a script missing the import line and ask what error occurs.
Specific values and commands to remember:
- The device_type string for Cisco IOS is 'cisco_ios'.
- send_command() returns a string; send_config_set() returns a list of strings (one per command).
- ConnectHandler(**device) is the typical syntax.
- To handle enable mode, include 'secret': 'enable_password' in the device dict.
Decision rule for scenario questions: When asked to choose a script that accomplishes a task, look for correct syntax: dictionary with required keys, proper method calls, and appropriate library import. Eliminate scripts with missing imports, incorrect method names (e.g., send_command misspelled), or wrong device_type. Also, check if the script handles credentials securely (e.g., not hardcoding in a shared script).
Python network automation uses libraries like paramiko (low-level SSH) and netmiko (simplified SSH for network devices).
The netmiko `ConnectHandler` requires a dictionary with `device_type`, `host`, `username`, `password` (and optionally `secret` for enable).
`send_command()` executes a single show command and returns the output as a string.
`send_config_set()` enters config mode and applies a list of configuration commands.
Always close connections with `disconnect()` to free resources.
The `requests` library is used for REST API calls (e.g., GET, POST) with JSON responses.
For loops are commonly used to iterate over a list of device IPs or commands.
The exam tests interpretation of scripts, not writing them from scratch.
These come up on the exam all the time. Here's how to tell them apart.
Paramiko
Low-level SSH library; requires manual SSH client creation and channel handling.
You must handle authentication, shell invocation, and command/response parsing manually.
More flexible but more code and error-prone.
Suitable for non-network SSH tasks or when you need fine-grained control.
Example: `ssh = paramiko.SSHClient(); ssh.connect(...); stdin, stdout, stderr = ssh.exec_command('show version')`
Netmiko
High-level library built on paramiko; provides `ConnectHandler` class.
Automatically handles device prompts, authentication, and command execution.
Vendor-specific device_type ensures correct interaction (e.g., `cisco_ios`, `arista_eos`).
Recommended for network automation; reduces code and errors.
Example: `connection = ConnectHandler(**device); output = connection.send_command('show version')`
Mistake
Paramiko is easier to use than netmiko for network devices.
Correct
Netmiko is built on paramiko and provides a higher-level interface that automatically handles SSH negotiation, authentication, and command execution with vendor-specific prompts. Paramiko requires manual channel management and is more error-prone for beginners.
Candidates often assume lower-level means simpler, but netmiko abstracts away complexity.
Mistake
Python scripts can run directly on a network device without any additional setup.
Correct
Cisco IOS does not have a native Python interpreter. You must run Python on an external host (PC, server) that connects to the device via SSH or API. Some Cisco platforms (like IOS-XE with Guest Shell) support Python on-box, but that is beyond CCNA scope.
Candidates confuse 'automation' with 'embedded scripting' like EEM (Embedded Event Manager).
Mistake
The `send_command()` method can be used to enter configuration mode.
Correct
`send_command()` is for exec mode commands (show commands). To enter config mode, use `send_config_set()` which automatically enters global configuration mode, applies commands, and exits. Using `send_command('configure terminal')` may work but is not the intended method.
Candidates think all commands are sent the same way, ignoring netmiko's design.
Mistake
If a device is unreachable, the script will skip it and continue to the next device.
Correct
By default, netmiko raises an exception (e.g., `NetMikoTimeoutException`) on connection failure, which will stop the script unless a try/except block is used. To skip unreachable devices, you must explicitly catch exceptions and continue.
Candidates assume automatic error handling, but Python scripts require explicit exception handling.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
Paramiko is a low-level SSH library that provides raw SSH access. You must manually handle the SSH client, authentication, channel creation, and command/response parsing. Netmiko is built on top of paramiko and provides a high-level interface specifically for network devices. It handles device prompts, pagination, and vendor-specific quirks. For CCNA, netmiko is preferred because it reduces code complexity. The exam expects you to recognize both, but netmiko is more common in automation scripts.
Include the `'secret'` key in the device dictionary with the enable password. For example: `device = {'device_type': 'cisco_ios', 'host': '...', 'username': 'admin', 'password': 'cisco', 'secret': 'enablepass'}`. When you call `send_command()` or `send_config_set()`, netmiko automatically enters enable mode if needed. If you omit `secret`, commands that require privilege level 15 may fail. The exam may test this by showing a script without `secret` and asking why certain commands fail.
`send_command()` is for exec mode commands (show, ping, etc.). It sends a single command and returns the output. `send_config_set()` is for configuration commands. It automatically enters global configuration mode, applies the list of commands, and exits config mode. It returns a list of strings, one per command. Using `send_command()` for config commands will likely fail because the device remains in exec mode. The exam may ask you to choose the correct method for a given task.
Modern Cisco devices running IOS-XE (like Catalyst 9000 series) support Guest Shell, which is a Linux container that can run Python scripts directly on the device. However, the CCNA exam focuses on external Python scripts that connect to devices via SSH or APIs. You are not expected to know how to run scripts on-box. The exam scenario assumes the script runs on a management host.
The `**` operator unpacks a dictionary into keyword arguments. For example, if `device = {'host': '10.1.1.1', 'port': 22}`, then `ConnectHandler(**device)` is equivalent to `ConnectHandler(host='10.1.1.1', port=22)`. This is a common pattern in Python to pass a variable number of arguments. The exam may test this syntax by asking what the line does.
You can use string methods like `.split()`, `.find()`, or regular expressions with the `re` module. For example, to extract the IP address from 'Gig0/1 10.1.1.1 up', you could use `output.split()[1]` (assuming consistent spacing). For more complex parsing, regular expressions are powerful: `re.search(r'Gig0/1\s+(\S+)', output).group(1)`. The exam may present a script that uses regex and ask for the extracted value.
The `requests` library is used to make HTTP/HTTPS requests to REST APIs. In network automation, it can interact with controllers like Cisco DNA Center, Meraki, or NX-API. For example, you can send a GET request to retrieve interface status as JSON. The exam may show a script that uses `requests.get()` and `response.json()` to parse the response. You need to understand that it returns structured data, not CLI text.
You've just covered Python Network Automation — now see how well it sticks with free CCNA 200-301 practice questions. Full explanations included, no account needed.
Done with this chapter?