eECHO BLOG

A journey of a thousand miles starts with a single step.

python ssh

I have research on how to access ssh using python:

1. Twisted – an event-driven networking engine written in Python.
2. Paramiko – implements the SSH2 protocol for secure connections to remote machines.
3. Pexpect – spawn a child application and control it as if a human were typing commands.

Three libraries have used different approach to gain access to ssh, and finally I choose pexpect for the simplicity. This post will briefly shows you how easy you can access ssh with pexpect module.

http://pypi.python.org/pypi?%3Aaction=search&term=pexpect&submit=search

#!/usr/bin/env python
import pexpect

# my ssh command line
p=pexpect.spawn('ssh -i /home/sdergats/.ssh/known_hosts root@brutus cat /proc/sys/net/ipv6/conf/eth1/mtu')
ssh_newkey = "Are you sure you want to continue connecting"
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
    #print "I say yes"
    p.sendline('yes')
    i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
    #print "I give password",
    p.sendline("nucleus")
elif i==2:
    print "I either got key or connection timeout"
    pass

print p.read()

http://linux.byexamples.com/archives/346/python-how-to-access-ssh-with-pexpect/

Comments are closed.