diff --git a/wg-p2p-client.py b/wg-p2p-client.py index 49ab6bd..eaa4cdc 100644 --- a/wg-p2p-client.py +++ b/wg-p2p-client.py @@ -1,11 +1,28 @@ +import hashlib from time import sleep import yaml import requests +from wgconfig import WireGuardConfig, wg_showconf, wg_syncconf with open("wg-p2p-client.conf") as f: cfg = yaml.safe_load(f) last_hash = "" +last_local_hash = "" url = f"{cfg['url']}/hash/{cfg['remote_wg']}" +urlpat2 = f"{cfg['url']}/peers/{cfg['remote_wg']}" while True: new_hash = requests.get(url).text - print(new_hash) + new_local_hash = hashlib.sha256(wg_showconf( + cfg["local_wg"]).encode()).hexdigest() + if last_hash != new_hash or last_local_hash != new_local_hash: + print(f"update hash to {new_hash}") + print(f"update local_hash to {new_local_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 = requests.get(url2).json() + p["Endpoint"] = res["Endpoint"] + wg_syncconf(cfg["local_wg"], str(local_cfg)) + last_hash = new_hash + last_local_hash = new_local_hash sleep(5) \ No newline at end of file diff --git a/wgconfig.py b/wgconfig.py index 725ac3c..481e4d8 100644 --- a/wgconfig.py +++ b/wgconfig.py @@ -72,4 +72,4 @@ def wg_showconf(ifname: str): def wg_syncconf(ifname: str, conf: str): - run(f"wg syncconf {ifname} /dev/stdin", shell=True, input=conf) + run(f"wg syncconf {ifname} /dev/stdin", shell=True, input=conf.encode())