7

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.

5
  • why do you need to add iptables rules in cron, if you want to add iptables rulesand you want them to be persistent you can add them to /etc/sysconfig/iptables or rc.local Commented Apr 10, 2014 at 9:45
  • You need to set your PATH properly to find iptables. Commented Apr 10, 2014 at 9:48
  • that would require restarting the iptables service yes? Commented Apr 10, 2014 at 9:48
  • 1
    Try adding the full path of all commands. which iptables will give it to you for iptables, do the same for the others. Commented Apr 10, 2014 at 9:48
  • done Mark! way to go! thanks Commented Apr 10, 2014 at 9:49

2 Answers 2

16

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
Sign up to request clarification or add additional context in comments.

Comments

0

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 .

2 Comments

While this is a more general and interesting solution, I don't think it is a problem on cronjob configuration, but on the paths of the scripts.
Yes..path of script and path of iptables command maybe is the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.