在Linux虚拟主机环境中,封禁恶意IP地址是保护服务器安全的重要措施。以下是多种封禁IP的方法和最佳实践:
iptables -A INPUT -s 192.168.1.100 -j DROPiptables -A INPUT -s 192.168.1.0/24 -j DROPiptables -A INPUT -s 123.45.67.89 -p tcp --dport 22 -j DROP # 封禁SSH访问
iptables -A INPUT -s 123.45.67.89 -p tcp --dport 80 -j DROP # 封禁HTTP访问iptables-save > /etc/sysconfig/iptables # CentOS/RHEL
iptables-save > /etc/iptables/rules.v4 # Debian/Ubuntufirewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" reject'
firewall-cmd --reloadfirewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" reject'
firewall-cmd --reloadufw deny from 192.168.1.100ufw deny from 123.45.67.89 to any port 22 # 封禁SSH
ufw deny from 123.45.67.89 to any port 80 # 封禁HTTP# Debian/Ubuntu
apt install fail2ban
# CentOS/RHEL
yum install fail2ban编辑 /etc/fail2ban/jail.local:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600systemctl restart fail2banecho "sshd: 192.168.1.100" >> /etc/hosts.deny
echo "ALL: 123.45.67.89" >> /etc/hosts.deny # 封禁所有服务#!/bin/bash
# 封禁1分钟内连接数超过100次的IP
netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n | \
while read count ip; do
if [ "$count" -gt 100 ]; then
iptables -A INPUT -s "$ip" -j DROP
echo "$(date) 封禁IP: $ip (连接数: $count)" >> /var/log/ip_ban.log
fi
doneiptables -L INPUT -n --line-numbersfail2ban-client status sshdiptables -D INPUT -s 192.168.1.100 -j DROPfail2ban-client set sshd unbanip 192.168.1.100