|
学着写的第一个shell scripts,其中得到了troll兄的不涩指教,见http://www.linuxsir.cn/bbs/showthread.php?t=274130
其中一些scripts书写格式参照了vbird的logfile.sh (注,http://linux.vbird.org 是个很好的站,vbird是个了不起的man)
由于本人E文极差,以为一些E文的注释请大家不要见笑,(在Shell中无法输入中文,见谅) 。
思路:
查找/var/log/secure文件中 试图sshd本机次数超过3次的IP,将其写入iptables 的filter 表中,然后DROP掉。
写入crontab每天凌晨2:30分运行一次!
******************************************************
#!/bin/bash
# Program
#
# The Program help you autofilter some bad user try to sshd my server
#
# author TMeng ( Email: tanmeng_sinoAT126DOTcom )
#
# History
# 2006/09/23 PM 16:54:16 TMeng First release
#
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
datenu=`date --date='l day ago' +%b' '%e`
basedir=/usr/local/virus/ipfilter
logfile="$basedir/sshd.faild.illegal.ip"
dirtyip="$basedir/dirty.ip"
filtip="$basedir/filt.ip"
iptable="/etc/sysconfig/iptables"
netface="ppp0"
mail=root@localhost
LANG=en
export PATH datenu basedir logfile dirtyip filtip iptable email LANG
# 0.0.1
#
##########################################################################
#
# INSTALL
#
# mkdir -p /usr/local/virus/ipfilter
# cp ipfilter.sh /usr/local/virus/ipfilter
#
# maybe you are used HDLC,PPP,LAN and other ways connect to internet
# you must modify the "$netface" variable
#
# add the Scripts to crontab,make shure running at AM 2:30
# 30 2 * * * root /usr/local/virus/ipfilter/ipfilter.sh
#
##########################################################################
#
# 0.0.2
# check the syslog service on your server
if [ ! -f "/var/log/secure" ]; then
echo -e " You must check your syslog service!! "
exit 1
fi
# 0.0.3
# Find the Bad IP address at /var/log/secure log file
grep "$datenu" /var/log/secure > | grep 'sshd' | grep 'Failed' | awk '{ print $11 }' \
> "$logfile"
grep "$datenu" /var/log/secure > | grep 'sshd' | grep 'Illegal' | awk '{ print $10 }' \
>> "$logfile"
# 0.0.4
# try to 3 times or more than sshd , are filt ip
uniq -c < "$logfile" > "$dirtyip";awk '$1 >= 3 { print $2 }' "$dirtyip" > "$filtip"
# 0.0.5
# add to filter table
while read ip;do
if ! grep -q "$ip" "$iptable" ;then
/sbin/iptables -t filter -A INPUT -i "$netface" -p tcp -s "$ip" -j DROP
fi
done < "$filtip"
# 0.0.6
# Because IPTABLES are in the kernel,So we don't restart IPTABLES Service
# Save as filter table to "iptable"
/sbin/iptables-save > "$iptable"
# 0.0.7
# And last,mail the "filtip" to you
mail -s " You must check these IP address ,they are attempt connect your server" "$mail" \
< "$filtip"
# 0.0.8
# edit crontab,make sure running at AM 2:30,like follow line
# 30 2 * * * root /usr/local/virus/ipfilter/ipfilter.sh
# all be done |
|