Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
mynetns_run: Run a program in a seperate network namespace
#!/bin/bash -e
NETNS_FILE=/var/run/netns/mynet
MNTNS_FILE=/var/run/ns/mynet_mnt
if [[ ! -f $NETNS_FILE ]]; then
ip netns add mynet
ip link add mynet0 type veth peer name mynet1
ip link set mynet0 up
ip link set mynet1 netns mynet
brctl addif br0 mynet0
ip netns exec mynet ip link set mynet1 up
ip netns exec mynet ip address add dev mynet1 192.168.57.101/24
ip netns exec mynet ip route add default via 192.168.57.1
fi
if [[ ! -f $MNTNS_FILE ]]; then
mnt_dir=$(dirname $MNTNS_FILE)
mkdir -p "$mnt_dir"
mount --bind "$mnt_dir" "$mnt_dir"
mount --make-private "$mnt_dir"
echo 'nameserver 192.168.57.1' > $MNTNS_FILE
unshare --mount=$MNTNS_FILE mount --bind $MNTNS_FILE /etc/resolv.conf
fi
exec nsenter --mount=$MNTNS_FILE --net=$NETNS_FILE sudo -u lilydjwg DISPLAY=:0 LANG=zh_CN.UTF-8 LANGUAGE=zh_CN:zh_TW GTK_IM_MODULE=fcitx QT_IM_MODULE=fcitx XMODIFIERS=@im=fcitx DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus TMUX=1 "$@"
Owner

lilydjwg commented May 13, 2016

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