1. 使用.logfile 方法
import pexpect
import sys
host="146.11.85.xxx"
user="inteuser"
password="xxxx"
command="ls -l"
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
child.expect('password:')
child.sendline(password)
childlog = open('promp.log',"ab")
child.logfile = childlog
child.expect(pexpect.EOF)
childlog.close()
2.改变标准输出sys.stdout的输出对象,将log print到文件
import pexpect
import sys
host="146.11.85.xxx"
user="inteuser"
password="xxxx"
command="ls -l"
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
child.expect('password:')
child.sendline(password)
__console__ = sys.stdout
childlog = open('promp.log',"w")
sys.stdout = childlog
child.expect(pexpect.EOF)
print(child.before.decode())
childlog.close()
sys.stdout = __console__