在Linux系统上,可以通过多种方式实现网络访问控制。以下是几种常见的方法:
iptables是Linux内核内置的防火墙工具,可以基于规则控制网络访问。
# 查看当前规则
sudo iptables -L -n -v
# 允许特定IP访问
sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
# 允许特定端口访问
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT # 允许SSH
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT # 允许HTTP
# 默认拒绝所有其他连接
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
# 保存规则(根据发行版不同)
sudo iptables-save > /etc/iptables.rules
nftables是iptables的替代品,语法更简洁:
# 创建表
sudo nft add table inet filter
# 创建链
sudo nft add chain inet filter input { type filter hook input priority 0 \; }
# 添加规则
sudo nft add rule inet filter input tcp dport 22 accept
sudo nft add rule inet filter input ct state established,related accept
sudo nft add rule inet filter input drop
# 持久化规则
sudo nft list ruleset > /etc/nftables.conf
通过/etc/hosts.allow和/etc/hosts.deny文件控制:
# /etc/hosts.allow
sshd: 192.168.1.0/24
httpd: 192.168.1.100
# /etc/hosts.deny
ALL: ALL
sudo ufw enable
sudo ufw allow 22/tcp
sudo ufw allow from 192.168.1.100
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" accept'
sudo firewall-cmd --reload
对于更高级的控制,可以使用网络命名空间:
# 创建网络命名空间
sudo ip netns add restricted_net
# 在命名空间中运行程序
sudo ip netns exec restricted_net ping google.com
需要更具体的配置方案,请提供您的具体需求场景(如Web服务器保护、数据库访问控制等)。