iptables常用命令

iptables常用命令
小妖iptables 是 Linux 上常用的防火墙工具,用于设置、维护和检查 IP 数据包过滤规则。以下是一些常用的 iptables 命令和规则:
基本命令
查看当前规则
1
sudo iptables -L
- sudo iptables -L -v: 显示详细信息
- sudo iptables -L -n: 不进行反向域名解析,显示数字格式
清除所有规则
1
sudo iptables -F
删除特定规则
1
sudo iptables -D <chain> <rule_number>
例如:
1
sudo iptables -D INPUT 1
设置默认策略
1
sudo iptables -P <chain> <policy>
例如,拒绝所有输入:
1
sudo iptables -P INPUT DROP
规则管理
允许所有本地回环接口通信
1
sudo iptables -A INPUT -i lo -j ACCEPT
允许已有的、相关的连接
1
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
允许特定端口的入站连接
例如,允许 HTTP (端口 80) 和 HTTPS (端口 443):1
2sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT允许特定 IP 地址的连接
例如,允许 192.168.1.100 的所有连接:1
sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
拒绝特定 IP 地址的连接
例如,拒绝 192.168.1.101 的所有连接:1
sudo iptables -A INPUT -s 192.168.1.101 -j DROP
限制 SSH 登录尝试
防止暴力破解,限制 SSH 连接尝试次数:1
2sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
网络地址转换 (NAT)
配置源地址转换 (SNAT)
例如,将 192.168.1.0/24 网络的出站流量的源 IP 改为 203.0.113.1:1
sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 203.0.113.1
配置端口地址转换 (DNAT)
例如,将外部流量的端口 8080 转发到内部网络 192.168.1.100 的端口 80:1
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80
配置 IP 伪装 (Masquerading)
适用于动态 IP 地址,如拨号连接:1
sudo iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
保存和恢复规则
保存规则
在 Ubuntu/Debian 中:1
sudo sh -c "iptables-save > /etc/iptables/rules.v4"
在 CentOS/RHEL 中:
1
sudo service iptables save
恢复规则
在 Ubuntu/Debian 中:1
sudo iptables-restore < /etc/iptables/rules.v4
在 CentOS/RHEL 中:
1
sudo service iptables restart
这些命令涵盖了 iptables 的基础操作,可以帮助你设置和管理防火墙规则以保护你的 Linux 系统。
评论
匿名评论隐私政策










