1、首先是防攻击脚本,原理是扫描/var/log/secure文件,发现一小时内尝试密码错误超过30次的ip,则
将该ip加入iptables黑名单drop掉。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#!/usr/bin/env perl my $LIMIT=30; my $log="/var/log/secure"; my $LOGFILE="/data/block_ip.log"; my $TIME=`date '+%b %e %H'`; chomp $TIME; my $BLOCK_IP; my %hash; open(FD,$log)||die("Can not open the file!$!n"); while(<FD>){ chomp; if ( /$TIME/ and /Failed password/ ) { my @line=split; my $ip=$line[-4]; $hash{$ip}++; } } close(FD); for(%hash) { if ($hash{$_} > $LIMIT) { my $IP=$_; $ips= `iptables-save`; $mo= qr(/INPUT/ and /DROP/ and /$IP/); unless ($ips=~$mo) { `iptables -I INPUT -s $IP -j DROP`; my $NOW=`date '+%Y-%m-%d %H:%M'`; chomp $NOW; `echo -e "$NOW : $IP" >>$LOGFILE`; } } } |
2、将该脚本保存为block_ssh.sh
3、创建一个上传任务,把该文件上传到远程服务器,给予执行权限。加入crontab 每5分钟执行一次。
1 2 3 4 5 6 7 |
task "upload", group =>"all", sub { say connection->server.":begin upload files!"; upload "block_ssh.sh", "/root/block_ssh.sh"; run "chmod 755 /root/block_ssh.sh"; run 'echo "*/5 * * * * root /root/block_ssh.sh" >>/etc/crontab'; say connection->server.":upload success!"; }; |