Tarek Sawah
Tarek Sawah

Reputation: 305

Bash script commands not working in cron

I have the following bash script to read logs and check for brute force then block violating IP using iptables.

#!/bin/bash
#blah blah run some commands to get the IP
iptables -A INPUT -s $p -j REJECT --reject-with icmp-host-prohibited
echo "BANNED $p FOR $COUNT ATTEMPTS" |wall

I did chmod 755. When I run the command from terminal it works fine. But when I setup a cronjob using crontab -e as root, it gets the IP and echos the "BANNED ..." message to the wall but nothing is added to the iptables list.

PS. I tried both #!/bin/bash and #!/bin/sh but no luck.

Upvotes: 7

Views: 7297

Answers (2)

MLSC
MLSC

Reputation: 5972

Try the following solution should work for you:

cat cronjob
* * * * * /path/to/script.sh

Then:

chmod +x cronjob
chmod +x script.sh

/etc/init.d/crond start  #redhat based servers like centos
/etc/init.d/cron  start  #debian based servers like ubuntu

crontab cronjob

NOTE: Sometimes you need to enter full path of IPTABLES command if your rules aren't added to /etc/sysconfig/iptables .

Upvotes: 0

kpopovbg
kpopovbg

Reputation: 301

Try to provide full path to iptables e.g.

$ which iptables
/sbin/iptables

and than modify your script like that:\

#!/bin/bash
#blah blah run some commands to get the IP
/sbin/iptables -A INPUT -s $p -j REJECT --reject-with icmp-host-prohibited
echo "BANNED $p FOR $COUNT ATTEMPTS" |wall

Upvotes: 16

Related Questions