SSH Connection to Multiple Devices with Paramiko

Tolga Koca
2 min readMay 5, 2023

--

In this example, we connect multiple network devices and collect different command logs. We use SSH to login to the devices with the paramiko module. So, you can run this code for any device with an SSH connection.
In the “SSH Connection to a Device with Paramiko” article, we deeply explain all the lines. So, if you don’t know about the following codes, you can check that article.

We import the necessary modules first. Then, we define the IP addresses and commands we run on the device as a list. We create “hosts” and “command_list” variables.

import paramiko
import time

hosts = ["10.1.1.1","10.1.1.2","10.1.1.3"]
command_list = ["show version", "show clock", "show ip route"]

Now, we can login to the devices. We use the “for” loop to login devices and run commands one by one. There are 2 for loops, outer and inner loops, and it’s a nested loop structure in Python. In the outer or 1st loop, we get the 1st iterable “10.1.1.1” from the “hosts” variable. So, we login to the device with the 1st loop. After all, lines finish with the “invoke_shell” function. We are inside the device to execute commands.

for ip in hosts:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect (ip,22,"user","pass")
commands = client.invoke_shell()

Then, we continue with the 2nd or the inner loop. It gets the 1st iterable of the “command_list” variable as “show version”. Then, it will execute and display the output of this command.
After that, the 1st iterable is finished. But we have 2 more items in the “command_list”. So, the code gets the 2nd iterable as “show clock” and does the same process, and it continues until all tables are executed.

for command in command_list:
commands.send(f"{command} \n")
time.sleep(2)
output = commands.recv(1000000)
output = output.decode("utf-8")
print(output)

We are still in the 1st iterable of the outer loop. So, all those commands are executed on “10.1.1.1”. After the inner loop finishes, the code gets the 2nd iterable of the “hosts” variable, which is “10.1.1.2”. It executes the same commands on that device now. This will continue until all the outer loop items are performed on the code.

So, in the output, we can see all of the show command outputs of all devices. We can put them in separate files to save in the local directory.

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:

--

--