Bash脚本以动态创建虚拟网络接口

问题描述 投票:1回答:1

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

服务器当前具有一个公共网络接口(eth0)。我正在尝试将为每个用户提供其他“虚拟”网络接口的设置合并到bash脚本中。这应该允许每个用户拥有一个单独的内部IP地址,该地址应该能够通过设置NAT规则来访问Internet。无论将每个用户重定向到哪个地理服务器,都将始终为其提供相同的内部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规则。

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

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

ubuntu networking iptables nat virtual-network
1个回答
0
投票

我能够通过如下创建具有两个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
© www.soinside.com 2019 - 2024. All rights reserved.