From c1c401747a295e13e7e1255f01868db6bb0f9ac8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E5=AE=8F=E6=98=9F?= Date: Tue, 6 Jun 2023 10:11:13 +0800 Subject: [PATCH] Added Replace method to replace rulespec (in specified pos) --- iptables/iptables.go | 6 ++++++ iptables/iptables_test.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/iptables/iptables.go b/iptables/iptables.go index 1e7ad24..8d04bb6 100644 --- a/iptables/iptables.go +++ b/iptables/iptables.go @@ -186,6 +186,12 @@ func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) er return ipt.run(cmd...) } +// Replace replaces rulespec to specified table/chain (in specified pos) +func (ipt *IPTables) Replace(table, chain string, pos int, rulespec ...string) error { + cmd := append([]string{"-t", table, "-R", chain, strconv.Itoa(pos)}, rulespec...) + return ipt.run(cmd...) +} + // InsertUnique acts like Insert except that it won't insert a duplicate (no matter the position in the chain) func (ipt *IPTables) InsertUnique(table, chain string, pos int, rulespec ...string) error { exists, err := ipt.Exists(table, chain, rulespec...) diff --git a/iptables/iptables_test.go b/iptables/iptables_test.go index 92ed271..cc2de33 100644 --- a/iptables/iptables_test.go +++ b/iptables/iptables_test.go @@ -309,6 +309,21 @@ func runRulesTests(t *testing.T, ipt *IPTables) { t.Fatalf("Delete failed: %v", err) } + err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT") + if err != nil { + t.Fatalf("Insert failed: %v", err) + } + + err = ipt.Replace("filter", chain, 1, "-s", subnet2, "-d", address2, "-j", "ACCEPT") + if err != nil { + t.Fatalf("Replace failed: %v", err) + } + + err = ipt.Delete("filter", chain, "-s", subnet2, "-d", address2, "-j", "ACCEPT") + if err != nil { + t.Fatalf("Delete failed: %v", err) + } + err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT") if err != nil { t.Fatalf("Append failed: %v", err)