Skip to content

Instantly share code, notes, and snippets.

@Lu-Yi-Hsun
Forked from dpino/ns-inet.sh
Last active December 1, 2019 18:08
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 Lu-Yi-Hsun/708155264a436ca3e33551f26ea25630 to your computer and use it in GitHub Desktop.
Save Lu-Yi-Hsun/708155264a436ca3e33551f26ea25630 to your computer and use it in GitHub Desktop.
Setup a network namespace with Internet access
#!/usr/bin/env bash
IFACE="$1"
NS="$2"
VETH="veth1"
VPEER="vpeer1"
VETH_ADDR="10.200.1.1"
VPEER_ADDR="10.200.1.2"
if [[ $EUID -ne 0 ]]; then
echo "請用權限執行此bash"
exit 1
fi
trap cleanup EXIT
cleanup()
{
ip li delete ${VETH} 2>/dev/null
}
exist_namespace=$(ip netns list | grep -w "${NS}")
if [ -z "$exist_namespace" ]
then
echo "請看Step 3 先新增namespace"
exit 1
fi
# Create veth link.
ip link add ${VETH} type veth peer name ${VPEER}
# Add peer-1 to NS.
ip link set ${VPEER} netns $NS
# Setup IP address of ${VETH}.
ip addr add ${VETH_ADDR}/24 dev ${VETH}
ip link set ${VETH} up
# Setup IP ${VPEER}.
ip netns exec $NS ip addr add ${VPEER_ADDR}/24 dev ${VPEER}
ip netns exec $NS ip link set ${VPEER} up
ip netns exec $NS ip link set lo up
ip netns exec $NS ip route add default via ${VETH_ADDR}
# Enable IP-forwarding.
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush forward rules.
iptables -P FORWARD DROP
iptables -F FORWARD
# Flush nat rules.
iptables -t nat -F
# Enable masquerading of 10.200.1.0.
iptables -t nat -A POSTROUTING -s ${VPEER_ADDR}/24 -o ${IFACE} -j MASQUERADE
iptables -A FORWARD -i ${IFACE} -o ${VETH} -j ACCEPT
iptables -A FORWARD -o ${IFACE} -i ${VETH} -j ACCEPT
# Get into namespace
ip netns exec ${NS} /bin/bash --rcfile <(echo "PS1=\"${NS}> \"")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment