使用Python在Linux上检测防火墙存在性

0 投票
2 回答
853 浏览
提问于 2025-04-17 15:03

我想显示防火墙是否存在。如果防火墙没有开启,用户应该收到一个警告。这个可以用Python代码实现吗?

2 个回答

0

在GNU/Linux系统中,防火墙(netfilter)是内核的一部分,所以我觉得只要Linux系统开着,防火墙也就开着。

接下来,你可以检查一下netfilter是否已经配置好,以及有没有设置任何规则。为此,你可以查看iptables命令的输出,比如用命令iptables -L。

2

这是我在关闭防火墙的Redhat机器上执行的命令。

[root@epmauto-165-253 ~]# service iptables status
iptables: Firewall is not running.
[root@epmauto-165-253 ~]#
[root@epmauto-165-253 ~]# python
Python 2.6.6 (r266:84292, May  1 2012, 13:52:17)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> status = os.popen("service iptables status").read()
>>> print status
iptables: Firewall is not running.

>>>

而在另一台开启防火墙的Redhat机器上,我执行了以下命令。

[root@blr-srm-auto157 ~]# service iptables status
Table: filter
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination
1    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination

[root@blr-srm-auto157 ~]# python
Python 2.6.6 (r266:84292, Apr 11 2011, 15:50:32)
[GCC 4.4.4 20100726 (Red Hat 4.4.4-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> status = os.popen('service iptables status').read()
>>> print status
Table: filter
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
2    ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
5    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination
1    REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination


>>>

撰写回答