wireguard-setup/scripts/rotate.py

54 lines
1.3 KiB
Python
Raw Normal View History

2021-09-21 11:52:17 +00:00
#!/usr/bin/env python3
import configparser
import subprocess
2021-11-03 07:51:41 +00:00
import requests
2021-09-21 11:52:17 +00:00
import re
import io
def offline():
2021-11-03 07:51:41 +00:00
try:
requests.head("https://1.1.1.1", timeout=1)
except Exception:
return True
else:
return False
2021-09-21 11:52:17 +00:00
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"])