«

»

Aug 05

SSH access via Python Script

python_logo

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

Follow me!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>