Python pexpect返回命令和命令输出

Python pexpect返回命令和命令输出,python,ssh,python-2.7,stdout,pexpect,Python,Ssh,Python 2.7,Stdout,Pexpect,我想连接到运行CLISH的服务器,在给出密码提示时提供密码(works),然后发出“shell”命令将我连接到bash shell(works),然后测试文件是否存在,如果缺少则打印“true”,如果存在则打印“空字符串”(works) 不起作用的是我用“pexpect.before”读回脚本中的内容。我已经要求pexpect预期基本提示,然后给我“before”,我的理解是:“在匹配提示之前,您在屏幕上看到了什么?”我不仅得到了预期的“true”或“”(空字符串),而且还得到了我发出的用于测试

我想连接到运行CLISH的服务器,在给出密码提示时提供密码(works),然后发出“shell”命令将我连接到bash shell(works),然后测试文件是否存在,如果缺少则打印“true”,如果存在则打印“空字符串”(works)

不起作用的是我用“pexpect.before”读回脚本中的内容。我已经要求pexpect预期基本提示,然后给我“before”,我的理解是:“在匹配提示之前,您在屏幕上看到了什么?”我不仅得到了预期的“true”或“”(空字符串),而且还得到了我发出的用于测试文件存在性的命令

例如,如果我直接使用SSH连接到机器,我将执行以下操作: 密码: 我的脚本返回的是命令和响应(问题和答案):

[!-f'/etc/logrotate.d/nginx']和&echo'true'

true

我只想要回答,要么是“真的”,要么是“真的”。我得到了回应,但我也得到了发出的命令

你能看出我做错了什么吗?请帮忙!我想继续使用pexpect,因为我对SSH会话有更复杂的“期望”

这是我的代码:

def connection(cmd):
    msg_newkey = 'Are you sure you want to continue connecting'
    p=pexpect.spawn('ssh '+user+'@'+host)
    msg = '''Super long welcome message containing your canned warning message, etc.
          myuser@'''+myhost+''''s password:'''
    i=p.expect([msg_newkey,'password:',pexpect.EOF])
    if i==0:
        print "Accepting key."
        p.sendline('yes')
        i=p.expect([msg_newkey,'password:',pexpect.EOF])
    if i==1:
        print "Supplying password"
        p.sendline(passwd)
    elif i==2:
        if "No route to host" in p.before:
            return p.before
        else:
            pass    # Add no functionality, just saying "move on"
    i=p.expect(['MYCLISHPROMPT>',pexpect.EOF])
    if i==0:
            p.sendline('shell')
    i=p.expect(['.*@.*\$',pexpect.EOF])
    if i==0:
            p.sendline(cmd)
    p.expect(['myuser@myhost:',pexpect.EOF])
    return p.before

 def look_for_file(step, filename, mytest):
    cmd = "[ ! -f '"+filename+"' ] && echo '"+mytest+"'"
    results = connection(cmd)
    print "***"+str(result)+"***"
    assert (results == '' or results == 0), "Step failed!  Error: "+results

有一个函数
setecho
(它的pair
getecho
)可以控制发送行中的字符串是否会被回显

setecho(self, state)
    This sets the terminal echo mode on or off. Note that anything the
    child sent before the echo will be lost, so you should be sure that
    your input buffer is empty before you call setecho().

然而,这显然不是在所有情况下都有效,您需要使用一些变通方法。一种是在bash中像在中一样切换echo。另一种方法是使用pexpect的函数
readline
readlines
,读取输出并丢弃响应给定命令的第一行。

我在一个脚本中遇到了这个问题,我需要将pexpect日志设置为sys.stdout,如下所示:

    shell = pexpect.spawn("bash")
    shell.logfile = sys.stdout
我尝试了其他答案中建议的解决方案,但没有成功;无论发生什么情况,传递给
sendline()
的字符串都会打印到日志中

但是,我发现暂时禁用pexpect日志似乎可以解决问题:

    shell.logfile = None
    shell.sendline(MY_STRING)
    shell.logfile = sys.stdout

谢谢你的意见!我将探索这些选项,并尽快将结果发布回这里。我遇到了另一个问题,现在正在发布这个问题:)这对我来说非常有效。我现在只得到我的结果,而不是我的命令。谢谢