Skip to content

Instantly share code, notes, and snippets.

@style95
Created May 5, 2022 02:39
Show Gist options
  • Save style95/96d8f1b426586801ff9f76e9c5396118 to your computer and use it in GitHub Desktop.
Save style95/96d8f1b426586801ff9f76e9c5396118 to your computer and use it in GitHub Desktop.
#!/bin/bash
veth_in_use=()
veth_all=()
for container in $(docker ps --format '{{.Names}}'); do
pid=$(docker inspect --format '{{.State.Pid}}' $container)
ifindex=$(nsenter -t $pid -n ip link | sed -n -e 's/.*eth0@if\([0-9]*\):.*/\1/p')
if [ -z "$ifindex" ]; then
echo "container:$container doesn't have veth"
else
veth=$(ip -o link | grep ^$ifindex: | sed -n -e 's/.*\(veth[[:alnum:]]*\).*/\1/p')
veth_in_use+=($veth)
fi
done
for i in $(brctl show | grep veth | awk '{print $(NF)}')
do
veth_all+=($i)
done
exist_orphaned=false
delete_orphaned=true
for i in "${veth_all[@]}"
do
for j in "${veth_in_use[@]}"
do
[[ $i == "$j" ]] && continue 2
done
ip link set $i down
ip link delete $i
if [ $? -ne 0 ]; then
echo "deleted orphaned veth: ${i} failed"
delete_orphaned=false
else
echo "deleted orphaned veth: ${i} successfully"
fi
exist_orphaned=true
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment