![iptables 单个规则中的多个源 IP](https://linux22.com/image/482034/iptables%20%E5%8D%95%E4%B8%AA%E8%A7%84%E5%88%99%E4%B8%AD%E7%9A%84%E5%A4%9A%E4%B8%AA%E6%BA%90%20IP.png)
我想在 iptables 中创建一条使用多个源 IP 地址的规则(如果可能)。这可能吗?
答案1
这只有当你能将你想要的源 IP 聚合到一个连续的范围内时才有可能。例如
iptables -A INPUT -s 192.168.0.0/24 -d 192.168.0.5 -p tcp -j ACCEPT
如果您找不到涵盖所需 IP 的通用网络掩码,则您必须编写几个相同的规则来执行您想要的操作。
有多个 iptables 框架可以处理编写 iptables 规则的低级别工作,允许您在更符号化的级别上定义规则。岸墙是目前大多数 Linux 发行版中附带的常见程序。
答案2
要在单个命令中添加多个源,我会这样做:
iptables -t filter -A INPUT -s 192.168.1.1,2.2.2.2,10.10.10.10 -j ACCEPT
iptables 会自动将其翻译成多个规则。
答案3
最初的问题出现在 2009 年 5 月,但自 2011 年 5 月以来,Linux 内核有一项功能可以满足这一需求,称为ipset。
下面是一个创建 ipset、向其中添加地址然后在防火墙规则中使用它的示例:
ipset -N office365 iphash
ipset -A office365 132.245.228.194
ipset -A office365 132.245.77.34
ipset -A office365 132.245.48.34
ipset -A office365 132.245.68.242
ipset -A office365 132.245.55.2
ipset -A office365 40.101.17.98
ipset -A office365 132.245.48.18
ipset -A office365 132.245.229.114
ipset -A office365 132.245.196.34
ipset -A office365 132.245.56.114
iptables -A OUTPUT -m set --match-set office365 dst -j ACCEPT
请参阅man iptables
和man ipset
以了解更多信息。
答案4
除了Bòss King的注释之外,还可以简单指定多个地址,以逗号分隔:
[!] -s, --source address[/mask][,...]
Source specification. Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address. Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying
any name to be resolved with a remote query such as DNS is a really bad idea. The mask can be either a network mask or a plain number, specifying the number of 1's at the left side of the network mask. Thus, a mask of 24 is equivalent to
255.255.255.0. A "!" argument before the address specification inverts the sense of the address. The flag --src is an alias for this option. Multiple addresses can be specified, but this will expand to multiple rules (when adding with -A),
or will cause multiple rules to be deleted (with -D).