How to sending commands to multiple devices with python

In this tutorial, we will learn How to send commands to multiple devices with python where we use network communication protocol(NCP) such as SSH( secure shell) or telnet for establishing the connection to the devices and start communication.

Here we have mentioned some of the basic approaches by using the paramiko library for SSH communication.


Commands To Stablish Connections

To establish this we need to follow certain steps which we have explained below and follow those steps to get through. Which starts with Installing Paramiko.

  1. Install Paramiko:

As it is a library that is used for establishing connections by the implementation of the SSH protocol. which you can install it using pip:

pip install paramiko
  1. Define a list of Devices and Their Credentials:

Create a list of devices that you want to send commands to, along with the corresponding login credentials (username, password, and/or SSH key). For example:

devices = [    {'host': '', 'username': 'admin', 'password': 'password1'},    {'host': '', 'username': 'admin', 'password': 'password2'},    {'host': '', 'username': 'admin', 'password': 'password3'}]
  1. Create A Functions For Send Commands:

Create a function that uses Paramiko to establish an SSH connection with a device, send a command, and return the output. here we have given an example:

import paramiko

def send_command( device, command):
    ssh = paramiko. SSHClient()
    ssh. set_ missing_ host_ key_ policy( paramiko. AutoAddPolicy())
    ssh. connect( hostname= device['host'], username= device[' username'], password= device[' password'])
    stdin, stdout, stderr = ssh.exec_command( command)
    output = stdout. read(). decode('utf-8')
    return output

It is used for taking the device dictionary and command string as arguments established by SSH connections with the device using the authenticated credentials.

Now as the last step, we need to send the command for the same.

  1. Send Commands To All the selected  Devices:

We can apply the loop for getting and keep on sending the command to different devices and for the same follow the code given below:

for device in devices:
    output = send_ command( device, 'show interfaces')
    print( device[ 'host'])
    print( output)

The above code would send the show interface command to each and every device and print the output of each on the console.


To learn more about How to send commands to multiple devices with python visit: How to send commands to multiple devices with python.

To learn more about python problems and their solutions along with the concepts you may visit: Python Tutorials And Problems.

To learn more about different programming languages as tutorials and solutions for problems you may visit: beta python programming languages Solutions.

Leave a Comment

%d bloggers like this: