Skip to content

Instantly share code, notes, and snippets.

@4piu
Created November 1, 2021 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4piu/b08bbe0c544116f5a1135545454bc5ec to your computer and use it in GitHub Desktop.
Save 4piu/b08bbe0c544116f5a1135545454bc5ec to your computer and use it in GitHub Desktop.
Create A Network Namespace with the NATed Internet
#!/usr/bin/env sh
NAMESPACE=nat
VETH_IP_HOST=10.0.0.1/24
VETH_IP_NS=10.0.0.2/24
# check root permission
if [ "$(id -u)" != "0" ]; then
echo "Please run as root"
exit 1
fi
# parse current network config
iname=$(ip -o link show | sed -rn '/^[0-9]+: en/{s/.: ([^:]*):.*/\1/p}') # enp34s0 / eth0 / eno0
on() {
# create namespace
ip netns add $NAMESPACE
# create veth pair
ip link add veth-default type veth peer name veth-$NAMESPACE
# assign one end of the veth to the namespace
ip link set veth-$NAMESPACE netns $NAMESPACE
# assign IP to the veth ends
ip addr add $VETH_IP_HOST dev veth-default
ip netns exec $NAMESPACE ip addr add $VETH_IP_NS dev veth-$NAMESPACE
# bring up the veth
ip link set veth-default up
ip netns exec $NAMESPACE ip link set lo up
ip netns exec $NAMESPACE ip link set veth-$NAMESPACE up
# add default route in the namespace
ip netns exec $NAMESPACE ip route add default via $(echo $VETH_IP_HOST | cut -f1 -d'/')
# enable IPv4 forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# enable iptables masquerade
iptables -t nat -A POSTROUTING -s $VETH_IP_NS -o $iname -j MASQUERADE
echo "Namespace '$NAMESPACE' created"
}
off() {
ip netns del $NAMESPACE
echo 0 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -D POSTROUTING -s $VETH_IP_NS -o $iname -j MASQUERADE
}
if [ "$1" = "on" ]; then
on
elif [ "$1" = "off" ]; then
off
else
echo -e "Invalid args! \nUsage: netns.sh [on|off]"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment