Non-Interactive SSH use case with Python
Sometimes the best way to learn to do something useful with a scripting language is with a starting point and a real world use case. While I don’t consider myself a Python expert, I can usually figure out how to put things together and get a task accomplished. For this article I challenged myself to create a simple script that performs the following:
- Open a file for a list of devices and credentials
- Log in to each device in the file using the credentials found
- Remove the current NTP server (1.1.1.1)
- Add a new NTP server (2.2.2.2)
- Save the configuration
I am sharing the script below as an example. Note this Python file uses paramiko. Therefore that library needs to be installed (MAC users – sudo pip install paramiko)
NTPChange.py
import paramiko
####devices.txt format
#### username,password,host
#### username,password,host
qbfile = open("devices.txt", "r")
for aline in qbfile:
values = aline.split(",")
myuser = values[0]
mypass = values[1]
myhost = values[2].rstrip()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(myhost, username=myuser, password=mypass)
channel = ssh.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
conf t
no ntp server Continue reading


