SSH Connection to a Device with Netmiko

Tolga Koca
2 min readMay 7, 2023

--

We can connect network and system devices with SSH protocol. In Python, the most popular connection modules are paramiko and netmiko. In this article, we connect a Cisco router with the netmiko module. You can check paramiko connection articles here:
Connect a single device with paramiko
Connect multiple devices with paramiko

First, we import the “Netmiko” function from the “netmiko” module.

from netmiko import Netmiko

Then, we can define the device information. It’s a dictionary of data types that netmiko can understand. We have the host as the IP address, username, password, and device_type to define the device brand/model/type. Here, the device type is “cisco_ios”. You can check the full list from its documentation. These are the mandatory keys to describe a device. We also have global_delay_factor, which adds a time delay between running the commands on the remote device. We define it as 0.1 seconds.

device = {
"host": "10.1.1.1",
"username": "admin",
"password": "test",
"device_type": "cisco_ios",
"global_delay_factor": 0.1,
}

We can define the commands as variables as below. Or we can define it as a string in the netmiko function. Here, we have a config variable, a list with 2 items. We enter the GigabitEthernet1/2 interface and change the description.
In the command variable, we check the configuration of the GigabitEthernet1/2 interface. So we can verify the changes on the port.

config= ["interface GigabitEthernet1/2", "description new_port"]
command = "show run interface GigabitEthernet1/2"

Now, we can connect to the device with the Netmiko function and bind it to the “net_connect” variable. We call this variable by calling other Netmiko functions. We write ** as a double asterisk and the host variable as the device. In netmiko, code is much more straightforward than in paramiko. With only a single command, we can connect to a device. Netmiko simplifies the connection, which is built on the paramiko module.

net_connect = Netmiko(**device)

Now, we can send the configuration to the device. We call the “send_config_set” function and enter the config variable inside the parentheses. It will execute all commands on the list in order.

config_output = net_connect.send_config_set(config)

Then, we call the “send_command” function. We enter the variable “command” as a string. The “send_command” function doesn’t allow entering a list data type. So, it must be a string. After all, we can disconnect from a device with the disconnect function. Finally, we can print the variables that we bind to the send_command and the send_config_set functions to display the whole output.

show_output = net_connect.send_command(command)
net_connect.disconnect()
print(config_output)
print(show_output)

You can enroll in my “Network Automation with Python” — LIVE training HERE.

For +100 Python networking scripts, check my book HERE.

Here is the full code:

--

--