nuno 已修改 1 month ago. 還原成這個修訂版本
1 file changed, 61 insertions
gistfile1.txt(檔案已創建)
| @@ -0,0 +1,61 @@ | |||
| 1 | + | global _hs_last_logged | |
| 2 | + | ||
| 3 | + | _hs_last_logged = load_hs_cache() | |
| 4 | + | ||
| 5 | + | pubkey_to_name = build_pubkey_to_name() | |
| 6 | + | log.info(f"Handshake poller started — {len(pubkey_to_name)} peers, " | |
| 7 | + | f"session threshold {WG_HANDSHAKE_CHECK_SEC}s") | |
| 8 | + | ||
| 9 | + | while True: | |
| 10 | + | try: | |
| 11 | + | result = subprocess.run( | |
| 12 | + | ["wg", "show", WG_WG_INTERFACE, "latest-handshakes"], | |
| 13 | + | capture_output=True, text=True | |
| 14 | + | ) | |
| 15 | + | for line in result.stdout.strip().splitlines(): | |
| 16 | + | parts = line.split() | |
| 17 | + | if len(parts) != 2: | |
| 18 | + | continue | |
| 19 | + | pubkey, ts_str = parts | |
| 20 | + | try: | |
| 21 | + | ts = int(ts_str) | |
| 22 | + | except ValueError: | |
| 23 | + | continue | |
| 24 | + | if ts == 0: | |
| 25 | + | continue | |
| 26 | + | ||
| 27 | + | client = pubkey_to_name.get(pubkey) | |
| 28 | + | if not client: | |
| 29 | + | continue | |
| 30 | + | ||
| 31 | + | last = _hs_last_logged.get(pubkey, 0) | |
| 32 | + | gap = ts - last | |
| 33 | + | ||
| 34 | + | if gap < WG_HANDSHAKE_CHECK_SEC: | |
| 35 | + | continue # keepalive, skip | |
| 36 | + | ||
| 37 | + | # New session — log it | |
| 38 | + | _hs_last_logged[pubkey] = ts | |
| 39 | + | ||
| 40 | + | # Get endpoint | |
| 41 | + | endpoint = get_endpoint(pubkey) or '' | |
| 42 | + | ||
| 43 | + | entry = { | |
| 44 | + | "timestamp": datetime.fromtimestamp(ts, tz=timezone.utc).isoformat(), | |
| 45 | + | "ip": "", | |
| 46 | + | "client": client, | |
| 47 | + | "event": "handshake", | |
| 48 | + | "endpoint": endpoint, | |
| 49 | + | } | |
| 50 | + | try: | |
| 51 | + | with EVENTS_LOG.open("a") as f: | |
| 52 | + | f.write(json.dumps(entry) + "\n") | |
| 53 | + | log.info(f"New session: {client} from {endpoint}") | |
| 54 | + | except Exception as e: | |
| 55 | + | log.error(f"Failed to write handshake event: {e}") | |
| 56 | + | ||
| 57 | + | log.debug(f"Gap for {client}: {gap}s (threshold: {WG_HANDSHAKE_CHECK_SEC}s)") | |
| 58 | + | save_hs_cache(_hs_last_logged) | |
| 59 | + | ||
| 60 | + | except Exception as e: | |
| 61 | + | log.error(f"Handshake poll error: {e}") | |
上一頁
下一頁