从pexpect sendline读取输出

cas*_*n04 5 python ssh sudo pexpect

我有预期的工作,但是在从中打印输出时遇到了问题。在下面的测试脚本中,它创建ssh连接,然后发送sudo su-,然后输入密码,然后发送需要sudo访问权限的行(我还向其中添加了p.interact()几次)确保它是根目录)。我遇到的问题是返回我运行的命令的输出。最后,我要运行一些顶级命令,一些du -h和其他(更为复杂的)空格命令。但是目前,当它尝试打印p.before时,我得到:

Traceback (most recent call last):
File "./ssh.py", line 37, in <module>
print p.before()
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的脚本(已编辑以删除通行证等)

#!/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
Run Code Online (Sandbox Code Playgroud)

我正在使用此链接:http : //linux.byexamples.com/archives/346/python-how-to-access-ssh-with-pexpect/

任何帮助深表感谢。

编辑:正如阿明·里戈指出的那样。我正在以p.before()之类的功能调用p.before。我这是愚蠢的错误,因为这解释了为什么我今天而不是昨天尝试此操作时会收到此错误。更改完我的脚本并修改要发送的命令后,请打印p.before,然后不返回任何输出。还有其他方法可以从sendline()命令返回输出吗?

Ree*_*nda 1

使用日志文件,该日志文件将所有输出存储在终端中。使用该示例代码:-

child = pexpect.spawn("ssh user@localhost")
child.logfile = open("/tmp/mylog", "w")
child.expect(".*assword:")
child.send("guest\r")
child.expect(".*\$ ")
child.sendline("python -V\r")
Run Code Online (Sandbox Code Playgroud)

打开日志文件并查看终端事件中的所有内容