Cron Bash – Troubleshooting Crontab Running Bash Script with SSH Command

bashcron

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.

Best Answer

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.