Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.popen seems to fail when run from crontab

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 python 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 error message below.

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?

like image 733
Matt Avatar asked Sep 05 '25 03:09

Matt


2 Answers

The cron PATH is very limited. You should either set absolute path to your ssh /usr/bin/ssh or set the PATH as a first line in your crontab.

like image 96
user1652558 Avatar answered Sep 07 '25 20:09

user1652558


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.

like image 32
Mike Axiak Avatar answered Sep 07 '25 20:09

Mike Axiak