我想连接到运行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