我有pexpect工作,但我在从它打印输出时遇到问题.在我下面的测试脚本中,它创建ssh连接,然后发送sudo su – ,然后发送我的密码,然后发送一行需要sudo访问权限(我还添加了几次p.interact()确保它在根).我遇到的问题是返回我运行的命令的输出.最后,我想运行一些顶级命令,以及一些du -h和其他(更复杂的)空间命令.但是目前当它试图打印p.before时,我得到:
Traceback (most recent call last):
File "./ssh.py", line 37, in
print p.before()
TypeError: 'str' object is not callable
这是我正在处理的脚本(编辑删除我的通行证等)
#!/usr/bin/env python
import pexpect
import struct, fcntl, os, sys, signal
def sigwinch_passthrough (sig, data):
# Check for buggy platforms (see pexpect.setwinsize()).
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912 # assume
s = struct.pack ("HHHH", 0, 0, 0, 0)
a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
global global_pexpect_instance
global_pexpect_instance.setwinsize(a[0],a[1])
ssh_newkey = 'Are you sure you want to continue connecting'
p=pexpect.spawn('ssh user@localhost')
i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
print "I give password",
p.sendline("mypassword")
elif i==2:
print "I either got key or connection timeout"
pass
elif i==3: #timeout
pass
global global_pexpect_instance
global_pexpect_instance = p
p.sendline("sudo su -")
p.sendline("mypasswd")
p.sendline("mkdir /home/user/test")
print p.before
任何帮助深表感谢.
编辑:正如Armin Rigo在下面指出的那样.我打电话给p.before作为像p.before()这样的函数.我这个愚蠢的错误,因为这解释了为什么我今天得到这个错误,而不是昨天我尝试这个时.在对我的脚本进行更改并修改正在发送的命令后,打印p.before,并且不返回任何输出.从sendline()命令返回输出的任何其他方法?