From dacee0f550656e55dea5f02674470962d485cca0 Mon Sep 17 00:00:00 2001 From: zxb <919411476@qq.com> Date: Fri, 3 Nov 2023 10:56:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=88=96=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=97=B6=20=E8=87=AA=E5=8A=A8=E4=BF=9D=E5=AD=98=20iptables=20?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=20=E6=B7=BB=E5=8A=A0=20service=20=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E6=96=87=E4=BB=B6=20=E5=90=AF=E5=8A=A8=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E6=97=B6=E5=8A=A0=E8=BD=BD=E5=B7=B2=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E7=9A=84=E8=A7=84=E5=88=99=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iptables-helper.service | 12 ++++++++++++ pkg/utils/iptables/handler.go | 12 ++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 iptables-helper.service diff --git a/iptables-helper.service b/iptables-helper.service new file mode 100644 index 0000000..db5cf55 --- /dev/null +++ b/iptables-helper.service @@ -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 \ No newline at end of file diff --git a/pkg/utils/iptables/handler.go b/pkg/utils/iptables/handler.go index 89c5c96..9939c14 100644 --- a/pkg/utils/iptables/handler.go +++ b/pkg/utils/iptables/handler.go @@ -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) +}