In general, you can edit the active iptables rules for IPv4 with a text editor by using the iptables-save
command to write the rules to a file and then using the iptables-restore
command to reload the new rules after you're done, e.g.:
user@host:~$ iptables-save > rules.v4
user@host:~$ vim rules.v4
user@host:~$ iptables-restore rules.v4
For IPv6 you would use the analogous commands ip6tables-save
and ip6tables-restore
, i.e.:
user@host:~$ ip6tables-save > rules.v6
user@host:~$ vim rules.v6
user@host:~$ ip6tables-restore rules.v6
The iptables-persistent
service checks in the following locations:
/etc/iptables/rules.v4
/etc/iptables/rules.v6
So to apply your rules and have them persist you would follow the same steps as above, but edit the iptables-persistent
files instead, e.g.:
user@host:~$ iptables-save > /etc/iptables/rules.v4
user@host:~$ vim /etc/iptables/rules.v4
user@host:~$ iptables-restore /etc/iptables/rules.v4
I don't know of an interactive command for editing iptables rules like what you're describing, but it should be pretty easy to roll your own. Here is a simple example:
#!/usr/bin/env bash
# iptables-e.sh
# Create a temporary file to store the new rules
TEMPFILE=$(mktemp)
# Save the current rules to a file
iptables-save > "${TEMPFILE}"
# Edit the rules interactively with a text editor
"${EDITOR}" "${TEMPFILE}"
# Try to load the rules and update the persistent rules if no errors occur
iptables-restore "${TEMPFILE}" && cat "${TEMPFILE}" > /etc/iptables/rules.v4
This actually isn't too much different from how crontab -e
works, which just automatically saves the active crontab to a file in the /var/spool/cron/crontabs
directory, which is what causes the crontab to be persistent. See the following post for further discussion of this subject:
You might also be interested in the following script:
I can't vouch for it though. I've never used it. It's just the only thing I found by searching for interactive iptables editing.
sudo apt-get install iptables-persistent
sudo iptables-save | sudo tee -a /etc/iptables/rules.v4
That's all.
– user84207 Jul 21 '23 at 00:24