Skip to content

Instantly share code, notes, and snippets.

@phhusson
Created January 6, 2020 17:41
Show Gist options
  • Select an option

  • Save phhusson/bd024f6f5fa91ba1320d10f2d59fa6bd to your computer and use it in GitHub Desktop.

Select an option

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
#!/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