📜  如何在 Linux 中设置防火墙?(1)

📅  最后修改于: 2023-12-03 14:52:25.486000             🧑  作者: Mango

如何在 Linux 中设置防火墙?

在 Linux 中,防火墙是保护计算机安全的重要组件。它可以过滤来自网络的流量,防止恶意攻击和未经授权的访问。Linux 系统默认使用 iptables 防火墙,但也可以使用其他防火墙工具,如 firewalld、ufw 等。

本文将介绍如何在 Linux 中使用 iptables 和 firewalld 两种主流防火墙设置进行防火墙设置。

使用 iptables
安装 iptables

大多数 Linux 发行版都默认安装了 iptables,如果您的系统未安装 iptables,可以使用以下命令安装:

sudo apt-get update
sudo apt-get install iptables
配置 iptables

使用 iptables 防火墙,需要编辑 iptables 规则集,在规则集中定义允许和禁止的网络流量。以下是一个简单的 iptables 规则集示例,允许 HTTP 和 SSH 流量:

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 80 -j ACCEPT
保存 iptables 配置

默认情况下,iptables 规则集不会在系统重启后保存。要保存 iptables 配置,需要使用以下命令:

sudo iptables-save > /etc/iptables/rules.v4
应用 iptables 配置

要应用新的 iptables 配置,需要使用以下命令:

sudo iptables-restore < /etc/iptables/rules.v4
使用 firewalld
安装 firewalld

大多数 Linux 发行版都已经集成了 firewalld。如果您的系统未安装 firewalld,请使用以下命令安装:

sudo apt-get update
sudo apt-get install firewalld
配置 firewalld

Firewalld 使用“区域”来托管服务,允许网络流量进入和离开特定的区域。以下示例将 HTTP 和 SSH 服务添加到“public”区域:

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --permanent --zone=public --add-service=ssh
保存和应用 firewalld 配置

要保存和应用新的 firewalld 配置,需要使用以下命令:

sudo firewall-cmd --reload

以上介绍了使用 iptables 和 firewalld 配置防火墙的基本步骤,您可以根据需要进行调整。防火墙是保护计算机安全的重要组件,必须小心配置,以保证安全。