Files
gitlab-instance-0a899031_cn…/scripts/ssh-setup-ntfy-acl3.py
2026-06-08 06:05:31 -05:00

66 lines
2.5 KiB
Python

#!/usr/bin/env python3
from __future__ import annotations
import os
import re
import secrets
import sys
import paramiko
from load_dev_env import ssh_config
HOST, USER, SSH_PASSWORD = ssh_config()
def run(c: paramiko.SSHClient, cmd: str) -> str:
print(f"\n$ {cmd.replace(PASSWORD, '***')}")
_, o, e = c.exec_command(f"echo '{PASSWORD}' | sudo -S bash -lc \"{cmd}\"", timeout=120, get_pty=True)
combined = o.read().decode("utf-8", errors="replace") + e.read().decode("utf-8", errors="replace")
sys.stdout.buffer.write(combined.encode("utf-8", errors="replace"))
return combined
def main() -> None:
api_pass = secrets.token_urlsafe(16)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PASSWORD, timeout=30)
try:
run(c, "docker exec nomadro-ntfy ntfy user add --help 2>&1 | head -30")
run(c, f"docker exec nomadro-ntfy ntfy user add nomadcna-api --role=writer --passwd={api_pass} 2>&1")
run(c, "docker exec nomadro-ntfy ntfy access '*' 'nomadcna-*' read 2>&1")
run(c, "docker exec nomadro-ntfy ntfy access nomadcna-api 'nomadcna-*' write-only 2>&1")
run(c, "docker exec nomadro-ntfy ntfy user list 2>&1")
token_out = run(c, "docker exec nomadro-ntfy ntfy token add -l nomadcna-backend nomadcna-api 2>&1")
token = re.search(r"tk_[a-zA-Z0-9_-]+", token_out)
token_val = token.group(0) if token else ""
if not token_val:
token_out2 = run(c, "docker exec nomadro-ntfy ntfy token add -l nomadcna-backend nomadro 2>&1")
token2 = re.search(r"tk_[a-zA-Z0-9_-]+", token_out2)
token_val = token2.group(0) if token2 else ""
if token_val:
repo = "/home/ubuntu/gitlab-instance-0a899031_cnomadcna/.env.local"
run(
c,
f"touch {repo} && grep -q '^NTFY_AUTH_TOKEN=' {repo} && "
f"sed -i 's/^NTFY_AUTH_TOKEN=.*/NTFY_AUTH_TOKEN={token_val}/' {repo} || "
f"echo 'NTFY_AUTH_TOKEN={token_val}' >> {repo}",
)
run(
c,
f"curl -s -X POST https://ntfy.nomadro.cn/nomadcna-healthcheck "
f"-H 'Authorization: Bearer {token_val}' -H 'Title: NomadCNA' -d 'push ok'",
)
run(c, "systemctl restart cnomadcna-api.service")
run(c, "systemctl is-active cnomadcna-api.service")
print(f"\nNTFY_AUTH_TOKEN={token_val}")
finally:
c.close()
if __name__ == "__main__":
main()