在使用Ubuntu的iptables时,用户可能会遇到各种常见问题。以下是一些常见问题的解决方案:
无法SSH远程连接
- 问题现象:配置完服务器后,突然发现SSH连接断开。
- 解决方案:
- 放行SSH端口:
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
- 允许已建立的连接:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
- 设置默认策略为DROP(谨慎操作):
iptables -P INPUT DROP
- 放行SSH端口:
服务器总被Ping洪水攻击
- 问题现象:监控警报显示ICMP流量激增。
- 解决方案:
- 允许正常Ping但限制频率:
iptables -A INPUT -p icmp --icmp-type 8 -m limit --limit 5/s -j ACCEPT
- 记录超限的Ping请求:
iptables -A INPUT -p icmp -j LOG --log-prefix "ICMP_Attack: "
- 丢弃过量请求:
iptables -A INPUT -p icmp -j DROP
- 允许正常Ping但限制频率:
网站端口开了却访问不了
- 问题现象:Nginx监听80端口,但外网无法访问。
- 解决方案:
- 允许80端口流量:
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
- 如果是网关服务器,需开启转发:
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
- DNAT端口映射:
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to 192.168.1.100:80
- 允许80端口流量:
服务重启后规则丢失
- 问题现象:精心配置的规则,重启后全部消失。
- 解决方案:
- 规则存储:
iptables-save > /etc/iptables.rules
- 开机加载:
iptables-restore < /etc/iptables.rules
- 持久化方案:
- CentOS 6及以下:
service iptables save
- Ubuntu/Debian:
apt install iptables-persistent
和netfilter-persistent save
- 通用方法(推荐加入开机脚本):
iptables-save > /etc/iptables.rules
和echo "pre-up iptables-restore < /etc/iptables.rules" >> /etc/network/interfaces
- CentOS 6及以下:
- 规则存储:
如何快速封禁恶意IP
- 问题现象:日志中发现某个IP频繁暴力破解。
- 解决方案:
- 创建IP黑名单集合:
ipset create blacklist hash:ip timeout 86400
- 动态封禁恶意IP(可结合fail2ban):
iptables -A INPUT -m set --match-set blacklist src -j DROP
- 限制SSH并发连接(防爆破):
iptables -A INPUT -p tcp --dport 22 -m connlimit --connlimit-above 3 -j REJECT
- 创建IP黑名单集合: