我想连接到运行 CLISH 的服务器,在出现密码提示时提供密码(有效),然后发出“shell”命令将我切换到 bash shell(有效),然后测试是否存在文件的名称,如果缺少则打印“true”,如果存在(有效)则打印“”(空字符串)。
不起作用的是我使用“pexpect.before”读回到脚本中的内容。我已经要求 pexpect 期待基本提示,然后给我“之前”,据我了解是:“在提示匹配之前,您在屏幕上看到了什么?”我不仅按预期得到了“true”或“”(空字符串),还得到了我发出的用于测试文件是否存在的命令。
例如,如果我直接通过 SSH 连接到机器,我会这样做: 密码:
我的脚本返回的是命令和响应(问题和答案):
[! -f '/etc/logrotate.d/nginx'] && echo 'true'
真
我只想要响应,要么是“true”,要么是“”。我收到了响应,但也收到了发出的命令。
你能看出我做错了什么吗?请帮忙!我想继续使用 pexpect,因为我对 SSH session 有更复杂的“期望”。
这是我的代码:
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
(它是 getecho
对),它应该控制 sendline 中的字符串是否会被回显。
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,如 this answer 所示。 。另一种方法是使用 pexpect 的函数 readline 或 readlines 来读取输出并丢弃与给定命令相呼应的第一行。
关于Python pexpect 返回命令和命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15211011/