Tuesday, 13 August 2013

pexpect-how to handle the permission denied exception

pexpect-how to handle the permission denied exception

The following script is performing scp to target host using the pexpect
module. I want to handle if I get Permission denied exception should try
with local array variable contain list of password and succeeded the scp.
local_pass = ["test123","welcome1","Welcome1"]
def file_copy(user,host,password,logfile,local_file):
print "Connecting to %s as %s" % (host,user)
local_file_copy = local_file
remote_file = os.path.basename(local_file)
print "Performing scp %s %s@%s:/tmp/%s" %
(local_file,user,host,remote_file)
p=pexpect.spawn("scp %s %s@%s:/tmp/%s" %
(local_file,user,host,remote_file))
p.timeout=10
i=p.expect([ssh_newkey,'assword:'],p.timeout)
print "setting log file %s" % (logfile)
fout=file(logfile,'w')
p.logfile=fout
counter=0
if i == 0:
print "yes to continue connecting"
p.sendline("yes");
i=p.expect([ssh_newkey,'assword:'],p.timeout)
if i == 1:
try:
print "entering ssh password %s" % (password)
output=p.sendline(password)
sys.exit(1)
except:
while(counter < 3):
print "Permission Denied...\n"
#p.expect(['Permission denied, please try
again.\r\n'],p.timeout)
p.expect(['assword:'],p.timeout)
p.sendline("%s" %(local_pass[counter]))
print "Attempting to relogin....\n"
print "LOCALPASSWORD : --> %s\n"
%(local_pass[counter])
counter+=1;
j=p.expect("]","#","$")
if j in range(4):
break;
print "returning expect handle"
p.expect(pexpect.EOF)
print "Script file has been copied to target host"

No comments:

Post a Comment