ubuntu20.04添加iptables规则

先把系统当前的规则保存下来

# 保存规则
iptables-save > /home/ubuntu/iptables/rules.v4
ip6tables-save > /home/ubuntu/iptables/rules.v6

新建iptabels.sh然后保存

#!/bin/bash

# 加载规则
iptables-restore < /home/ubuntu/iptables/rules.v4
ip6tables-restore < /home/ubuntu/iptables/rules.v6

请将/home/ubuntu/iptables/rules.v4和/home/ubuntu/iptables/rules.v6替换为您希望保存规则的实际路径。

在保存脚本后,您可以使用以下命令将其添加到系统启动脚本中:

sudo cp /home/ubuntu/iptables/iptables.sh /etc/init.d/
sudo update-rc.d iptables.sh defaults

这将确保在每次系统重启时自动加载iptables规则。

在较新的Ubuntu版本中,推荐使用systemd来管理启动脚本。您可以按照以下步骤将iptables.sh脚本添加为开机启动脚本:

将iptables.sh脚本复制到/etc/systemd/system/目录下:

sudo cp /home/ubuntu/iptables/iptables.sh /etc/systemd/system/

使用文本编辑器打开iptables.sh文件:

sudo nano /etc/systemd/system/iptables.sh

在文件的开头添加以下内容:

#!/bin/bash
保存并关闭文件。

运行以下命令以使脚本可执行:

sudo chmod +x /etc/systemd/system/iptables.sh

创建一个iptables.service文件:

sudo nano /etc/systemd/system/iptables.service

在文件中添加以下内容:

[Unit]
Description=Iptables Service

[Service]
ExecStart=/etc/systemd/system/iptables.sh

[Install]
WantedBy=multi-user.target
保存并关闭文件。

运行以下命令以重新加载systemd守护进程:

sudo systemctl daemon-reload

启用iptables.service并设置为开机启动:

sudo systemctl enable iptables.service

现在,iptables.sh脚本将在系统启动时自动运行。您可以使用以下命令来启动、停止或重新启动脚本:

启动脚本:

sudo systemctl start iptables.service

停止脚本:

sudo systemctl stop iptables.service

重新启动脚本:

sudo systemctl restart iptables.service

所有原创文章采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可。
您可以自由的转载和修改,但请务必注明文章来源并且不可用于商业目的。
本站部分内容收集于互联网,如果有侵权内容、不妥之处,请联系我们删除。敬请谅解!

添加新评论

  关于博主

当你发现自己的才华撑不起野心时,就请安静下来学习吧

  近期评论

要铭记在心:每天都是一年中最美好的日子。

生活远没有咖啡那么苦涩,关键是喝它的人怎么品味!每个人都喜欢和向往随心所欲的生活,殊不知随心所欲根本不是生活。

如果错过了太阳时你流泪了,那么你也要错过群星了。

不如意的时候不要尽往悲伤里钻,想想有笑声的日子吧。

我不明白为什么要那么在意别人的看法,评头论足只是无聊人的消遣,何必看得如临大敌。如果你不吃别人家的饭,就别太把别人的话放在心上。