Created
January 6, 2020 17:41
-
-
Save phhusson/bd024f6f5fa91ba1320d10f2d59fa6bd to your computer and use it in GitHub Desktop.
Runs a program in a program within a netns that temporary steals a host interface
This file contains hidden or 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
| #!/bin/bash | |
| #This script "steals" an interface from the host to a temporary network namespace | |
| #Then, Linux will release the interface back to the host | |
| #Teardown is guaranteed by kernel when all pid with iface/netns are dead | |
| iface="$1" | |
| shift | |
| cmd="" | |
| while [ "$#" -ge 1 ];do | |
| cmd="$cmd $(printf '%q' "$1")" | |
| shift | |
| done | |
| pidfile=$(mktemp) | |
| ( | |
| if ! unshare -nfp --mount-proc bash -c " | |
| #This is the pid of the (), not unshared!& | |
| echo $$ > $pidfile | |
| while [ -f $pidfile ];do sleep .1;done | |
| $cmd || true | |
| kill -9 -1 || true | |
| ";then | |
| echo shit | |
| echo shit > $pidfile | |
| fi | |
| ) & | |
| while [ ! -s "$pidfile" ];do | |
| sleep .1 | |
| done | |
| #Pid of subshell | |
| pid=$(cat $pidfile) | |
| if [ "$pid" = "shit" ];then | |
| echo shit... | |
| exit 1 | |
| fi | |
| #Pid of unshare | |
| pid=$(pgrep -P $pid) | |
| #Pid of shell inder unshare | |
| pid=$(pgrep -P $pid) | |
| ip link set dev "$iface" netns $(pgrep -P $pid) | |
| rm -f $pidfile | |
| wait |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment