ssh to cisco router with python cmd script and save to file.txt

Python is a strong language to do any thing you want. If you want to make a program which will take router backup in a file with scheduled time. You can also use current date as concurrent with file name.

First you need to import “paramiko” library for ssh client.

You can also import datetime for naming the file with creation date.

Use below py codes which is complete with file output in the same directory. You can change the directory if you want.

import paramiko
import datetime


ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())


hostname = '192.168.200.2'
username = 'noc'
password = 'noc123'
port = 22


ssh.connect(hostname, port, username, password, look_for_keys=True)

stdin,stdout,stderr = ssh.exec_command('show run')
output = stdout.readlines()


date = datetime.datetime.now()
f = open('Core-01__'+date.strftime("%d %B %Y")+'.txt','w')
f.write(''.join(output))
print('Write successfull')
f.close()

Above python script will use ssh to login to router having IP 192.168.200.2 with user noc and password noc123. it will write “show running-config” to a file named “Core-01__date”.

Hope you will find this useful.