crontab to run bash script (ssh command in it) not working

CentOS 5.4

(in my script file - script.sh)

#!/bin/bash
ssh 192.168.0.1 'iptables -L' > /tmp;

(in /etc/crontab)

30 21 30 9 * root /bin/bash /script.sh

If I run the script in terminal, things work just fine. But use crontab to run it, the tmp will be generated, but there's nothing in the tmp file (0k). I already run ssh agent so ssh won't prompt to ask password. What could be the problem with this? Thanks.


I suggest you to always explicitly set all needed variables at the beginning of the scripts.

PATH=/bin:/usr/bin:/sbin
MYVAR=whatever

That said, I would

  1. create a private/public keypair
  2. set an empty password on the private key
  3. set permission 400 on the private key file
  4. put the public key in the authorized_keys file of the root user on 192.168.0.1

Now try the connection with

#!/bin/bash
PATH=/usr/bin

ssh -i /myprivatekey -l root 192.168.0.1 '/sbin/iptables -L' > /tmp/output.$$

Edit: I guessed that the "iptables" command had to be executed by root on the remote server. If it is not, of course the "-l" parameter has to be changed accordingly.


Things that won't run from cron but will run from the terminal are almost always a problem due the difference in environment. You should use the full path to your executables and explicitly set any environment variables and PATH that they need.

#!/bin/bash
/usr/bin/ssh 192.168.0.1 '/sbin/iptables -L' > /tmp/output.$$

By the way, you don't really have your script in the root directory do you?

Also, /tmp is a directory that should already exist. You should create your output as a file within it as I've shown.


I don't think ssh-agent is going to help in this case because the cronjob isn't a subprocess of one that has the ssh-agent communication params in its environment. You'll need to set up a passwordless login for this to work.

One way to get more info is to change your ssh call to be

ssh -vvv 192.168.0.1 'iptables -L' 2>&1 > /tmp/output.$$

so that 1) ssh will produce verbose debugging output on stderr and 2) stderr will be redirected along with stdout. That output.$$ file should have more info about what's going on... my bet is, as I said, on lack of perms to open your key.