在Debian系統中,可以使用 iptables 或 firewalld 來實現端口轉發。以下是兩種方法的詳細步驟:
firewalld 的端口轉發firewalld 是一個動態管理防火墻的工具,適用于CentOS 7及Debian系統。以下是使用 firewalld 進行端口轉發的步驟:
安裝 firewalld(如果尚未安裝):
sudo apt-get update
sudo apt-get install firewalld
啟動并啟用 firewalld 服務:
sudo systemctl start firewalld
sudo systemctl enable firewalld
開啟內核轉發:
echo 1 > /proc/sys/net/ipv4/ip_forward
編輯 firewalld 配置文件:
打開 /etc/firewalld/zones/public.xml 文件,并添加以下內容:
<?xml version="1.0" encoding="utf-8"?>
<zone>
<short>Public</short>
<description>For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
<service name="ssh"/>
<service name="dhcpv6-client"/>
<port protocol="tcp" port="10-65000"/>
<port protocol="udp" port="10-65000"/>
<masquerade/>
<forward-port to-addr="遠程IP" to-port="遠程端口" protocol="tcp" port="本地端口"/>
<forward-port to-addr="遠程IP" to-port="遠程端口" protocol="udp" port="本地端口"/>
</zone>
重啟 firewalld 服務以應用更改:
sudo systemctl restart firewalld
iptables 的端口轉發iptables 是一個強大的防火墻工具,適用于Debian和Ubuntu系統。以下是使用 iptables 進行端口轉發的步驟:
安裝 iptables(如果尚未安裝):
sudo apt-get update
sudo apt-get install iptables
啟動并啟用 iptables 服務:
sudo systemctl start iptables
sudo systemctl enable iptables
清空所有防火墻規則:
sudo iptables -F
sudo iptables -X
開啟內核轉發:
echo 1 > /proc/sys/net/ipv4/ip_forward
或者編輯 /etc/sysctl.conf 文件,取消以下行的注釋:
net.ipv4.ip_forward=1
然后運行以下命令使更改生效:
sudo sysctl -p
添加 iptables 規則:
將本地端口8080轉發到遠程服務器的80端口:
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 遠程服務器IP:80
為了確保數據包在本地和遠程服務器之間正確傳輸,需要添加一個 iptables 規則,將源地址偽裝為本地服務器的地址:
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
保存 iptables 規則:
sudo sh -c "iptables-save > /etc/iptables/rules.v4"
重啟 iptables 服務以應用更改:
sudo systemctl restart netfilter-persistent