要实现 CentOS 上的 iptables 自动化,你可以使用以下方法:
创建一个脚本文件,例如 iptables.sh,并在其中添加你需要的 iptables 规则。例如:
#!/bin/bash
# 清除现有规则
iptables -F
iptables -X
# 设置默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# 允许已建立的连接
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# 允许 SSH 连接
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# 允许本地回环接口的连接
iptables -A INPUT -i lo -j ACCEPT
# 允许特定 IP 地址访问
iptables -A INPUT -s 192.168.1.100 -j ACCEPT
# 保存规则
service iptables save
给脚本添加可执行权限:
chmod +x iptables.sh
然后运行脚本:
./iptables.sh
你可以将此脚本添加到系统启动项中,以便在每次启动时自动应用规则。
iptables-services:iptables-services 是一个用于管理 iptables 规则的服务。首先,确保已安装此软件包:
sudo yum install iptables-services
然后启动并启用 iptables 服务:
sudo systemctl start iptables
sudo systemctl enable iptables
现在,你可以使用 systemctl 命令来管理 iptables 规则。例如,要停止 iptables 服务:
sudo systemctl stop iptables
要重新加载规则:
sudo systemctl reload iptables
firewalld:firewalld 是 CentOS 7 中的默认防火墙管理工具。要安装 firewalld,请运行:
sudo yum install firewalld
启动并启用 firewalld 服务:
sudo systemctl start firewalld
sudo systemctl enable firewalld
现在,你可以使用 firewall-cmd 命令来管理防火墙规则。例如,要允许 SSH 连接:
sudo firewall-cmd --permanent --add-service=ssh
要重新加载规则:
sudo firewall-cmd --reload
注意:firewalld 和 iptables 不兼容,因此在 CentOS 7 中使用 firewalld 时,需要卸载 iptables-services 软件包。