Skip to content

Instantly share code, notes, and snippets.

@kalebo
Created September 2, 2020 20:58
Show Gist options
  • Save kalebo/6e0046f3d0fd4a22aefeb5923b2ca20d to your computer and use it in GitHub Desktop.
Save kalebo/6e0046f3d0fd4a22aefeb5923b2ca20d to your computer and use it in GitHub Desktop.
A simple script that will map wireguard peers to usernames. Assmues that script lives in a directory where subdirectories named after the user contain the users publickey file
#!/usr/bin/env python3
from subprocess import run
from pathlib import Path as path
from functools import lru_cache
def wg_show(interface, field):
res = run(["wg", "show", interface, field], check=True, text=True, capture_output=True)
return map(lambda l: l.split(maxsplit=1), res.stdout.strip().split('\n'))
def get_active_peers(interface):
pairs = wg_show(interface, "latest-handshakes")
return [peer for peer, handshake in pairs if handshake != "0"]
@lru_cache
def allowed_ips(interface):
pairs = wg_show(interface, "allowed-ips")
return {peer: ip for peer, ip in pairs}
@lru_cache
def peer_map():
pubkeys = path(__file__).parent.glob("**/publickey")
return {key.read_text().strip(): key.parent.name for key in pubkeys}
def print_peer_info(peer, interface):
try:
print(f"Peer: {peer}")
print("\tclient:\t", peer_map()[peer])
print("\tip:\t", allowed_ips(interface)[peer])
except:
pass
if __name__ == "__main__":
for peer in get_active_peers("coreform"):
print_peer_info(peer, "coreform")
#print(peer_map.cache_info())
#print(allowed_ips.cache_info())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment