溫馨提示×

Debian防火墻端口轉發方法

小樊
76
2025-02-24 10:40:29
欄目: 智能運維

在Debian系統中,可以使用 iptablesfirewalld 來實現端口轉發。以下是兩種方法的詳細步驟:

基于 firewalld 的端口轉發

firewalld 是一個動態管理防火墻的工具,適用于CentOS 7及Debian系統。以下是使用 firewalld 進行端口轉發的步驟:

  1. 安裝 firewalld(如果尚未安裝):

    sudo apt-get update
    sudo apt-get install firewalld
    
  2. 啟動并啟用 firewalld 服務

    sudo systemctl start firewalld
    sudo systemctl enable firewalld
    
  3. 開啟內核轉發

    echo 1 > /proc/sys/net/ipv4/ip_forward
    
  4. 編輯 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>
    
  5. 重啟 firewalld 服務以應用更改

    sudo systemctl restart firewalld
    

基于 iptables 的端口轉發

iptables 是一個強大的防火墻工具,適用于Debian和Ubuntu系統。以下是使用 iptables 進行端口轉發的步驟:

  1. 安裝 iptables(如果尚未安裝):

    sudo apt-get update
    sudo apt-get install iptables
    
  2. 啟動并啟用 iptables 服務

    sudo systemctl start iptables
    sudo systemctl enable iptables
    
  3. 清空所有防火墻規則

    sudo iptables -F
    sudo iptables -X
    
  4. 開啟內核轉發

    echo 1 > /proc/sys/net/ipv4/ip_forward
    

    或者編輯 /etc/sysctl.conf 文件,取消以下行的注釋:

    net.ipv4.ip_forward=1
    

    然后運行以下命令使更改生效:

    sudo sysctl -p
    
  5. 添加 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
    
  6. 保存 iptables 規則

    sudo sh -c "iptables-save > /etc/iptables/rules.v4"
    
  7. 重啟 iptables 服務以應用更改

    sudo systemctl restart netfilter-persistent
    

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女