fdm/deploy/preview-access.py

31 lines
975 B
Python

import getpass
from pathlib import Path
import paramiko
client = paramiko.SSHClient()
client.load_host_keys(str(Path.home() / ".ssh" / "known_hosts"))
client.connect("47.108.78.12", username="root", password=getpass.getpass("SSH password: "), timeout=20)
def run(command):
_, out, err = client.exec_command(command, timeout=30)
print(out.read().decode() + err.read().decode(), flush=True)
if out.channel.recv_exit_status():
raise RuntimeError("配置检查失败")
target = "/etc/nginx/conf.d/fdm-ip-preview.conf"
try:
run(f"test ! -e {target}")
with client.open_sftp() as sftp:
sftp.put(str(Path(__file__).with_name("nginx-ip-preview.conf")), target)
try:
run("nginx -t && systemctl reload nginx")
run("curl -fsS -H 'Host: 47.108.78.12' http://127.0.0.1/healthz")
except Exception:
run(f"mv {target} {target}.disabled && nginx -t && systemctl reload nginx")
raise
finally:
client.close()