在Ubuntu中,使用iptables實(shí)現(xiàn)NAT轉(zhuǎn)換需要配置IPv4轉(zhuǎn)發(fā)和設(shè)置相應(yīng)的NAT規(guī)則
/etc/sysctl.conf
文件,取消或添加以下行:net.ipv4.ip_forward=1
保存文件并運(yùn)行以下命令使更改生效:
sudo sysctl -p
sudo apt-get update
sudo apt-get install iptables
nat_rules
的腳本,包含以下內(nèi)容:#!/bin/sh
# 清除現(xiàn)有規(guī)則
iptables -t nat -F
iptables -t nat -X
# 設(shè)置SNAT規(guī)則
# 將源IP地址從內(nèi)部網(wǎng)絡(luò)(例如192.168.1.0/24)更改為外部接口(例如eth0)的IP地址
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.0/24 -j SNAT --to-source $(ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
# 設(shè)置DNAT規(guī)則
# 將目標(biāo)IP地址更改為內(nèi)部主機(jī)(例如192.168.1.100)的IP地址
iptables -t nat -A PREROUTING -i eth0 -d $(ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}') -j DNAT --to-destination 192.168.1.100
請根據(jù)您的網(wǎng)絡(luò)環(huán)境修改腳本中的IP地址和接口名稱。
chmod +x nat_rules
./nat_rules
/etc/rc.local
文件中。如果/etc/rc.local
不存在,請創(chuàng)建一個:#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
/path/to/nat_rules
exit 0
請確保將/path/to/nat_rules
替換為實(shí)際腳本路徑。然后,使/etc/rc.local
可執(zhí)行:
chmod +x /etc/rc.local
現(xiàn)在,您已經(jīng)在Ubuntu上使用iptables實(shí)現(xiàn)了NAT轉(zhuǎn)換。