scripts: wake-watch — wol-gate 깨우기 시도 수집·아는 주소 제외 주간 리포트
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
42b31e24e2
commit
28aaf80107
1 file changed
+137
Executable
+137
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""깨우기 시도 주소 수집 + 주간 분석 (wol-gate 로그).
|
||||
|
||||
wol-gate는 서버가 잠든 상태에서 들어온 요청만 maybeWake()로 넘기므로, 그 로그 = "깨우기 시도".
|
||||
TrueNAS에서 `docker logs`를 읽어 ~/wake-watch/events.jsonl에 누적한다(컨테이너 재생성 시 로그가 사라지므로).
|
||||
아는 주소(~/wake-watch/known.json)를 뺀 나머지를 리포트한다.
|
||||
|
||||
wake-watch.py collect 로그 수집·누적만
|
||||
wake-watch.py report 수집 후 주간(기본 7일) 리포트를 ~/wake-watch/report-YYYY-MM-DD.txt에 쓰고 출력
|
||||
wake-watch.py known add <ip|cidr> [메모] 아는 주소로 등록
|
||||
"""
|
||||
import ipaddress, json, os, re, subprocess, sys, datetime, collections, urllib.request
|
||||
|
||||
HOME = os.path.expanduser("~/wake-watch")
|
||||
EVENTS = f"{HOME}/events.jsonl"
|
||||
KNOWN = f"{HOME}/known.json"
|
||||
TRUENAS = "truenas_admin@192.168.0.240"
|
||||
CONTAINER = "ix-wol-gate-wol-gate-1"
|
||||
LINE = re.compile(r'^(\S+Z) \[wol-gate\] (waking|wake suppressed \(cooldown\)|wake blocked \(non-KR\)|wake denied \(watchlist\)) - triggered by (\S+) "(\w+) ([^"]*)" UA="(.*)"$')
|
||||
KIND = {"waking": "wake", "wake suppressed (cooldown)": "cooldown", "wake blocked (non-KR)": "non-kr", "wake denied (watchlist)": "denied"}
|
||||
|
||||
def load_known():
|
||||
if not os.path.exists(KNOWN):
|
||||
return {"entries": []}
|
||||
return json.load(open(KNOWN))
|
||||
|
||||
def is_known(ip, known):
|
||||
try:
|
||||
a = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
return False
|
||||
for e in known["entries"]:
|
||||
try:
|
||||
if a in ipaddress.ip_network(e["net"], strict=False):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
return False
|
||||
|
||||
def collect():
|
||||
os.makedirs(HOME, exist_ok=True)
|
||||
seen = set()
|
||||
last = ""
|
||||
if os.path.exists(EVENTS):
|
||||
for l in open(EVENTS):
|
||||
try:
|
||||
d = json.loads(l)
|
||||
except ValueError:
|
||||
continue
|
||||
seen.add((d["ts"], d["ip"], d["kind"], d["target"]))
|
||||
last = max(last, d["ts"])
|
||||
cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", TRUENAS, f"sudo docker logs -t {CONTAINER} 2>&1"]
|
||||
out = subprocess.run(cmd, capture_output=True, text=True, timeout=60).stdout
|
||||
new = 0
|
||||
with open(EVENTS, "a") as f:
|
||||
for line in out.splitlines():
|
||||
m = LINE.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
ts, kind, ip, method, target, ua = m.groups()
|
||||
key = (ts, ip, KIND[kind], target)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
f.write(json.dumps({"ts": ts, "ip": ip, "kind": KIND[kind], "method": method, "target": target, "ua": ua[:120]}, ensure_ascii=False) + "\n")
|
||||
new += 1
|
||||
return new
|
||||
|
||||
def geo(ip):
|
||||
try:
|
||||
r = urllib.request.urlopen(f"http://ip-api.com/json/{ip}?lang=ko&fields=status,regionName,city,isp,mobile,hosting,proxy", timeout=6)
|
||||
return json.load(r)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def report(days=7):
|
||||
known = load_known()
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
since = now - datetime.timedelta(days=days)
|
||||
rows = []
|
||||
for l in open(EVENTS):
|
||||
d = json.loads(l)
|
||||
t = datetime.datetime.fromisoformat(d["ts"].replace("Z", "+00:00")[:26] + "+00:00") if False else datetime.datetime.strptime(d["ts"][:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=datetime.timezone.utc)
|
||||
d["_t"] = t
|
||||
rows.append(d)
|
||||
week = [d for d in rows if d["_t"] >= since]
|
||||
unknown = [d for d in week if not is_known(d["ip"], known)]
|
||||
per = collections.defaultdict(list)
|
||||
for d in unknown:
|
||||
per[d["ip"]].append(d)
|
||||
kst = lambda t: (t + datetime.timedelta(hours=9)).strftime("%m-%d %H:%M")
|
||||
out = [f"== 깨우기 시도 주간 리포트 ({kst(since)} ~ {kst(now)} KST)",
|
||||
f"시도 총 {len(week)}건 · 아는 주소 {len(week) - len(unknown)}건 · 모르는 주소 {len(unknown)}건 ({len(per)}개 IP)", ""]
|
||||
if not per:
|
||||
out.append("모르는 주소 없음.")
|
||||
nets = collections.Counter()
|
||||
for ip, evs in sorted(per.items(), key=lambda kv: -len(kv[1])):
|
||||
g = geo(ip)
|
||||
tags = []
|
||||
if g.get("hosting"): tags.append("IDC")
|
||||
if g.get("mobile"): tags.append("모바일")
|
||||
if g.get("proxy"): tags.append("프록시")
|
||||
kinds = collections.Counter(e["kind"] for e in evs)
|
||||
try:
|
||||
nets[str(ipaddress.ip_network(ip + "/24", strict=False))] += len(evs)
|
||||
except ValueError:
|
||||
pass
|
||||
out.append(f"{ip:18} {len(evs):3}건 {kst(min(e['_t'] for e in evs))}~{kst(max(e['_t'] for e in evs))} "
|
||||
f"{g.get('isp','?')} {g.get('regionName','')} {g.get('city','')} {','.join(tags)} [{', '.join(f'{k}:{v}' for k, v in kinds.items())}]")
|
||||
out.append(f"{'':18} {evs[0]['method']} {evs[0]['target'][:60]} UA={evs[0]['ua'][:50]}")
|
||||
multi = [(n, c) for n, c in nets.items() if sum(1 for ip in per if ip.startswith(n.rsplit('.', 1)[0] + '.')) >= 2]
|
||||
if multi:
|
||||
out += ["", "== 같은 /24에서 여러 IP가 시도 (차단 후보 → wol-gate/deny-cidrs.json)"]
|
||||
out += [f"{n} {c}건" for n, c in multi]
|
||||
out += ["", "아는 주소로 등록: scripts/wake-watch.py known add <ip|cidr> [메모]"]
|
||||
text = "\n".join(out)
|
||||
path = f"{HOME}/report-{datetime.date.today():%Y-%m-%d}.txt"
|
||||
open(path, "w").write(text + "\n")
|
||||
print(text)
|
||||
print(f"\n(저장: {path})")
|
||||
|
||||
def main():
|
||||
a = sys.argv[1:]
|
||||
if a[:2] == ["known", "add"] and len(a) >= 3:
|
||||
k = load_known()
|
||||
k["entries"].append({"net": a[2], "note": " ".join(a[3:]), "added": datetime.date.today().isoformat()})
|
||||
os.makedirs(HOME, exist_ok=True)
|
||||
json.dump(k, open(KNOWN, "w"), ensure_ascii=False, indent=1)
|
||||
print("등록:", a[2]); return
|
||||
if a[:1] == ["collect"]:
|
||||
print("신규", collect(), "건"); return
|
||||
if a[:1] == ["report"]:
|
||||
n = collect(); print(f"(신규 {n}건 수집)\n"); report(int(a[1]) if len(a) > 1 else 7); return
|
||||
print(__doc__)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user