修改或删除时 自动保存 iptables 配置

添加 service 配置文件
启动服务时加载已保存的规则文件
This commit is contained in:
zxb 2023-11-03 10:56:17 +08:00
parent 1a3f513741
commit dacee0f550
2 changed files with 24 additions and 0 deletions

12
iptables-helper.service Normal file
View File

@ -0,0 +1,12 @@
[Unit]
Description=Iptables Helper
After=network.target
[Service]
Environment="HOME=/root"
ExecStartPre=iptables-restore /etc/iptables.rule
ExecStart=/opt/iptables-helper/iptables-helper
Restart=on-failure
[Install]
WantedBy=multi-user.target

View File

@ -62,6 +62,9 @@ func AddRule(rule Rule) error {
cmd := command.Commander{}
_, err = cmd.ExecuteWithResult("sudo iptables " + strings.Join(args, " "))
if err == nil {
SaveRule()
}
return err
}
@ -70,5 +73,14 @@ func DelRuleByCmd(cmd string) error {
cmd = strings.Split(cmd, "&")[0]
commander := command.Commander{}
_, err := commander.ExecuteWithResult("sudo iptables -D " + cmd)
if err == nil {
SaveRule()
}
return err
}
func SaveRule() {
cmd := "sh -c \"iptables-save | tee /etc/iptables.rule\""
commander := command.Commander{}
commander.Execute("sudo " + cmd)
}