共计 1574 个字符,预计需要花费 4 分钟才能阅读完成。
之前我曾经用 shell 脚本提取 lastb 登录失败超过指定次数的 IP 加入到 iptables,来禁止这些 IP 登录主机,达到防止恶意攻击的目的。后来为了给主机提供更全面的防护,又安装了 fail2ban。
root ssh:notty host-219-235-4-2 Thu Apr 23 19:32 – 19:32 (00:00)
root ssh:notty host-219-235-4-2 Thu Apr 23 19:32 – 19:32 (00:00)
root ssh:notty host-219-235-4-2 Thu Apr 23 19:32 – 19:32 (00:00)
root ssh:notty host-219-235-4-2 Thu Apr 23 19:32 – 19:32 (00:00)
root ssh:notty host-219-235-4-2 Thu Apr 23 19:32 – 19:32 (00:00)
root ssh:notty 61.160.247.150 Thu Apr 23 02:18 – 02:18 (00:00)
root ssh:notty 61.160.247.150 Thu Apr 23 02:18 – 02:18 (00:00)
root ssh:notty 61.160.247.150 Thu Apr 23 02:18 – 02:18 (00:00)
前面多了一个 host,而且 IP 的分隔是用“-”,最后一位的 IP 地址无法显示出来。
grep ‘Failed password for root from’ /var/log/secure|grep ‘219.235.4.22’
Apr 23 19:32:27 localhost sshd[17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:30 localhost sshd[17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:31 localhost sshd[17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:34 localhost sshd[17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:36 localhost sshd[17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
这时 IP 地址还有对方的端口都显示出来了,比 lastb 要详细的多。
#!/bin/bash
bad_ip=` grep ‘Failed password for root from’ /var/log/secure|awk ‘{print $11,$1,$2}’|sort|uniq -c|awk ‘$1>4 {print $2}’|xargs`
for ip in $bad_ip; do
in_iptables=`iptables -nvL|grep $ip |wc -l`
if [$in_iptables -eq 0]; then
iptables -I INPUT -s $ip -j REJECT
service iptables save
fi
done
执行一下,成功!