Reputation: 1181
I'm writing a python nagios check to check the timestamp of a file the last time it was updated, however I need to check two separate hosts in my script so I want to use a remote ssh command to return the timestamp to stdout and use that to make sure a script has completed within the last 24 hours because when the script completes it touches a file.
When I run the command from command prompt it works however when I run it from my python code it doesn't return the output back to my program.
Grants-MacBook-Pro:test GrantZukel$ ssh ubuntu@hostname sudo ls -la /home/ubuntu/ | grep code_regen_complete
The authenticity of host 'ec2-54-144-160-238.compute-1.amazonaws.com (54.144.160.238)' can't be established.
RSA key fingerprint is hidden.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/Users/GrantZukel/.ssh/known_hosts).
-rw-r--r-- 1 root root 0 Jan 29 17:23 code_regen_complete
Grants-MacBook-Pro:test GrantZukel$
The python is :
def get_code_time():
p = subprocess.Popen(['ssh','ubuntu@hostname', '"sudo ls -la /home/ubuntu/ | grep code_regen_complete"'], stdout=subprocess.PIPE)
out, err = p.communicate()
m = re.search('\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}', out)
return m.group(0)
however when I use debugger the out or err vars are completely empty. Any ideas?
Upvotes: 1
Views: 4707
Reputation: 485
Get rid of the double-quotes around the ls
command:
p = subprocess.Popen(['ssh','ubuntu@hostname', 'sudo ls -la /home/ubuntu/code_regen_complete'], stdout=subprocess.PIPE)
You might also want to try Fabric.
Upvotes: 1
Reputation: 107287
You need to pass shell=True
in your command :
p = subprocess.Popen(['ssh','ubuntu@hostname', '"sudo ls -la /home/ubuntu/ | grep code_regen_complete"'], stdout=subprocess.PIPE,shell=True)
Upvotes: 2