欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ubuntu双网卡主机给其他主机共享网络

程序员文章站 2022-06-03 21:15:46
...
  1. 设备:
    1. Ubuntu主机(主机1)有两张网卡:eno1(外网), eno2(内网)
    2. 其他主机(主机2)有一张网卡:eno1(连接第一台主机的eno2)
  2. 目标:
    • 主机1给主机2共享网络。

    • 步骤:

      1. 配置主机1的两张网卡:

        推荐使用netplan。

        example:

        # Let NetworkManager manage all devices on this system
        network:
        version: 2
        #  renderer: NetworkManager
        renderer: networkd
        ethernets:
             eno1:
                     addresses: [192.168.3.50/24]
                     gateway4: 192.168.3.1
                     dhcp4: no
                     nameservers:
                             addresses: [114.114.114.114]
                     optional: true
             eno2:
                     addresses: [192.168.0.1/24]
                     gateway4: 192.168.3.50
                     dhcp4: no
                     nameservers:
                             addresses: [114.114.114.114]
                         optional: true
        
      2. 开启主机1ipv4转发:

        sudo vim /etc/sysctl.conf
        /ipv4.ip_forwar                 # 直接回车
        ^                               # 到行首
        x                               # 删除`#`
        :wq                             # 保存并退出
        
      3. 开启主机1包过滤:

        sudo iptables -P INPUT ACCEPT
        sudo iptables -P FORWARD ACCEPT
        sudo iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -o eno1 -j MASQUERADE
        sudo service networking restart
        

        最后一行一定写对,前面ip/mask是子网的网段/掩码,-o指向输出端口(外网网卡)

        sudo iptables-save > /etc/iptables.rules        # 保存
        sudo iptables-restore < /etc/iptables.rules     # 恢复
        
      4. 主机2网卡配置:

        # Let NetworkManager manage all devices on this system
        network:
          version: 2
          #  renderer: NetworkManager
          renderer: networkd
          ethernets:
                  eno1:
                          addresses: [192.168.0.x/24]   # x in [2,254]
                          gateway4: 192.168.0.1         # eno2的ip address
                          dhcp4: no
                          nameservers:
                                  addresses: [114.114.114.114]
                          optional: true
        
      5. 配置生效:两主机都要执行

        sudo netplan try
        sudo netplan apply