这是我的第一个Shell Script,写的乱乱糟糟,试验了一下,还是可用的,目前已经在我自己的WEB服务器上跑起来了!!~~
#!/bin/bash#这个shell script 用来防止SSH暴力破解#Auther:Aaron Guo#Date:Jan 8 2016#Version:1.2# 指定该SHELL的日志文件logfile="/var/log/blocked_ip"# 获取现在时间,用来grep /var/log/secure. (格式:mm dd HH)timenow=$(date '+%b %e %H')# 如果在当前一小时内,20次连接失败,则记录rootip=$(grep "$timenow" /var/log/secure|grep root.*because|awk '{print $9}'|sort|uniq -c|sed s/[\.][a-zA-Z].*//g|awk '$1>20 {print $1":"$2}')anyip=$(grep "$timenow" /var/log/secure|grep Invalid| awk '{print $10}'|sort|uniq -c|sed s/[\.][a-zA-Z].*//g|awk '$1>20 {print $1":"$2}')# 添加破解root密码的到iptablesfor i in $rootipdoip=$(echo $i|awk -F: '{print $2}')# 检查***者的IP在iptables存在否. iptables-save|grep INPUT|grep DROP|grep "$ip">/dev/null# 如果不存在(也就是上一条命令执行错误,变量$? > 0 ),那么添加到iptables. if [ $? -gt 0 ]; then iptables -A INPUT -s "$ip" -p tcp --dport 22 -j DROP now=$(date '+%Y-%m-%d %H:%M')# add to log file. echo -e "$now : $ip" >> $logfile fidone# 添加随便试用户名的那些到iptables.for i in $anyipdoip=$(echo $i|awk -F: '{print $2}')# check crackers ip exist or not. iptables-save|grep INPUT|grep DROP|grep "$ip">/dev/null# do not exist , add to iptables. if [ $? -gt 0 ]; then iptables -A INPUT -s "$ip" -p tcp --dport 22 -j DROP now=$(date '+%Y-%m-%d %H:%M')# add to log file. echo -e "$now : $ip" >> $logfile fidone
最后把这个脚本添加可执行(x)权限,之后添加到/etc/crontab,我设定的是每10分钟执行一次(*/10)
# For details see man 4 crontabs# Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed */10 * * * * root /root/blockip.sh
如有错误,欢迎指正!!