shell结合iptables自动拒绝恶意连接ssh的方法及实现代码
本脚本实现:
调用方法:
停止方法:
代码:
#!/bin/bash
do
#设置连接出错次数
#邮件报警地址设置
#本机IP地址设置,邮件报警时用
#设置获取的IP地址的存放位置
#获取sshd服务端口
TIME=`date +”%Y-%m-%d %H:%M:%S”` echo ” “”日 期”" “”时 间”" “”连接次数”" “”IP 地 址”" “”日期”" “”小时” > $BADIP ;lastb -i | awk ‘{print $3″ “$6″ “$7}’ | awk -F: ‘{print $1}’ |sort |uniq -c|awk ‘$1 > ‘$NUMBER’ {print $1″ ” $2″ “$3″ “$4}’| awk -vtime=”$TIME” ‘{print time” “$1 ” “$2″ “$3″ “$4}’|column -t >>$BADIP cat $BADIP >> $BKIP DROPIP=`cat $BADIP | wc -l ` ipline=/tmp/.ssh/.ipline touch $ipline if [ $DROPIP -gt 1 ] ; then for bip in `grep -v 日期$BADIP | awk ‘{print $4}’` do IPLINEA=`/sbin/iptables -L -n –line-number |egrep ‘[DROP|22]‘ | grep -v Ch |awk ‘{print $1}’|wc -l` echo $IPLINEA > $ipline iptables -I INPUT -s $bip -p tcp –dport $SSHPORT -j DROP echo $bip >> $IPLIST echo “$TIME Lock IP address $bip iptables ” >> $LOG cat /var/log/btmp >> /var/log/btmp.bak ; >/var/log/btmp TIME_NOWA=`date +%s` echo $TIME_NOWA > time done fi LINEVE=`wc -l /tmp/.ssh/.ipline | awk ‘{print $1}’ ` if [ $LINEVE -gt 0 ] ; then echo linefile ok > /dev/null else echo 0 > $ipline fi IPLINE=`cat $ipline` LINEB=`grep -v 日期$BKIP|wc -l |awk ‘{print $1}’` VALUE=`echo “$LINEB-$LINEA”|bc` #获取被列入$BKIP的ip地址 LAST=`tail -n $VALUE $BKIP` if [ $VALUE -gt 0 ] ; then sendmail -t <<EOF from: $MAILFROM to: $MAILTO subject: 严重警告 $time 当前有人正在试探性连接SSH服务,系统已拦截,查看详情请登录服务器$IPADDR 。 $LAST EOF echo “$TIME send mail to $MAILTO” >> $LOG fi IPLINEB=`/sbin/iptables -L -n –line-number |egrep ‘[DROP|22]‘ | grep -v Ch |awk ‘{print $1}’|wc -l` if [ $IPLINEB -eq 1 ] ; then IPLINEB=`/sbin/iptables -L -n –line-number |egrep ‘[DROP|22]‘ | grep -v Ch |awk ‘{print $1}’|wc -l >/dev/null ; echo “$IPLINEB+1″|bc ` fi #当前时间 OLD_TIME=`cat time` TIME_NOWB=`date +%s` #间隔时间判断 TIME_IN=`echo “$TIME_NOWB-$OLD_TIME” | bc` #删除禁止的IP地址 LNUMBER=`echo “$IPLINEB-$IPLINE”|bc` if [ $LNUMBER -lt 2 ] ; then LNUMBER=`echo “$IPLINEB-$IPLINE+2″|bc` else LNUMBER=`echo “$IPLINEB-$IPLINE”|bc` fi if [ $LNUMBER -gt 1 ] ; then if [ $TIME_IN -gt $RETIME ] ; then iptables -L -n –line-number | awk ‘{print $5″ “$2″ “$1″ “$8}’ | awk -Fdpt: ‘{print $1″ “$2}’ | egrep -v ‘[num|Ch]‘ | grep $SSHPORT|column -t > $IPTFILE RMIP=`cat $IPLIST |awk ‘{print $1}’` for i in `awk ‘NR==FNR{a[$1]=$2″ “$3″ “$4}NR>FNR{print $0,a[$1]}’ $IPTFILE $IPLIST | awk ‘{print $3}’` do iptables -D INPUT $i >$IPLIST echo “$TIME Remove lock $RMIP IP address ” >> $LOG done fi fi #ps aux | grep ./ssh |grep -v ‘/usr/sbin/sshd’ |grep -v grep |awk ‘{print $2}’ >> $LOG sleep $EXEC_TIME done (责任编辑:IT) |