Skip to content

Instantly share code, notes, and snippets.

@blead
Forked from kheminw/ns-inet.sh
Last active March 7, 2019 16:49
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 blead/c4d41dc22b610867222f5814f4cb1f91 to your computer and use it in GitHub Desktop.
Save blead/c4d41dc22b610867222f5814f4cb1f91 to your computer and use it in GitHub Desktop.
Setup a network namespace with Internet access
#!/usr/bin/env bash
set -x
NS="mysql"
VETH="vethmysql"
VPEER="vpeermysql"
VETH_ADDR="10.200.1.1"
VPEER_ADDR="10.200.1.2"
if [[ $EUID -ne 0 ]]; then
echo "You must be root to run this script"
exit 1
fi
# Remove namespace if it exists.
ip netns del $NS &>/dev/null
# Create namespace
ip netns add $NS
# 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
#!/usr/bin/env bash
set -x
NS="wp"
VETH="vethwp"
VPEER="vpeerwp"
VETH_ADDR="10.200.2.1"
VPEER_ADDR="10.200.2.2"
if [[ $EUID -ne 0 ]]; then
echo "You must be root to run this script"
exit 1
fi
# Remove namespace if it exists.
ip netns del $NS &>/dev/null
# Create namespace
ip netns add $NS
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment