import hashlib from time import sleep import yaml import requests from pathlib import Path from wgconfig import WireGuardConfig, wg_showconf, wg_syncconf def local_hash(ifname: str): return hashlib.sha256(wg_showconf(ifname).encode()).hexdigest() cfg = yaml.safe_load(Path(__file__).with_suffix(".conf").read_text()) last_hash = "" last_local_hash = "" url = f"{cfg['url']}/hash/{cfg['remote_wg']}" urlpat2 = f"{cfg['url']}/peers/{cfg['remote_wg']}" with requests.Session() as sess: sess.verify = "ca.crt" sess.cert = ("client1.crt", "client1.key") while True: try: new_hash = sess.get(url).text new_local_hash = local_hash(cfg["local_wg"]) if last_hash != new_hash or last_local_hash != new_local_hash: print(f"update hash to {new_hash}") local_cfg = WireGuardConfig.get_from_interface(cfg["local_wg"]) for peer in cfg["peers"]: if p := local_cfg.get_peer(peer): url2 = f"{urlpat2}/{peer}" res = sess.get(url2).json() p["Endpoint"] = res["Endpoint"] wg_syncconf(cfg["local_wg"], str(local_cfg)) new_local_hash = local_hash(cfg["local_wg"]) print(f"update local_hash to {new_local_hash}") last_hash = new_hash last_local_hash = new_local_hash except Exception as ex: print(ex) sleep(5)