0

I am writing a script that logs into a remote node via SSH and checks for a service being up by saving the output of pgrep -a <service-name> , storing it in a variable and checking if that variable is UP or not.

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")

If I run the above as it is, I get the below response:

[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

But when I pgrep a bogus service, the response is

[]
The service is running

Ive checked on the remote server that pgrep -a haaaaaaaaa retuns nothing. But it doesnt seem to register as an empty variable in python. What is it that I am doing wrong ?

7
  • 4
    Result is a list. You can check for an empty list with if not list: Commented Apr 3, 2017 at 19:33
  • 4
    use if not result. Or if result == [] Commented Apr 3, 2017 at 19:34
  • 1
    [] is simply not the same as "". Commented Apr 3, 2017 at 19:36
  • 2
    That's a pretty crappy way to check whether the service is up, for what it's worth. I can think of multiple failure modes. Commented Apr 3, 2017 at 19:36
  • 2
    I'd say swap your conditional and just use if result: #good else: #bad Commented Apr 3, 2017 at 19:36

1 Answer 1

1

You are equating a list with an empty string. That is why your code fails. The correct answer to this would be:

if not result:
  print("The service is not running")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.