Every network engineer who do some scripting will have to write script to SSH to other host or device.
Luckily there’s no need to write long and complex code to do it as there are tools for this already created, tested and widely used. One I would like to introduce is PXSSH.
Pxssh is based on pexpect. It’s class extends pexpect.spawn to specialize setting up SSH connections. I use pxssh frequently for making ssh connections in python.
Usage example:
import pxssh s = pxssh.pxssh() if not s.login ('localhost', 'myusername', 'mypassword'): print "SSH session failed on login." print str(s) else: print "SSH session login successful" s.sendline ('uptime') s.prompt() # match the prompt print s.before # print everything before the prompt. s.logout() #We can also execute multiple command like this: s.sendline ('uptime;df -h')
More details are available on following websites:
https://pexpect.readthedocs.org/en/latest/api/pxssh.html
http://pexpect.sourceforge.net/pxssh.html