Friday, December 01, 2006

scp using Python and pexpect

Following is the python script which shows how to Copy file from another machine using pexpect.
Script uses pexpect and you should have it installed before you try it.

Idea is enter all the errors etc in a list which then is passed to pexpect. Then on certain conditions the functions is recursively called e.g. After receiving "....continue (yes/no)?" script sends "yes" and then calls itself again. Next time it gets "[Pp]assword", sends password and then calls itself again.

If any of the errors ( res >= 4 ) it returns False.

Copy the following script in a file and sun with the filename parameter.

e.g. scp.py hello.tgz

-----Script Follows----------



#!/usr/bin/python
# Python SCP and Expect Example 1.0
# Author: Arvind Deshpande
# License: GPL http://www.gnu.org/licenses/gpl.txt

#from pexpect import pexpect
import pexpect
import sys
import time
import os

expectations = ['[Pp]assword',
'continue (yes/no)?',
pexpect.EOF,
pexpect.TIMEOUT,
'Name or service not known',
'Permission denied',
'No such file or directory',
'No route to host',
'Network is unreachable',
'failure in name resolution',
'No space left on device'
]

def fetchFileSCP(child=None, *args):
print "Received Args:",child, args
try:
if not child:
child = pexpect.spawn( 'scp -r USER@SERVER.COM:%s /HOME/USER/'%(args[0]))
res = child.expect( expectations )
print "Child Exit Status :",child.exitstatus
print res,"::",child.before," :After:",child.after
if res == 0:
child.sendline('XXXXXXXX')
return fetchFileSCP(child,None)
if res == 1:
child.sendline('yes')
return fetchFileSCP(child,None)
if res == 2:
line = child.before
print "Line:",line
print "Now check the result and return status."
if res == 3:
print "TIMEOUT Occurred."
child.kill(0)
return False
if res >= 4:
child.kill(0)
print "ERROR:",expectations[res]
return False
return True
except:
import traceback; traceback.print_exc()
print "Did file finish?",child.exitstatus

if __name__ == '__main__':
stat = True
stat = fetchFileSCP(None,sys.argv[1])
if stat:
print "File Transferred successfully."
else:
print "Failure while copying files securely."

No comments: