Quantcast
Channel: Active questions tagged 22.04 - Ask Ubuntu
Viewing all articles
Browse latest Browse all 4452

Ubuntu Server binded two network cards, How do I specify an ip for a shell in a folder

$
0
0

I bought a Ubuntu Server with two network cards:

Run ip address show, result is:

  • 172.31.0.2 public ip is 101.47.30.28
  • 172.31.0.3 public ip is 101.47.55.42

ip address show result

Run route -n, result is:

route -n result

I had created two folders: hh01/, hh02/, each folder had a a.sh, both content is:

#!/bin/bashwhile true; do    PUBLIC_IP=$(curl -s https://api.ipify.org)    echo "Current Public ip address:$PUBLIC_IP"    sleep 3done

And now I want to assign a fixed ip address to each folder, such as:

  • hh01/a.sh should echo 101.47.30.28
  • hh02/a.sh should echo 101.47.55.42

I had try this shell, but it do not work:

#!/bin/bash# 设置变量hh01_IP="172.31.0.2"hh02_IP="172.31.0.3"hh01_VETH="veth0"hh02_VETH="veth1"hh01_VPEER="veth0-peer"hh02_VPEER="veth1-peer"DEFAULT_GW="172.31.0.1"# 创建网络命名空间ip netns add hh01ip netns add hh02# 创建 veth 对ip link add "$hh01_VETH" type veth peer name "$hh01_VPEER"ip link add "$hh02_VETH" type veth peer name "$hh02_VPEER"# 将 veth 对的一端移动到命名空间ip link set "$hh01_VPEER" netns hh01ip link set "$hh02_VPEER" netns hh02# 配置主命名空间中的 veth 接口ip addr add "$hh01_IP"/24 dev "$hh01_VETH"ip addr add "$hh02_IP"/24 dev "$hh02_VETH"ip link set "$hh01_VETH" upip link set "$hh02_VETH" up# 配置命名空间中的 veth 接口ip netns exec hh01 ip addr add "$hh01_IP"/24 dev "$hh01_VPEER"ip netns exec hh02 ip addr add "$hh02_IP"/24 dev "$hh02_VPEER"ip netns exec hh01 ip link set "$hh01_VPEER" upip netns exec hh02 ip link set "$hh02_VPEER" up# 启用网络命名空间内的 lo 接口ip netns exec hh01 ip link set lo upip netns exec hh02 ip link set lo up# 配置默认路由ip netns exec hh01 ip route add default via "$DEFAULT_GW" dev "$hh01_VPEER"ip netns exec hh02 ip route add default via "$DEFAULT_GW" dev "$hh02_VPEER"# 配置策略路由,使每个命名空间通过不同的接口访问外部网络ip rule add from "$hh01_IP" lookup 100ip rule add from "$hh02_IP" lookup 200ip route add 172.31.0.0/20 dev eth0 src "$hh01_IP" table 100ip route add default via "$DEFAULT_GW" dev eth0 table 100ip route add 172.31.0.0/20 dev eth1 src "$hh02_IP" table 200ip route add default via "$DEFAULT_GW" dev eth1 table 200# 启动 pm2 进程,将其移入网络命名空间ip netns exec hh01 pm2 start /root/hh01/a.sh --name test-hh01ip netns exec hh02 pm2 start /root/hh02/a.sh --name test-hh02# 保留 SSH 和其他服务在默认网络命名空间echo "配置完成!"echo "test-hh01 进程运行在网络命名空间 hh01"echo "test-hh02 进程运行在网络命名空间 hh02"

Viewing all articles
Browse latest Browse all 4452

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>