Table of Contents
Getting Started with Netmiko
Netmiko is a Python library that makes it much easier to connect to network devices over SSH and run commands programmatically. It is built on top of another library called Paramiko and adds network specific features, such as handling different device types, dealing with interactive prompts, and simplifying configuration changes. In the context of network automation, Netmiko is often one of the first practical tools beginners use to talk to real routers and switches with code.
This chapter focuses specifically on Netmiko. It assumes you already understand why automation matters and have basic familiarity with Python from previous chapters in this section. Here you will see how Netmiko is used to connect to devices, execute commands, and apply changes in a simple and controlled way.
What Netmiko Is Good At
Netmiko is designed to solve a very practical problem. Network devices often do not have modern APIs, but nearly all of them support SSH to provide a command line interface. Manually logging in to dozens or hundreds of devices to run the same checks or changes is very slow and error prone. Netmiko lets you:
Connect to many different vendors with a consistent Python interface.
Run show commands and capture the output as text for later processing.
Enter configuration mode and send configuration commands in bulk.
Handle device prompts and timing issues that are common on network CLIs.
Because of its vendor support and simplicity, Netmiko is especially popular for Cisco, Juniper, Arista, HP, and many others. For absolute beginners, it provides a gentle introduction to real world automation without requiring you to redesign your entire network or deploy complex APIs.
Installing and Setting Up Netmiko
To use Netmiko you need a working Python environment and the ability to reach your network devices over SSH. The actual installation is straightforward using the Python package manager.
To install Netmiko, you typically use:
pip install netmikoIn some environments you might use:
pip3 install netmikoafter you have installed Python 3.
Once installed, you import it in your Python script. The most commonly used import is:
from netmiko import ConnectHandler
The ConnectHandler function is the main entry point. It creates an SSH connection to your network device and returns an object that you can use to send commands.
You do not need to install a separate SSH library. Netmiko bundles the necessary dependencies and handles the SSH session for you.
Defining Device Connections
Before Netmiko can connect to a device, you must describe that device in Python. Netmiko typically uses a Python dictionary to hold connection parameters. These parameters depend on the device type and the credentials you use.
A basic device definition looks like this:
from netmiko import ConnectHandler
device = {
"device_type": "cisco_ios",
"host": "192.0.2.10",
"username": "admin",
"password": "MyPassword123",
"secret": "MyEnablePassword",
}
The device_type value tells Netmiko how to talk to the device. It includes details such as how to enter configuration mode and how prompts look. Some common device_type values include:
| Vendor / OS | Example device_type value |
|---|---|
| Cisco IOS | cisco_ios |
| Cisco NX-OS | cisco_nxos |
| Cisco ASA | cisco_asa |
| Juniper Junos | juniper |
| Arista EOS | arista_eos |
| HP ProCurve | hp_procurve |
You do not have to memorize these. They are documented in Netmiko and can be looked up when needed. The important point is that the correct device_type enables Netmiko to adapt to vendor specific CLI behavior.
The host, username, and password fields are straightforward. The secret is often used for enable mode on Cisco style devices. If your device does not require an enable password, you can omit secret or leave it empty.
Connecting and Running Show Commands
Once a device dictionary is defined, you can open an SSH connection and run commands. Netmiko returns an object that represents the active connection and provides several methods to interact with the device.
A typical pattern for running a show command is:
from netmiko import ConnectHandler
device = {
"device_type": "cisco_ios",
"host": "192.0.2.10",
"username": "admin",
"password": "MyPassword123",
"secret": "MyEnablePassword",
}
connection = ConnectHandler(**device)
connection.enable() # enter privileged mode if required
output = connection.send_command("show ip interface brief")
print(output)
connection.disconnect()Here is what happens step by step:
Netmiko uses ConnectHandler(**device) to create an SSH session using the details in the dictionary.
If the device has an enable mode, connection.enable() enters that mode so you have full access to privileged commands.
The send_command method sends a command exactly as you would type it on the CLI. It waits for the device to respond and then returns the full text output as a Python string.
You can then print or process the output. For example, you could search for a particular interface or status.
Finally, connection.disconnect() closes the SSH session cleanly.
For absolute beginners, it is important to see that this entire flow is not fundamentally different from typing into a terminal, except that the interaction is now performed by a script. This means you can repeat it, scale it to many devices, and integrate it into larger tools.
Sending Configuration Changes
Netmiko can also apply configuration changes. Instead of manually entering configuration mode and typing each command, you can provide a list of configuration commands and let Netmiko send them one after another.
The key method for this is send_config_set. Example:
from netmiko import ConnectHandler
device = {
"device_type": "cisco_ios",
"host": "192.0.2.10",
"username": "admin",
"password": "MyPassword123",
"secret": "MyEnablePassword",
}
connection = ConnectHandler(**device)
connection.enable()
config_commands = [
"interface GigabitEthernet0/1",
"description Connected to Server A",
"switchport mode access",
"switchport access vlan 10",
]
output = connection.send_config_set(config_commands)
print(output)
connection.disconnect()
Netmiko automatically enters configuration mode before sending the list, then exits when done. The returned output contains both the commands and the device replies, similar to what you would see in a live session.
You can also load configuration commands from a file and pass them into send_config_set after reading them into a list of strings. This is useful for standardized templates.
Important rule: When using Netmiko for configuration changes, always test your scripts in a lab environment before running them on production devices. Simple mistakes in a script can be multiplied across many devices very quickly.
Handling Multiple Devices
One of the main reasons to use Netmiko is the ability to run the same tasks across many devices. This is often done by storing multiple device dictionaries in a list and looping over them.
Here is a simple example that runs a show command on several devices:
from netmiko import ConnectHandler
devices = [
{
"device_type": "cisco_ios",
"host": "192.0.2.10",
"username": "admin",
"password": "MyPassword123",
"secret": "MyEnablePassword",
},
{
"device_type": "cisco_ios",
"host": "192.0.2.11",
"username": "admin",
"password": "MyPassword123",
"secret": "MyEnablePassword",
},
]
for device in devices:
connection = ConnectHandler(**device)
connection.enable()
output = connection.send_command("show version | include uptime")
print(f"Device {device['host']} uptime:")
print(output)
print()
connection.disconnect()In this pattern, the code is almost the same as the single device case. The only difference is that you run it in a loop over each device dictionary in the list. This illustrates how Netmiko combines well with basic Python concepts like lists and loops to build useful automation quickly.
As you gain experience, you can extend this approach with error handling to deal with timeouts or authentication failures, and with more advanced Python techniques such as parallel execution. However, the fundamental Netmiko behavior stays the same.
Working With Prompts and Timing
Network devices often have interactive prompts, such as confirmations for reload commands or warnings. Netmiko includes methods to handle these cases. For simple show and configuration commands, you usually do not need to worry about prompts. For more complex interactions, Netmiko offers send_command_timing and send_command with an expect_string parameter.
send_command_timing does not try to match the device prompt. Instead, it sends a command, waits a short period, returns output, and lets you send further input based on that. This is useful when the device behavior is not predictable.
For example, when a command triggers a yes or no confirmation, you could do:
output = connection.send_command_timing("reload")
if "Proceed with reload" in output:
output += connection.send_command_timing("y")
print(output)For beginners, it is enough to understand that Netmiko can go beyond simple one line commands when needed. You do not have to manually manage SSH channels or low level bytes. Instead, you stay focused on the logical interaction.
Basic Error Handling and Safety
When connecting to real devices, some connections will fail. The host may be unreachable, credentials might be wrong, or SSH might be disabled. Netmiko raises Python exceptions in such cases. You can catch these exceptions to prevent your script from crashing halfway through a batch of devices.
An example with simple error handling:
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetmikoTimeoutException, NetmikoAuthenticationException
device = {
"device_type": "cisco_ios",
"host": "192.0.2.99",
"username": "admin",
"password": "WrongPassword",
}
try:
connection = ConnectHandler(**device)
output = connection.send_command("show ip interface brief")
print(output)
connection.disconnect()
except NetmikoTimeoutException:
print(f"Timeout connecting to {device['host']}")
except NetmikoAuthenticationException:
print(f"Authentication failed for {device['host']}")
Using try and except in this way allows you to log problems without stopping your entire automation run. As your automation grows, you can expand this with better logging and reporting, but the core idea is the same.
Important rule: Always include at least basic error handling in Netmiko scripts that run against multiple devices. Without it, a single failing device can interrupt the whole process.
When to Use Netmiko
Netmiko is particularly suitable when:
You work with traditional CLI based devices that do not have rich APIs.
You want to automate existing commands you already know from the terminal.
You are starting in network automation and want a simple path from manual work to scripts.
You need quick one off tools to collect information across many devices.
There are other tools in the automation ecosystem that focus on configuration models, idempotence, or full infrastructure as code. Those are covered in different chapters. Netmiko complements them by providing a direct way to talk to the CLI, which is often still necessary in mixed or older environments.
In practice, many engineers start with small Netmiko scripts to gain confidence, then later integrate Netmiko into larger solutions or migrate parts of the workflow to more advanced tools. For an absolute beginner, building a simple script that logs in to a device and runs a show command is an excellent first milestone.
Summary
Netmiko provides a practical bridge between manual CLI work and Python based automation. You have seen how to install it, describe devices in dictionaries, establish SSH connections, run show commands, apply configuration changes, loop over multiple devices, and handle basic errors. With this foundation, you can start building small scripts that save you time and reduce repetitive tasks, while still working with the familiar network CLI.