add rotate

This commit is contained in:
Roy Olav Purser 2021-09-21 13:52:17 +02:00
parent 8dc1ac818a
commit d8c78d3965
Signed by: roypur
GPG Key ID: E14D26A036F21656

49
scripts/rotate.py Executable file
View File

@ -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"])