Skip to content

Instantly share code, notes, and snippets.

@oomatz
Created October 28, 2018 10:02
Show Gist options
  • Save oomatz/e33677be4732d211ae8592191016d897 to your computer and use it in GitHub Desktop.
Save oomatz/e33677be4732d211ae8592191016d897 to your computer and use it in GitHub Desktop.
netns内部からNATして外部通信可能にするサンプルスクリプト
#!/bin/bash
# mynets(network namespace)
# +--------------------------------+
# eth0 br0 172.31.0.1/24 | |
# +---------+ +--------------+ | |
# | | | | | +-------+ |
# | | | +-----+ | | | |
# +----+----+ | | veth+-------------------+ veth | 172.31.0.100/24 |
# | | +-----+ | | | |
# +----------+ | | +-------+ |
# NAT(MASQUERADE) | | | |
# +--------------+ | |
# +--------------------------------+
NS=mynets
BRIDGE=br0
BRIDGE_VETH=${BRIDGE}_veth
NS_VETH=${NS}_veth
GW="172.31.0.1"
NETWORK="172.31.0.0"
CLIENT_IP="172.31.0.100"
PREFIX=24
# Create bridge and network namespace
brctl addbr ${BRIDGE}
ip netns add ${NS}
# Create veth pair
ip link add ${BRIDGE_VETH} type veth peer name ${NS_VETH}
# Connect veth pair
## to bridge
brctl addif ${BRIDGE} ${BRIDGE_VETH}
## to namespace
ip link set ${NS_VETH} netns ${NS}
# Setup ip address
## for bridge
ip addr add ${GW}/${PREFIX} dev ${BRIDGE}
## for namespace
ip netns exec ${NS} ip addr add ${CLIENT_IP}/${PREFIX} dev ${NS_VETH}
# Make interfaces up
ip netns exec ${NS} ip link set ${NS_VETH} up
ip link set ${BRIDGE} up
ip link set ${BRIDGE_VETH} up
# routing
ip netns exec ${NS} ip route add default via ${GW}
## setup nat to access the internet
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s ${NETWORK}/${PREFIX} -j MASQUERADE
@oomatz
Copy link
Author

oomatz commented Oct 28, 2018

  • 通信確認
# ip netns exec mynets ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=5.81 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=119 time=6.46 ms
  • iptables(NAT)確認
# iptables -v -t nat -L
Chain PREROUTING (policy ACCEPT 1 packets, 84 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 1 packets, 69 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 1 packets, 69 bytes)
 pkts bytes target     prot opt in     out     source               destination
    1    84 MASQUERADE  all  --  any    any     172.31.0.0/24        anywhere

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment