Last active
November 1, 2021 09:58
-
-
Save 4piu/28e8d4ae7bda02311bf75804629332bd to your computer and use it in GitHub Desktop.
Create A Network Namespace Using a Bypass Gateway
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
NAMESPACE=proxy | |
GATEWAY=172.16.1.15 | |
STATIC_IP= #172.16.1.97/24 | |
DNS_SERVER=172.16.1.1 | |
# 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 | |
on() { | |
# create namespace | |
ip netns add $NAMESPACE | |
# create macvlan | |
ip link add macvlan-$NAMESPACE link $iname type macvlan mode bridge | |
# assign macvlan to the namespace | |
ip link set macvlan-$NAMESPACE netns $NAMESPACE | |
# make resolve.conf | |
mkdir -p /etc/netns/$NAMESPACE | |
touch /etc/netns/$NAMESPACE/resolv.conf | |
# bring up the interfaces | |
ip netns exec $NAMESPACE ip link set lo up | |
ip netns exec $NAMESPACE ip link set macvlan-$NAMESPACE up | |
# set IP address of the macvlan interface | |
[ -z "$STATIC_IP" ] && ip netns exec $NAMESPACE dhclient macvlan-$NAMESPACE || ip netns exec $NAMESPACE ip addr add $STATIC_IP dev macvlan-$NAMESPACE | |
sleep 1 | |
# add default route in the namespace | |
[ -z "$STATIC_IP" ] && ip netns exec $NAMESPACE ip route del default | |
ip netns exec $NAMESPACE ip route add default via $GATEWAY | |
# custom dns | |
[ -z "$DNS_SERVER" ] || echo "nameserver $DNS_SERVER" > /etc/netns/$NAMESPACE/resolv.conf | |
echo "Namespace '$NAMESPACE' created with gateway '$GATEWAY'" | |
} | |
off() { | |
ip netns del $NAMESPACE | |
rm -rf /etc/netns/$NAMESPACE | |
} | |
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