Thursday, December 12, 2019

cron - 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.



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.


No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...