use*_*047 8 iptables command-line scripts connection
一些 IP 正在打开我服务器的数千个连接。我有一台 Ubuntu 14 服务器。我使用以下命令检查总连接数:
netstat -an | grep tcp | awk '{print $5}' | 切 -f 1 -d : | 排序 | uniq -c | 排序 -n
然后我使用以下 iptables 规则来阻止罪魁祸首 IP。
iptables -I 输入 1 -s xxxx -j DROP
它工作正常并阻止IP地址。但是,我无法 24/7 全天候在线监控服务器。我想知道是否有任何可以用来自动执行此操作的 Shell 脚本?例如,如果一个 IP 在任何时候打开超过 X 个连接,它应该被上述 iptables 规则自动禁止。
ter*_*don 10
首先,不要重新发明轮子。这正是denyhosts用于:
DenyHosts is a python program that automatically blocks ssh attacks by
adding entries to /etc/hosts.deny. DenyHosts will also inform Linux
administrators about offending hosts, attacked users and suspicious
logins.
Run Code Online (Sandbox Code Playgroud)
据我所知,denyhosts仅用于ssh连接,但也
fail2ban涉及几乎任何事情:
Fail2Ban consists of a client, server and configuration files to limit
brute force authentication attempts.
The server program fail2ban-server is responsible for monitoring log
files and issuing ban/unban commands. It gets configured through a
simple protocol by fail2ban-client, which can also read configuration
files and issue corresponding configuration commands to the server.
Run Code Online (Sandbox Code Playgroud)
两者都在存储库中可用:
sudo apt-get install denyhosts fail2ban
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您也可以编写此脚本。就像是:
#!/usr/bin/env sh
netstat -an |
awk -vmax=100 '/tcp/{split($5,a,":"); if(a[1] > 0 && a[1]!="0.0.0.0"){c[a[1]]++}}
END{for(ip in c){if(c[ip]>max){print ip}}}' |
while read ip; do iptables -I INPUT 1 -s "$ip" -j DROP; done
Run Code Online (Sandbox Code Playgroud)
在awk将提取的IP地址,并指望他们和只打印那些出现超过max倍(这里-vmax=100,相应修改)。然后将 IP 输入到运行相关iptables规则的 while 循环中。
要运行这个 24/7,我会做一个 cronjob,每分钟左右运行一次上面的命令。将此行添加到/etc/crontab
* * * * * root /path/to/script.sh
Run Code Online (Sandbox Code Playgroud)