views:

39

answers:

2

Hi All,

probably a daft question but....

I'm running a script from crontab that will just ssh and run a command and store the results in a file.

the function that seems to be failing is subprocess.popen

Here is the function

def _executeSSHCommand(sshcommand,user,node):

    '''
    Simple function to execute an ssh command on a remote node.
    '''

    sshunixcmd = '/usr/bin/ssh %s@%s \'%s\'' % (user,node,sshcommand)
    process = subprocess.Popen([sshunixcmd],
                                shell=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
    process.wait()
    result = process.stdout.readlines()
    return result

When it's run from the command line, it executes correctly, from Cron it seems to fail with the message

here are the crontab entries 02 * * * * /home/matt/scripts/check-diskspace.py >> /home/matt/logs/disklog.log

Here are the errors

Sep 23 17:02:01 timmy CRON[13387]: (matt) CMD (/home/matt/scripts/check-diskspace.py >> /home/matt/logs/disklog.log)
Sep 23 17:02:01 timmy CRON[13386]: (CRON) error (grandchild #13387 failed with exit status 2)

I'm going blind trying to find exactly where I have gone so wrong.

Any ideas ?

+1  A: 

You probably need to pass ssh the -i argument to tell ssh to use a specific key file. The problem is that your environment is not set up to tell ssh which key to use.

The fact that you're using python here is a bit of a red herring.

Mike Axiak
Hi All, after reading all the comments, I suspect this isn't a python *thing* but rather my lack of understanding around ssh and crontab.
Bovril
Thanks to everyone that answered!!! I'll spend this evening hacking about to fill in those knowledge gaps!!!
Bovril
+1  A: 

For everything ssh-related in python, you might consider using paramiko. Using it, the following code should do what you want.

import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect(node, username=user)
stdout = client.exec_command(ssh_command)[0]
return stdout.readlines()
mripard