Skip to content

Instantly share code, notes, and snippets.

@Gunni
Last active June 28, 2019 00:14
Show Gist options
  • Save Gunni/42c764ed8ae2c0c6e1315a55866ba701 to your computer and use it in GitHub Desktop.
Save Gunni/42c764ed8ae2c0c6e1315a55866ba701 to your computer and use it in GitHub Desktop.
Wireguard prettifier
#!/usr/bin/python3
'''
The script looks for a line similar to:
PublicKey=eP5bTA845m1hTnp0bjgFnw4efn+NHQ7WrXVwVmffwhY=
Then it goes back one line and uses that if it is a comment
# Example comment
Example file content
```
[Peer]
# Example
PublicKey = eP5bTA845m1hTnp0bjgFnw4efn+NHQ7WrXVwVmffwhY=
AllowedIPs = 192.0.2.3/32, 2001:db8::3cf5/128
```
'''
import argparse
import os
import re
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--cfg', default='/etc/systemd/network/wg0.netdev')
args = parser.parse_args()
pubkeyRegex = re.compile(r'^PublicKey ?= ?(.*)$', re.IGNORECASE)
peerRegex = re.compile(r'^peer: (.*)$')
keyLabels = {}
# Stores the previous line from the current iteration
prevLine = ''
with open(args.cfg) as f:
for line in f:
line = line.strip()
pubkeyMatch = re.search(pubkeyRegex, line)
if pubkeyMatch != None:
pubkey = pubkeyMatch.group(1)
# The regex can match empty string so we prevent that here
if len(pubkey) != 44:
continue
# If the previous line was a comment, then use it
if len(prevLine) > 3 and prevLine[0] == '#':
keyLabels[pubkey] = prevLine[2:]
else:
keyLabels[pubkey] = 'Unknown'
prevLine = line
# We have parsed the config file, now we will run wg and modify its output
wg = subprocess.run(['wg'], encoding='utf-8', stdout=subprocess.PIPE)
for line in wg.stdout.split('\n'):
peerMatch = re.search(peerRegex, line)
if peerMatch != None:
pubkey = peerMatch.group(1)
if pubkey in keyLabels.keys():
print('{} is {}'.format(line.strip(), keyLabels[pubkey]))
continue
print(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment