Saturday, January 4, 2014

Using pexpect (python library) to pass password for password-based SSH authentication

In earlier post, I have talked about the expect tool. see http://khawarblog.blogspot.co.uk/2014/01/using-expect-tool.html. This post provides information about using a python library for the same purpose.
Python provides a library pexpect (https://pexpect.readthedocs.org/en/latest/) that behaves the similar as the expect tool. Since python is a high level language as compared with shell scripting, there is more power available to a user/developer to use it for various complex scenarios. Following is a sample using pexpect. This code launches a SCP command with password and transfers a local file to a remote server.



import pexpect
import sys

"""
username = will be your user
host = hostname or ip address of the remote machine
password = is password for the username on remote machine
"""
user_host="username@host"
user_pass="password"

filename="file path"
child = pexpect.spawn("scp  %s %s:~/" % (filename, user_host) )
#this will print the received output on stdout
child.logfile_read = sys.stdout
#the pseudo terminal waits for a line that ends with password: which is normally the case in ssh
child.expect(".*ssword: $")
#this will send user password to the terminal
child.sendline(user_pass)
#here it waits for EOF output
child.expect(pexpect.EOF)

print '\ndone'

No comments: