返回通过python内部expect命令中嵌入的ssh远程执行的grep命令的状态
我有一个低于python的脚本,其中我正在使用expect执行远程SSH命令。在这里,即使目标文件是否包含字符串“error”,退出代码也会作为success返回,因为只有ssh连接被检查。如何获取grep命令的状态返回通过python内部expect命令中嵌入的ssh远程执行的grep命令的状态,python,ssh,expect,Python,Ssh,Expect,我有一个低于python的脚本,其中我正在使用expect执行远程SSH命令。在这里,即使目标文件是否包含字符串“error”,退出代码也会作为success返回,因为只有ssh连接被检查。如何获取grep命令的状态 #! /usr/bin/python import subprocess def execute(cmd): proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subproce
#! /usr/bin/python
import subprocess
def execute(cmd):
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
_output, _error = proc.communicate()
_code = proc.returncode
return _output, _error, _code
host = "localhost"
passwd = "kube"
cmd="/usr/bin/expect -c 'spawn ssh "+host+" \"cat /home/kube/f1 | grep -qi error\"; expect \"password:\" { send \""+passwd+"\r\"} ;interact' "
_output, _error, return_code = execute(cmd)
print cmd + "\n" + _output + "\n" + _error
if (return_code == 0):
print "no error"
else:
print "contains error"
备选案文1:
让远程命令输出指示您成功/失败的内容。例如:
ssh user@host "/some/command | grep -q some-string && echo MAGIC-SUCCESS || echo MAGIC-FAILURE"
在Python中,您可以获得输出并解析它
备选案文2:
根据《人类期望》:
- 等等
[…]
通常返回四个整数的列表。第一个整数是等待的进程的pid。第二个整数是对应的繁殖id。第三个整数是操作系统错误时的wait
,否则为-1
。如果第三个整数是0
,则第四个整数是派生进程返回的状态。如果第三个整数是0
,则第四个整数是操作系统设置的-1
的值。[……]错误号
等待
结果,然后使用不同的值检查退出
,Python代码可以获得退出状态
对于Expect部分,它是这样的:
spawn。。。
...
预期eof
设置结果[等待]
退出[lindex$结果3]
运行此操作后,您在\u输出
和\u错误
中有什么内容?有专门的库通过SSH为远程子进程制作,或者我经常这样做。此外,密码和ssh在某种程度上缺少ssh的要点,IMHO。zvone
no error only outputspawn ssh localhost cat/home/kube/f1 | grep-qi errorkube@localhost's password:
我在我的expect
命令字符串cmd=“/usr/bin/expect-c'spawn ssh”+host+“\”cat/home/kube/f1 | grep-qi错误中添加了这些行\"; 应为\“密码:\”{send\”+passwd+“\r\”};预期eof;设置结果[等待];退出[lindex result 3]“
但它总是返回0(无论错误字符串是否存在)。刚刚修复。lindex result 3
==>lindex$result 3
pynexj是的,它现在可以工作了:)谢谢!顺便说一句,python有自己的错误。可能比在python中运行Expect要简单一些。