系统为ubuntu18.04版本:
首先配置iptables:
1 2 3 4 | iptables -t nat -A PREROUTING -p tcp -m tcp --dport 1000:10000 -j DNAT --to-destination 20.20.20.1:1000-10000 iptables -t nat -A PREROUTING -p udp -m udp --dport 1000:10000 -j DNAT --to-destination 20.20.20.1:1000-10000 iptables -t nat -A POSTROUTING -d 20.20.20.1 -p tcp -m tcp --dport 1000:10000 -j SNAT --to-source 10.10.10.1 iptables -t nat -A POSTROUTING -d 20.20.20.1 -p udp -m udp --dport 1000:10000 -j SNAT --to-source 10.10.10.1 |
查看配置:iptables -L -t nat
保存iptables配置到文件:/etc/iptables.rules
1 | iptables-save > /etc/iptables.rules |
重启系统后,使配置生效,需要运行命令
1 | iptables-restore < /etc/iptables.rules |
可能由于系统环境,以下两种方式失败:
在/etc/network/interfaces文件中添加iptables-restore < /etc/iptables.rules命令,重启系统,iptables配置未生效
在/etc/network/if-pre-up.d/中添加脚本的方式,重启系统,iptables配置依然失败
成功解决方法:
vim /etc/rc.local
1 2 | #!/bin/sh iptables-restore < /etc/iptables.rules |
chmod +x /etc/rc.local
vim /lib/systemd/system/rc.local.service(实例系统已经配置了这个文件,如果没有,请手动配置)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # SPDX-License-Identifier: LGPL-2.1+ # # This file is part of systemd. # # systemd is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # This unit gets pulled automatically into multi-user.target by # systemd-rc-local-generator if /etc/rc.local is executable. [Unit] Description=/etc/rc.local Compatibility Documentation=man:systemd-rc-local-generator(8) ConditionFileIsExecutable=/etc/rc.local After=network.target [Service] Type=forking ExecStart=/etc/rc.local start TimeoutSec=0 RemainAfterExit=yes GuessMainPID=no |
systemctl enable rc.local
重启系统测试,iptables配置生效,问题解决
参考文章:https://ilouis.cn/ubuntu/ubuntu_setting_iptables.html
-----------日常记录---------------