Tuesday, October 18, 2011

Pexpect is help interact with ssh

I have a 400-500 ssh server that I need connect to by ssh,since those server are not real OS server,they are eqipment,they are response very slowly,even for the login,I tried jsch,it can not handle the server's delay,my command was inserted into the server's prompt information,and not been accepted and executed.
there is a tool call script expect that can help with this,but lack of database connection and data process(File read/write) and data structure
so I come up with a python and pexpect package,it was very neat to connect to ssh server interact with it and fetch the result,save it to a file,extract data I want,then save into database,here is the part of code for pexepect:
def readEqam(ip,userIndex):
print 'connecting to',ip
starttime = datetime.now()
logFile = file('eqam_'+ip+".txt",'w')
child=pexpect.spawn('ssh '+userNames[userIndex]+'@'+ip)
child.logfile=logFile
i=child.expect(["Are you sure you want to continue connecting","password:"])
print i
if i==0:
child.sendline('yes')
i=child.expect('password:')
child.sendline(passwords[userIndex])
i=child.expect("#>",60)
if(i!=0):
child.kill(0)
return False
else:
child.sendline("show application m-cmts")
i=child.expect("#>",60)
if(i!=0):
child.kill(0)
return False
else:
data = child.before
child.sendline("closeSession")
child=None
elif i==1:
child.sendline(passwords[userIndex])
i=child.expect('#>',60)
if i!=0:
child.kill(0)
return False
else:
child.sendline("show application m-cmts")
#print child.before
i=child.expect("#>",60)
if(i!=0):
child.kill(0)
return False
else:
#print "START",child.before,"END"
data = child.before
child.sendline("closeSession")
child.sendline("\r")
child = None

logFile.close()
print 'total time used:',(datetime.now()-starttime).seconds
return True,data

No comments:

Post a Comment