Python pexpect – (password and password less authentication by ssh and do remote task)

This code use pexpect module of python to perform the operation.

 


#v1.0 - to supply password and login

import sys
import pexpect

user = 'user'
password = 'password'
host = 'host1.us.com'
command = 'hostname ; echo $?'
def dossh(user, password, host, command):
        child = pexpect.spawn('ssh %s@%s %s' % (user,host,command),logfile=sys.stdout,timeout=None)
          prompt = child.expect(['password:', r"yes/no",pexpect.EOF])
if prompt == 0:
        child.sendline(password)
elif prompt == 1:
        child.sendline("yes")
        child.expect("password:", timeout=30)
        child.sendline(password)
        data = child.read()
        print data
        child.close()

dossh(user, password, host, command)

Using the sys module this can be further enhanced to pass the arguments in argv[n].

Here logs will be written in stdout but it can be changed to any logfile.

Also this can be modified to perofrm scp operation or any othere complex command on remote server. Correct the indentation after copying the code.

or any other expected prompt can be added in the  list and value can be passed as required.

Its enhanced here to handle passwordless authentication as well.

#!/usr/bin/env python
#v1.1 - To handle both password and passwordless authentication 
import sys
import pexpect

user = 'user1'
password = 'welcome1'
host = sys.argv[1]
command = 'hostname; whoami; echo $?'

def dossh(user,password,host,command):
    try:
        child =  pexpect.spawn("ssh  -o ServerAliveInterval=100 -n %s@%s '%s'" % (user,host,command),logfile=sys.stdout,timeout=None)
        i = child.expect(['password:', r'\(yes\/no\)',r'.*[$#] ',pexpect.EOF])
        if i == 0:
                child.sendline(password)
        elif i == 1:
                child.sendline("yes")
                ret1 = child.expect(["password:",pexpect.EOF])
                if ret1 == 0:
                        child.sendline(password)
                else:
                        pass
        else:
                pass
        data = child.read()
        print data
        child.close()
        return True
    except Exception as error:
        print error
        return False

dossh(user, password, host, command)
Advertisements

About Divyashree - The GNULINUX Guy

I am a Linux and Opensource enthusiast. I started working on Linux early in 2007 while I was doing my Masters in Computer Science and passed out in 2010. Currently working as a DevOps in in Public/Private cloud domain. my @github : https://github.com/kumarprd my @nagiosexchange : https://exchange.nagios.org/directory/Owner/divyaimca/1 my @linkedin : https://www.linkedin.com/in/priyadarshee-kumar-☁-a9415615
This entry was posted in Programming, TIPS & T RICS, Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s