[TriLUG] Bash Script in cron job

Brian Blater (BBList) bblist at ridetta.org
Wed Feb 22 15:23:07 EST 2006


I've created a script that is to run every minute and monitor the
/var/log/messages log for "Illegal user" messages from sshd and then
write those addresses to the /etc/hosts.deny file. If I run the script
from the command prompt, it works just fine and updates the hosts.deny
file.

So, I edit the /etc/crontab file and added a new entry as below:
*/1 * * * *     root  /root/hosts.deny.sh
I then see that every minute the script is run, however, the hosts.deny
file is not updated and none of the IPs are inserted into the file. I
thought maybe I had something wrong with the script but it works fine if
I go to the command line and run hosts.deny.sh. Go figure. I'm sure
there is some little thing I need to do, but I can't figure out what it
is.

The script is as follows:
#!/bin/bash
LAST_IP=0.0.0.0
COUNT=1

# Set MAXCOUNT to the maximum failures allowed before blacklisting
MAXCOUNT=5

#
# The three lines below put the leading lines in /etc/hosts.allow
# Note: This script overwrites the entire /etc/hosts.allow file.
#

echo '
# /etc/hosts.deny
# See `man tcpd? and `man 5 hosts_access? as well as /etc/hosts.allow
# for a detailed description.
http-rman : ALL EXCEPT LOCAL' > /etc/hosts.deny

#
# Scan the /var/log/messages file for failed login attempts via ssh.
# Parse out the IP address, and count the failure occurances from that
IP
# If the IP fails more than 5 times -  deny further access
#

for IP in `/bin/grep sshd /var/log/messages|/bin/grep "Illegal
user"|/bin/sed 's/^.*from//'|cut -f2 -d " "`; do
  if [ ${LAST_IP} == ${IP} ] ; then
     let COUNT=${COUNT}+1
  else
  if [ ${COUNT} -ge ${MAXCOUNT} ] ; then
        echo "ALL: ${LAST_IP}/32" >> /etc/hosts.deny
  fi
     LAST_IP=${IP}
     COUNT=1
  fi
done

Any help would be greatly appreciated.

Thanks,
Brian



More information about the TriLUG mailing list