Last active
June 30, 2023 14:09
-
-
Save CatoLynx/48a490da66796bbad08dff75345b6048 to your computer and use it in GitHub Desktop.
Bash script to append aliases to peer IDs in Wireguard output
This file contains 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 | |
# To the extent possible under law, I hereby waive all copyright | |
# and related or neighboring rights to this program. | |
# Determine the path of this script, to read the aliases file relative to that | |
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) | |
# Check if the unbuffer command is available. | |
# It is used to retain colored output from wg show | |
if [ -x "$(command -v unbuffer)" ]; then | |
has_unbuffer=true | |
else | |
has_unbuffer=false | |
fi | |
# Read the wg_aliases.txt file and store the contents in an associative array | |
declare -A aliases | |
while read -r line; do | |
peer_id=$(echo "$line" | awk '{print $1}') | |
alias=$(echo "$line" | cut -d' ' -f2-) | |
aliases["$peer_id"]="$alias" | |
done < "$parent_path/wg_aliases.txt" | |
# Get the WireGuard connection status | |
if [ "$has_unbuffer" = true ] ; then | |
wg_output=$(unbuffer wg show) | |
else | |
wg_output=$(wg show) | |
fi | |
# Iterate over each line of the wg output | |
while IFS= read -r line; do | |
# Check if line contains "peer" | |
if [[ $line == *peer* ]]; then | |
# Extract the peer ID | |
peer_id=$(echo "$line" | sed -e 's@\x1b\[[0-9;]*m@@g' | awk '{print $2}') | |
# Check if the line is not empty | |
if [[ -n $peer_id ]]; then | |
# Check if the peer ID has an alias | |
if [[ -n ${aliases["$peer_id"]} ]]; then | |
# Get the alias for the peer ID | |
alias="${aliases["$peer_id"]}" | |
# Modify the line to include the alias in parenthesis | |
modified_line=$(echo "$line" | sed "s@$peer_id@$peer_id ($alias)@") | |
# Print the modified line | |
echo -e "$modified_line" | |
else | |
# Print the line as is if no alias is found | |
echo "$line" | |
fi | |
else | |
echo "$line" | |
fi | |
else | |
echo "$line" | |
fi | |
done <<< "$wg_output" |
This file contains 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
uLqAm7B9StcjwwtL9ZWPteh2kFbtkpZziQwab8joU5i= Node 1 | |
oVo972LTd6ASJN4AFqn7jSp9uYEgc47FxJtw5FDxj2E= Node 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment