#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
# filename: pexpect_test.py
import pexpect,time,sys
def sendCommt():
demo = open("result.txt", "ab")
demo.write('==========Log Tile: demo==========\n')
print "start link"
child = pexpect.spawn('ssh %s@%s' % (user,ip))
print "link to 10.10.16.24."
child.expect("natsu@10.10.16.24's password: ")
child.sendline(passwd)
for cmd in cmds:
time.sleep(2)
p = pexpect.spawn(cmd)
p.logfile = demo
p.write('=====================\n')
p.expect(pexpect.EOF)
print cmd
time.sleep(2)
demo.close()
child.close()
print "done"
if __name__ == '__main__':
user = 'natsu'
ip = '10.10.16.24'
passwd = '1'
cmds = ['ps','ls','ls -l','ifconfig','date']
# patterns = ['Are you sure you want to continue connecting (yes/no)?','password:']
# CONTINUES,PASSWD = range(len(patterns))
# flag = 'yes'
try:
sendCommt()
except pexpect.TIMEOUT:
print "TIMEOUT"
# except pexpect.EOF:
# print "EOF"
在linux环境下运行Python
上面的代码可以运行通过
但是把p = pexpect.spawn(cmd) 改成 p = pexpect.sendline(cmd)后,就会报这个错误
这里有个类似的描述http://stackoverflow.com/questions/11403932/python-attributeerror-module-object-has-no-attribute-serial
但是照他的改法会报这个
看下面dir的结果,pexpect模块里面没有sendline这个方法,所以会报AttributeError.
正确的用法示例如下:
要在pexpect.spawn(cmd)的返回值上调用sendline方法,参考:http://pexpect.readthedocs.org/en/stable/overview.html