我正在编写一个脚本,通过SSH登录到远程节点,并通过保存pgrep -a <service-name>
的输出来检查服务是否已启动,将其存储在变量中并检查该变量是否为UP。 / p>
HOST="172.29.219.110"
COMMAND="pgrep -a haproaxy"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
print ( result )
if result == "":
print ("The service is NOT running")
else:
print ("The service is running")
如果按原样运行上述内容,我会收到以下回复:
[b'31318 /usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid\n', b'31319 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds\n', b'31320 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds\n']
The service is running
但是当我pgrep
虚假服务时,响应是
[]
The service is running
我已在远程服务器上检查pgrep -a haaaaaaaaa
什么都没有回复。但它似乎没有在python中注册为空变量。我做错了什么?
答案 0 :(得分:0)
您将列表与空字符串等同起来。这就是你的代码失败的原因。对此的正确答案是:
if not result:
print("The service is not running")