2026-10-25 10:43:31
在Linux中实现网络隔离的核心方法是通过配置VLAN划分逻辑网络,并结合iptables或nftables设置防火墙规则。具体步骤如下:
一、VLAN配置Debian/Ubuntu系统:使用命令sudo apt-get install vlan。
CentOS/RHEL系统:使用命令sudo yum install vconfig。

创建VLAN接口:
假设物理网卡为eth0,创建VLAN ID为10和20的接口,命令如下:sudo vconfig add eth0 10sudo vconfig add eth0 20
配置VLAN接口IP地址:
编辑网络配置文件,Debian/Ubuntu系统编辑/etc/network/interfaces,CentOS/RHEL系统编辑/etc/sysconfig/network-scripts/ifcfg-eth0.10等文件,示例配置如下:# eth0.10auto eth0.10iface eth0.10 inet static address 192.168.10.1 netmask 255.255.255.0 vlan-raw-device eth0# eth0.20auto eth0.20iface eth0.20 inet static address 192.168.20.1 netmask 255.255.255.0 vlan-raw-device eth0
重启网络服务使配置生效,Debian/Ubuntu系统使用sudo systemctl restart networking,CentOS/RHEL系统使用sudo systemctl restart network。
阻止VLAN间通信:
默认情况下VLAN间可通信,使用以下命令阻止VLAN 10和VLAN 20间通信:sudo iptables -A FORWARD -i eth0.10 -o eth0.20 -j DROPsudo iptables -A FORWARD -i eth0.20 -o eth0.10 -j DROP
允许特定VLAN访问Internet:
若希望VLAN 10可访问Internet而VLAN 20不行,配置NAT规则如下(假设连接到Internet的网卡为eth1):sudo iptables -t nat -A POSTROUTING -o eth1 -s 192.168.10.0/24 -j MASQUERADEsudo iptables -A FORWARD -i eth0.10 -o eth1 -j ACCEPTsudo iptables -A FORWARD -i eth1 -o eth0.10 -m state --state RELATED,ESTABLISHED -j ACCEPT
保存防火墙规则:
Debian/Ubuntu系统使用sudo iptables-save > /etc/iptables/rules.v4。
CentOS/RHEL系统使用sudo service iptables save,确保重启后规则仍有效。
创建文件/etc/nftables.conf,示例内容如下:table inet filter { chain input { type filter hook input priority 0; policy drop; iifname "lo" accept ct state {established, related} accept tcp dport 22 accept icmp type echo-request accept reject with icmp type port-unreachable } chain forward { type filter hook forward priority 0; policy drop; iifname "eth0.10" oifname "eth0.20" drop iifname "eth0.20" oifname "eth0.10" drop iifname "eth0.10" oifname "eth1" accept iifname "eth1" oifname "eth0.10" ct state {established, related} accept reject with icmp type port-unreachable } chain output { type filter hook output priority 0; policy accept; }}table ip nat { chain postrouting { type nat hook postrouting priority 100; policy accept; oifname "eth1" ip saddr 192.168.10.0/24 masquerade }}

使用命令sudo nft -f /etc/nftables.conf应用配置。
启动并启用nftables服务,命令为sudo systemctl enable nftables和sudo systemctl start nftables。
假设VLAN 10中主机IP为192.168.10.10,VLAN 20中主机IP为192.168.20.20。在VLAN 10主机上ping 192.168.20.20,若配置正确应ping不通,反之亦然。
使用traceroute命令查看数据包路由路径,使用tcpdump抓包分析网络流量情况。
Network Namespaces:提供完全隔离的网络环境,每个namespace有独立网络接口、路由表和防火墙规则,适用于容器技术等高度隔离场景。
网络桥接和流量整形:通常用于更复杂网络架构。
范围是1到4094,避免与已有ID冲突,选择有管理意义的ID,如VLAN 10用于开发环境,VLAN 20用于测试环境等,VLAN ID 1通常为默认VLAN,不建议使用。
定期检查防火墙规则和VLAN配置,使用iptables -L或nft list ruleset查看防火墙规则,使用ip link show查看VLAN接口配置。
可使用Nagios或Zabbix等网络监控工具,监控网络流量和连接状态,及时发现异常。