Beginner Python Script to ssh into remote network device and run multiple commands

1.9k Views Asked by At

Please pardon me as I am a very new to any programming language. I have around 25 network devices combination of cisco, juniper, linux etc which i need to remotely access and run some basic cli commands to get the output. Individually SSHing in to the devices will take long time. Can some tell me where to start this basic script?

2

There are 2 best solutions below

0
On

Try the following:

pip install paramiko

then in your script:

import base64
import paramiko
key = paramiko.RSAKey(data=base64.b64decode(b'AAA...'))
client = paramiko.SSHClient()
client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
client.connect('ssh.example.com', username='strongbad', password='thecheat')

def run_command(command)
    stdin, stdout, stderr = client.exec_command(command)
    for line in stdout:
        print('... ' + line.strip('\n'))
    return True

run_command('ls')
run_command('cd..')
run_command('apt-get update')


client.close()
0
On

You can use Netmiko or NAPALM.

These two python libraries support almost all different vendor devices.

https://napalm.readthedocs.io/en/latest/index.html

https://pynet.twb-tech.com/blog/automation/netmiko.html