如何在Linux中设置防火墙?代码举例讲解

在Linux中,可以通过以下方式设置防火墙:

  1. 使用iptables配置防火墙:
    iptables是Linux上默认的防火墙软件,配置文件在/etc/iptables.rules。常用命令有:
# 列出防火墙规则 
sudo iptables -L

# 删除所有规则
sudo iptables -F  

# 允许所有OUTGOING流量 
sudo iptables -P OUTPUT ACCEPT  

# 拒绝所有INCOMING流量 
sudo iptables -P INPUT DROP  

# 允许SSH连接 
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT  

# 保存规则  
sudo iptables-save > /etc/iptables.rules

配置文件示例:

*filter

# 允许所有OUTGOING流量
-P OUTPUT ACCEPT  

# 拒绝所有INCOMING流量 
-P INPUT DROP  

# 允许SSH连接
-A INPUT -p tcp --dport 22 -j ACCEPT  

# 允许ping
-A INPUT -p icmp -j ACCEPT  

# 允许http/https
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

# 保存配置
-A OUTPUT -j SAVE

*nat

# Leave this chain empty
*mangle 
# Leave this chain empty  
  1. 使用firewallD配置防火墙:
    firewallD是Linux上更易于使用的防火墙配置工具,配置文件在/etc/firewalld/目录下。常用命令有:
# 启动/重启/停止firewallD 
sudo systemctl start/restart/stop firewalld  

# 查看状态 
firewall-cmd --state

# 添加规则 - 允许ssh连接  
firewall-cmd --permanent --add-service=ssh  

# 重新加载规则
firewall-cmd --reload  

# 移除规则  - 禁止http连接  
firewall-cmd --permanent --remove-service=http  

# 查看规则  
firewall-cmd --list-all