Skip to content

Instantly share code, notes, and snippets.

@Apsu
Last active December 4, 2015 03:06
Show Gist options
  • Save Apsu/ce0c8a56a685cc75f2ed to your computer and use it in GitHub Desktop.
Save Apsu/ce0c8a56a685cc75f2ed to your computer and use it in GitHub Desktop.
Find veth pairs on the host which are not in any running containers
#!/usr/bin/env bash
# Create associative arrays
declare -A interior=()
declare -A exterior=()
# Make sure ethtool is installed on this host
apt-get install -y ethtool &>/dev/null
# For each container
for container in $(lxc-ls)
do
# For each list of ifindex:ifname pairs, sorted by ifindex, skipping loopback (lo)
for items in $(awk -F': ' '{print $1 ":" $2}' < <(lxc-attach -n $container -- ip -o l | sort -n | tail -n+2))
do
# For each ifindex:ifname pairs
for item in "${items[@]}"
do
# Split into ifindex and ifname
index=$(echo $item | awk -F':' '{print $1}')
name=$(echo $item | awk -F':' '{print $2}')
# Add entry keyed on ifindex => ifname and container name
interior+=([$index]="$name $container")
done
done
done
# For each ifindex:ifname pair where ifname contains 'veth'
for item in $(ip -o l | grep veth | awk -F': ' '{print $1 ":" $2}')
do
# Split into ifindex and ifname
index=$(echo $item | awk -F':' '{print $1}')
name=$(echo $item | awk -F':' '{print $2}')
# Extract peer ifindex from ethtool
peer=$(ethtool -S $name | awk '/peer_ifindex/ {print $2}')
# Add entry keyed on interior peer's ifindex => ifname
exterior+=([$peer]=$name)
done
# For each peer (interior) ifindex
for peer in "${!exterior[@]}"
do
# Store exterior ifname for this veth pair
extname=${exterior[$peer]}
# If this peer ifindex was also found inside the container
if [[ -n ${interior[$peer]} ]]
then
# Split out values into ifname and container name
items=(${interior[$peer]})
name="${items[0]}"
container="${items[1]}"
echo "Found peer for interface $extname => $peer:$name in $container"
# Otherwise the exterior veth is dangling; delete it!
else
# This section redirects to stderr only
# You can filter just for this output with: $script 1>/dev/null
echo "Peer $peer for interface $extname not in a container!" >&2
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment