From d8c78d39654c9fb196c8adcb300c44575dac72c2 Mon Sep 17 00:00:00 2001 From: Roy Olav Purser Date: Tue, 21 Sep 2021 13:52:17 +0200 Subject: [PATCH] add rotate --- scripts/rotate.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100755 scripts/rotate.py diff --git a/scripts/rotate.py b/scripts/rotate.py new file mode 100755 index 0000000..be01781 --- /dev/null +++ b/scripts/rotate.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +import configparser +import subprocess +import re +import io + +def offline(): + expr = re.compile("ips:[^()]+handshake") + proc = subprocess.run(["wg", "show", "vpn"], capture_output=True, encoding="utf-8") + return len(expr.findall(proc.stdout)) == 0 + +def rotate_conf(): + iface = None + peers = [] + try: + with open("/snacks/wireguard/wg.conf", "r") as f: + pattern = re.compile("\[[^\[\]]+\][^\[\]]+") + sections = [] + for section in re.findall(pattern, f.read()): + sections.append(section.strip()) + except Exception as e: + print(e) + else: + for section in sections: + config = configparser.ConfigParser() + config.read_string(section) + if "Peer" in config.sections(): + peers.append(config) + else: + iface = config + buf = io.StringIO() + try: + iface.write(buf) + except Exception as e: + print(e) + else: + first = peers.pop(0) + peers.append(first) + for peer in peers: + peer.write(buf) + try: + with open("/snacks/wireguard/wg.conf", "w") as f: + f.write(buf.getvalue()) + except Exception as e: + print(e) + +if offline(): + rotate_conf() + subprocess.run(["systemctl", "restart", "vpnclient-wg"])