1

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?

2
  • unrelated, but if you log in as ubuntu, why do you need to sudo to list /home/ubuntu? Commented Jan 29, 2015 at 19:24
  • and why don't you ls -l /home/ubuntu/code_regen_complete directly? Commented Jan 29, 2015 at 19:26

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks this worked I still had to modify a few things but this ultimately is what helped thanks.
one more qeustion tho
sudo ssh ubuntu@hosts sudo git log -1 --date=iso | grep ^Date: | awk '{print $2','$3, $4}' how do i execute that command against /var/www/vhosts/webdirectory
local_repo_date = compare_codebase("sudo ssh ubuntu@hostname 'cd /var/www/vhosts/bazumedia.com/; sudo git log -1 --date=iso | grep ^Date'") I figured it out nvm
1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.