首页 > 解决方案 > 用于动态创建虚拟网络接口的 Bash 脚本

问题描述

我正在编写一个 bash 应用程序,它在 Ubuntu 18.04 服务器集群上运行,并在部署在不同地理区域的多台服务器之间配置和同步用户帐户。服务器允许用户根据他们当前的位置被重定向到适当的地理服务器,然后授予他们 SSH shell 访问权限。

服务器目前只有一个公网接口(eth0)。我正在尝试为每个用户提供额外的“虚拟”网络接口到 bash 脚本中。这应该允许每个用户拥有一个单独的内部 IP 地址,该地址应该能够通过设置 NAT 规则访问互联网。无论他们被重定向到哪个地理服务器,每个用户都将始终获得相同的内部 IP 地址。

例如,以下配置文件为登录的每个用户定义了虚拟接口名称和 IP 地址。此配置文件使用我编写的 REST API 在每个服务器之间同步:

{
  "users": [
    {
      "username": "user0",
      "interface": "veth0",
      "ip_address": "192.168.1.0"
    },
    {
      "username": "user1",
      "interface": "veth1",
      "ip_address": "192.168.1.1"
    },
    {
      "username": "user2",
      "interface": "veth2",
      "ip_address": "192.168.1.2"
    },
    {
      "username": "user3",
      "interface": "veth3",
      "ip_address": "192.168.1.3"
    }
  ]
} 

如果 user2 登录到服务器,bash 脚本会自动创建相应的接口和 IP,如下所示:

ip link add type $interface
ifconfig $interface $ip_address

这会将以下内容添加到 ifconfig 输出:

veth2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
    inet 192.168.1.2  netmask 255.255.255.0  broadcast 192.168.1.255
    ether a6:e7:de:40:9a:28  txqueuelen 1000  (Ethernet)
    RX packets 27  bytes 2082 (2.0 KB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 1132  bytes 48520 (48.5 KB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

我在服务器上将“/proc/sys/net/ipv4/ip_forward”设置为 1 以启用 IP 转发,但我无法确定要添加到启动脚本中的正确 iptables MASQUERADE、FORWARD 和 NAT 规则。

到目前为止,我无法从虚拟接口访问互联网。

我似乎无法弄清楚我做错了什么,任何帮助将不胜感激。

标签: ubuntunetworkingiptablesnatvirtual-network

解决方案


我能够通过使用两个 veth 对自动创建网络命名空间来解决这个问题,如下所示:

#!/bin/bash

#enable port forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

#create network namespace (netns0)
ip netns add $netns

#add loopback interface to namespace
ip netns exec $netns ip link set lo up

#create veth pairs
ip link add $vetha type veth peer name $vethb

#add $vethb to namespace
ip link set $vethb netns $netns

#add ip addresses to interfaces
ip addr add $ip1 dev $vetha
ip netns exec $netns ip addr add $ip2 dev $vethb

#enable interfaces
ip link set $vetha up
ip netns exec $netns ip link set $vethb up

#enable ip forwarding and nating with iptables
iptables -A FORWARD -o eth0 -i $vetha -j ACCEPT
iptables -A FORWARD -i eth0 -o $vetha -j ACCEPT
iptables -t nat -A POSTROUTING -s $ip2 -o eth0 -j MASQUERADE

#add default route to namespace
ip netns exec $netns ip route add default via $ip1

#set dns servers for namespace
mkdir -p /etc/netns/netns0
echo "nameserver 1.1.1.1" > /etc/netns/netns0/resolv.conf

推荐阅读