Is there a way to move a rule in the iptables
and change it position ? I'm aware i can use -I
to insert a rule in a specific position, but i also like to keep the counters.
5 Answers
You can also do following
- Write the output of
iptables-save
to a file:iptables-save > /tmp/iptables.txt
- Edit this file with a text editor, move whichever line you want.
- Reload the file:
iptables-restore < /tmp/iptables.txt

- 82,805

- 2,553
-
2slaps forehead – chb Aug 09 '22 at 04:31
No, you cannot move a rule. However, you can set the counter for any rule you add/insert/replace (using the -c
or --set-counters
parameter). So you could check the current count, delete the rule and reinsert it with the old count value.

- 1,794
- 1
- 10
- 12
To see what you have and what you want to change you first need to do some examination.
- Check for counters and write these somewhere so you can enter them later.
iptables-save -c
- Check for the line you want to replace / reposition using
iptables -L -v -n --line-n
- Write the rule in the designated CHAIN and add the counters explained in step on. For example.
iptables -R INPUT 5 -i virbr0 -p udp -m udp -c 3441 472271 --dport 53 -j ACCEPT -m comment --comment "Some comment"
Meaning of -c
-c [packets:bytes]
The above iptables rule will be entered on line 5.
You can save the current iptables (and counters) by doing
iptables-save -c -f /somepath/iptrules-$(date +%F)

- 22,803

- 9,344
Display iptables lines number:
iptables -L --line-numbers -n
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT all -- 192.6.3.2 anywhere
2 ACCEPT all -- 192.6.3.1 anywhere
3 ACCEPT all -- 192.6.3.0 anywhere
Let's say that you want to move the rule Nb 3 to the rule Nb 2 do this:
iptables -I INPUT 2 -s 192.6.3.0 -j ACCEPT
-I: to insert
INPUT: Name of the chain
2: Position number where you want to insert the chain
-s 192.6.3.0 -j ACCEPT: rule to insert at the position number
Delete your old rule Nb 3 which is now in position Nb 4:
iptables -D INPUT 4
As we insert a new rule, the old rule that was in the third position is now in the fourth position.

- 223
-
-
-
I was aware of this method, but the key part was to keep the rule counter, and this is where the
-c
option come. So in the end I was not able to move a rule, but to reinsert it in the new position, and remove the old rule. (which mimic a rule move) – Rabin Dec 29 '22 at 08:46
Adding to the answer from Valentin Bajrami:
if you have your current iptables rules and counters to a file using
iptables-save -c -f /somepath/iptrules-$(date +%F)
you can then modify the file with your required changes
nano /somepath/iptrules-$(date +%F)
then restore with counters by doing
iptables-restore -c /somepath/iptrules-$(date +%F)
Both commands above could be replaced with ip6tables if you're dealing with ipv6

- 116,213
- 16
- 160
- 287

- 123
- 1
- 6