Skip to content

Instantly share code, notes, and snippets.

@scrool
Last active October 3, 2020 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scrool/ff3fabb94cd178964fcb31b237041ea6 to your computer and use it in GitHub Desktop.
Save scrool/ff3fabb94cd178964fcb31b237041ea6 to your computer and use it in GitHub Desktop.
#!/usr/bin/bash
# Reads WiFi connections managed by NetworkManager. Ignores connections
# not in ifcfg-rh format
# <https://developer.gnome.org/NetworkManager/stable/nm-settings-ifcfg-rh.html>
# Leaves out UUID, HWADDR and NAME from comparison of config file content.
# If any files are duplicated, removes oldest connections based on timestamp
set -eu
set -o pipefail
basedir="/etc/sysconfig/network-scripts"
function wifi_connection_filenames()
{
nmcli -m tabular -f type,filename -t connection show \
| grep 802-11-wireless: \
| cut -d : -f 2 \
| grep "$basedir"
}
function hash_config()
{
egrep -v '^UUID=|^HWADDR=|^NAME=' "$1" \
| sha1sum \
| awk '{print $1 }' \
| tr -d '\n'
}
function sorted_config_hashes()
{
while IFS= read -r filename
do
hash=$(hash_config "$filename")
echo "$hash $filename"
done | sort -t ' ' -k 1
}
function duplicate_hashes()
{
awk '{ print $1 }' \
| uniq -c \
| ( grep -v ' 1 ' || true ) \
| awk '{print $NF}'
}
function oldest_duplicate_uuids()
{
sch=$(wifi_connection_filenames | sorted_config_hashes)
duplicate_hashes <<< "$sch" | while IFS= read -r duplicate
do
for filename in $(echo "$sch" | grep "^$duplicate " | awk '{ print $2 }')
do
uuid=$(grep "UUID=" "$filename" | cut -f2 -d '=')
nmcli -m tabular -t -f connection.timestamp,connection.uuid connection show "$uuid" | xargs echo || continue
done | sort -t ' ' -k 1 | sed '$d'
done | awk '{ print $NF }'
}
function main()
{
duplicates=$(oldest_duplicate_uuids)
if [ -z "$duplicates" ]
then
echo "No duplicates found."
return
else
echo "Duplicate UUIDs:"
echo "$duplicates"
xargs --no-run-if-empty nmcli connection delete <<< "$duplicates"
fi
}
main
#
# Copyright (c) 2020 Pavol Babinčák. All rights reserved.
#
#This work is licensed under the terms of the MIT license.
#For a copy, see <https://opensource.org/licenses/MIT>.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment