Skip to content

Instantly share code, notes, and snippets.

@nzbr
Created July 23, 2019 19:29
Show Gist options
  • Save nzbr/dbf0acfa3e7854105be726a0d15e31cc to your computer and use it in GitHub Desktop.
Save nzbr/dbf0acfa3e7854105be726a0d15e31cc to your computer and use it in GitHub Desktop.
Creates hosts-file entries from a wireguard config
#!/usr/bin/python3
import sys
import os
if len(sys.argv) != 2:
print("Usage:\twghosts.py <interface>")
sys.exit(1)
interface = sys.argv[1]
conffile = "/etc/wireguard/%s.conf" % interface
if not os.path.isfile(conffile):
print('No configuration for interface "%s" found' % interface)
sys.exit(1)
with open(conffile, "r") as f:
config = f.read()
blocks = config.split("[Peer]\n")
peers = []
for block in blocks:
if block.startswith("["): #Not a [Peer] block
continue
lines = block.split("\n")
peer = [None, None]
for line in lines:
if line.startswith("# Name"):
peer[1] = line.split("=")[1].strip()
elif line.startswith("AllowedIPs"):
ips = line.split("=")[1].strip()
for ip in ips.split(" "):
addr = ip.split("/")[0] #Remove subnet info
parts = addr.split(".")
if len(parts) == 4 and not parts[3] == "0":
peer[0] = addr
peers += [peer]
for peer in peers:
if not peer[0] is None and not peer[1] is None:
print("%s\t%s" % tuple(peer))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment