安装工具
apt update && apt install net-tools
分析脚本
curl -sS -O https://raw.githubusercontent.com/woniu336/open_shell/main/monitor_without_logs.sh && chmod +x monitor_without_logs.sh && ./monitor_without_logs.sh
连接数超过100的IP
netstat -tn | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | awk '$1 > 100 {print $1 " connections from " $2}'
前10个连接数最多的IP
netstat -tn | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10
防火墙
限制该IP最多200个连接
iptables -A INPUT -s 3.3.3.3 -m connlimit --connlimit-above 200 -j DROP
验证规则是否生效
iptables -L INPUT -n --line-numbers | grep 3.3.3.3
实时监控效果
watch "netstat -an | grep 3.3.3.3 | wc -l"
效果验证
ss -tuln | grep 3.3.3.3 | wc -l
查看iptables丢弃统计
iptables -L INPUT -v -n | grep 3.3.3.3
如果确认问题解决,可以移除规则
iptables -D INPUT -s 3.3.3.3 -m connlimit --connlimit-above 200 -j DROP
或者调整为更宽松的限制
iptables -R INPUT 1 -s 3.3.3.3 -m connlimit --connlimit-above 100 -j DROP
设置定期监控
crontab -e
添加以下行,每10分钟检查一次
*/10 * * * * /root/monitor_without_logs.sh >> /var/log/haproxy_monitor.log 2>&1
查看日志
cat /var/log/haproxy_monitor.log
高峰期需求估算
curl -sS -O https://raw.githubusercontent.com/woniu336/open_shell/main/peak_estimation.sh && chmod +x peak_estimation.sh && ./peak_estimation.sh
查看当前连接的唯一IP数量
netstat -tn | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | wc -l
查看连接分布情况
netstat -tn | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -20
查看443端口的具体连接数
netstat -tn | grep :443 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | wc -l
看所有443端口连接的状态分布
netstat -tn | grep :443 | awk '{print $6}' | sort | uniq -c
看平均每个IP的连接数
echo "scale=2; 3454/3598" | bc
查看总连接数
netstat -tn | grep ESTABLISHED | wc -l