在 CentOS 系统中,使用 iptables
命令可以设置防火墙规则,以允许特定 IP 地址访问服务器。以下是一些基本步骤和示例命令,帮助你配置 iptables
以允许特定 IP 访问。
假设你想允许 IP 地址 192.168.1.100
访问服务器的所有端口,可以使用以下命令:
sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
如果你只想允许特定 IP 访问服务器的特定端口(例如,允许 192.168.1.100
访问端口 80 和 443),可以使用以下命令:
sudo iptables -A INPUT -p tcp -s 192.168.1.100 --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp -s 192.168.1.100 --dport 443 -j ACCEPT
如果你需要允许多个特定 IP 访问,可以重复上述命令,或者使用 -m iprange
模块来指定一个 IP 范围:
sudo iptables -A INPUT -m iprange --src-range 192.168.1.100-192.168.1.110 -j ACCEPT
iptables
规则默认情况下,iptables
规则在系统重启后会丢失。为了使规则永久生效,你需要保存这些规则。CentOS 7 及以上版本使用 firewalld
服务来管理防火墙规则,而 CentOS 6 使用 iptables-persistent
。
使用 firewalld
服务:
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" accept'
sudo firewall-cmd --reload
使用 iptables-persistent
服务:
sudo service iptables-persistent save
iptables
规则你可以使用以下命令查看当前的 iptables
规则:
sudo iptables -L -n -v
iptables
规则之前,建议先备份当前的规则,以便在需要时可以恢复。firewalld
服务,确保它已启用并正在运行:sudo systemctl status firewalld
sudo systemctl start firewalld
通过以上步骤,你应该能够成功配置 iptables
以允许特定 IP 地址访问你的 CentOS 服务器。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>