97 lines
3.4 KiB
Python
97 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Синхронизация сертификатов с VPS в домашний nginx.
|
|
|
|
certbot на VPS обновляет /etc/letsencrypt/live/<domain>/, но домашний
|
|
nginx использует копии в /etc/nginx/certs/<domain>/. Без синхронизации
|
|
копии устаревают и домены начинают отдавать просроченный сертификат.
|
|
"""
|
|
import glob
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
|
|
# Публичный SSH к VPS нестабилен (banner exchange). Основной путь — туннель,
|
|
# публичный адрес — резерв.
|
|
VPS_CANDIDATES = [
|
|
os.environ.get("VPS_SSH", "root@193.233.210.184"),
|
|
"root@10.88.0.1",
|
|
]
|
|
VPS = VPS_CANDIDATES[0]
|
|
HOME_CERTS = "/etc/nginx/certs"
|
|
LOG = "/var/log/cert-sync.log"
|
|
|
|
|
|
def sh(cmd, timeout=600):
|
|
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
|
|
return r.returncode, (r.stdout or "") + (r.stderr or "")
|
|
|
|
|
|
def log(msg):
|
|
line = f"{time.strftime('%Y-%m-%dT%H:%M:%S')} {msg}"
|
|
print(line, flush=True)
|
|
with open(LOG, "a", encoding="utf-8") as f:
|
|
f.write(line + "\n")
|
|
|
|
|
|
def fetch(remote_path, local_path):
|
|
# Пробуем все адреса VPS (туннель, затем публичный), по 2 попытки каждый
|
|
for host in VPS_CANDIDATES:
|
|
for attempt in range(2):
|
|
rc, out = sh(
|
|
f"scp -q -o BatchMode=yes -o ConnectTimeout=15 "
|
|
f"-o ServerAliveInterval=5 {host}:{remote_path} {local_path}.new",
|
|
timeout=180)
|
|
if rc == 0:
|
|
if host != VPS:
|
|
log(f"VPS доступен через {host}")
|
|
return True
|
|
time.sleep(4)
|
|
return False
|
|
|
|
|
|
def same(a, b):
|
|
try:
|
|
return open(a, "rb").read() == open(b, "rb").read()
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def main():
|
|
domains = [os.path.basename(d) for d in glob.glob(f"{HOME_CERTS}/*")
|
|
if os.path.isdir(d)]
|
|
changed, failed = [], []
|
|
for d in domains:
|
|
dst_dir = os.path.join(HOME_CERTS, d)
|
|
new_full = os.path.join(dst_dir, "fullchain.pem.new")
|
|
new_key = os.path.join(dst_dir, "privkey.pem.new")
|
|
if not fetch(f"/etc/letsencrypt/live/{d}/fullchain.pem", os.path.join(dst_dir, "fullchain.pem")):
|
|
failed.append(d)
|
|
continue
|
|
if not fetch(f"/etc/letsencrypt/live/{d}/privkey.pem", os.path.join(dst_dir, "privkey.pem")):
|
|
failed.append(d)
|
|
continue
|
|
full = os.path.join(dst_dir, "fullchain.pem")
|
|
key = os.path.join(dst_dir, "privkey.pem")
|
|
if same(full, new_full) and same(key, new_key):
|
|
os.remove(new_full)
|
|
os.remove(new_key)
|
|
continue
|
|
os.replace(new_full, full)
|
|
os.replace(new_key, key)
|
|
os.chmod(full, 0o644)
|
|
os.chmod(key, 0o600)
|
|
changed.append(d)
|
|
|
|
if changed:
|
|
rc, out = sh("nginx -t 2>&1 | tail -1 && systemctl reload nginx 2>&1")
|
|
log(f"обновлено сертификатов: {len(changed)} ({', '.join(changed[:5])}) | nginx: {out.strip()[:80]}")
|
|
else:
|
|
log(f"изменений нет (проверено доменов: {len(domains)})")
|
|
if failed:
|
|
log(f"не удалось скачать: {', '.join(failed[:8])}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|