starttime=`date +'%Y-%m-%d %H:%M:%S'`
#执行程序
sleep 10
endtime=`date +'%Y-%m-%d %H:%M:%S'`
echo $starttime $endtime
start_seconds=$(date --date="$starttime" +%s);
end_seconds=$(date --date="$endtime" +%s);
echo "本次运行时间: "$((end_seconds-start_seconds))"s"
根据时间戳比对删掉4个小时前的规则
#!/bin/bash
source /etc/profile
#取负载 进行判断
Load=`uptime |awk -F[,\ .] '{print $17}'`
if [ $Load -gt "10" ];then
#把tcp连接大于三次的ip存入变量
tcp_connect_ip=`netstat -ntu|awk '{print $5}'|awk -F: '{print $1}'|awk -F '.' '{print $1"."$2"."$3"."}'|sort|uniq -c|sort -rn|awk '$1>3{print $2}'`
#进行循环 判断是否是官方蜘蛛和公司ip
for i in $tcp_connect_ip
do
if [[ $i =~ "192.168" ]] || [[ $i =~ "127." ]] || [[ $i =~ "180.76.189." ]] || [[ $i =~ "222.173.94." ]] || [[ $i =~ "172.16.16." ]] || [[ $i =~ "115.208.66.180." ]] || [[ $i =~ "116.179.32." ]] || [[ $i =~ "116.179.37." ]] || [[ $i =~ "220.181.108." ]] || [[ $i =~ "42.236.10." ]] || [[ $i =~ "42.236.43." ]]|| [[ $i =~ "180.163.220." ]] || [[ $i =~ "120.55.93." ]] || [[ $i =~ "180.76.154." ]] || [[ $i =~ "27.223.12." ]] || [[ $i =~ "110.249.201." ]] || [[ $i =~ "110.249.202." ]] || [[ $i =~ "111.225.148." ]] || [[ $i =~ "111.225.149." ]] || [[ $i =~ "220.243.188." ]] || [[ $i =~ "220.243.189." ]]
then
echo "$i is ok"
else
#精确当前时间
Time=`date +'%Y-%m-%d %H:%M:%S'`
#把当前时间做成时间戳
End_Time=$(date --date="$Time" +%s)
#把时间戳做成tag 打入到iptables规则中
iptables -I INPUT -s `echo $i|sed -nr 's#(.*)\.(.*)\.(.*)\.(.*)#\1.\2.\3.0\/24#gp'` -m comment --comment $(date --date="$Time" +%s) -j DROP
#根据时间找到四个小时以上的规则进行删除
iptables-save |grep comment|awk "\$8<$End_Time-14400{print}"|awk '{print "iptables -D " $2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13}'|bash
fi
done
#删除重复的规则
iptables-save|sort|uniq -c|sort -rn|awk '$1>1{print "iptables -D",$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13}'|bash
fi