Skip to content

Connect to SSH using Python

Good Night,

If you want to execute commands in console using python you can use the pexpect library. You can get it in http://sourceforge.net/projects/pexpect/. To install it use:

$ sudo python setup.py install

After install it, you can have fun. I did a small script to test it.

[code lang=”python”]import pexpect

class SSH():
def connect(self):
x = True
sshConnection = pexpect.spawn(‘ssh -l matheus -p 22 192.168.0.254’)
sshConnection.expect(‘[email protected]\’s password:’)
sshConnection.sendline(‘password’)
while True:
print sshConnection.readline();
if x is True:
sshConnection.sendline(‘uptime’)
x = False
sshConnection.readline();

s = SSH()
s.connect()[/code]

If you have any problem try to use:

$ sudo apt-get install python-dev

Example connect to SSH using Python

Matheus

Published inpython

65 Comments

  1. I don’t even know how I ended up here, but I thought
    this post was good. I don’t know who you are but certainly
    you are going to a famous blogger if you aren’t
    already 😉 Cheers!

Leave a Reply

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