Files
nginx/install.py
2025-12-03 12:02:28 +08:00

174 lines
5.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
from pathlib import Path
# ============================================================
# 手动指定要管理的站点配置文件(脚本同目录下)
# ============================================================
NGINX_SITES = [
"gogongxt.com",
"git.gogongxt.com",
"images.gogongxt.com",
"chat.gogongxt.com",
"nas.gogongxt.com",
"tools.gogongxt.com",
"code.gogongxt.com",
]
# ============================================================
# 常量配置
# ============================================================
NGINX_AVAILABLE = Path("/etc/nginx/sites-available")
NGINX_ENABLED = Path("/etc/nginx/sites-enabled")
LOCAL_DIR = Path(__file__).parent.resolve() # 当前脚本所在目录
# ============================================================
# 权限检查
# ============================================================
def require_root():
if os.geteuid() != 0:
print("⚠️ 需要root权限正在使用sudo重新执行...")
try:
os.execvp("sudo", ["sudo", sys.executable] + sys.argv)
except Exception as e:
print(f"❌ 无法自动提升权限: {e}")
sys.exit(1)
# ============================================================
# 工具函数
# ============================================================
def run(cmd, check=True):
print(f"🔹 执行命令: {' '.join(cmd)}")
result = subprocess.run(cmd, check=check)
return result.returncode == 0
def ensure_dirs():
for d in (NGINX_AVAILABLE, NGINX_ENABLED):
d.mkdir(parents=True, exist_ok=True)
# ============================================================
# 安装 / 卸载操作
# ============================================================
def install_nginx_configs():
ensure_dirs()
print(f"📦 开始安装 {len(NGINX_SITES)} 个 Nginx 配置文件...")
for name in NGINX_SITES:
src = LOCAL_DIR / name
dest_available = NGINX_AVAILABLE / name
dest_enabled = NGINX_ENABLED / name
if not src.exists():
print(f"⚠️ 跳过:未找到配置文件 {src}")
continue
print(f"🔹 安装配置: {src.name}")
# 删除已存在的目标文件/链接
if dest_available.exists() or dest_available.is_symlink():
print(f"🔸 删除旧的可用配置: {dest_available}")
dest_available.unlink(missing_ok=True)
# 创建 sites-available 的软链接
run(["sudo", "ln", "-s", str(src), str(dest_available)])
# 删除已存在的启用链接
if dest_enabled.exists() or dest_enabled.is_symlink():
print(f"🔸 删除旧的启用链接: {dest_enabled}")
dest_enabled.unlink(missing_ok=True)
# 创建 sites-enabled 的软链接
run(["sudo", "ln", "-s", str(dest_available), str(dest_enabled)])
print("🔍 检查 Nginx 配置语法...")
if run(["sudo", "nginx", "-t"], check=False):
print("✅ 配置检查通过,正在重启 Nginx...")
run(["sudo", "systemctl", "restart", "nginx"])
else:
print("❌ nginx 配置错误,请手动修复后重试。")
sys.exit(1)
print("✅ 所有配置已安装完成!")
def uninstall_nginx_configs():
ensure_dirs()
print(f"🗑️ 开始卸载 {len(NGINX_SITES)} 个 Nginx 配置文件...")
for name in NGINX_SITES:
dest_available = NGINX_AVAILABLE / name
dest_enabled = NGINX_ENABLED / name
print(f"🔹 卸载配置: {name}")
if dest_enabled.exists() or dest_enabled.is_symlink():
print(f"🗑️ 删除启用链接: {dest_enabled}")
dest_enabled.unlink(missing_ok=True)
if dest_available.exists() or dest_available.is_symlink():
print(f"🗑️ 删除可用配置链接: {dest_available}")
dest_available.unlink(missing_ok=True)
print("🔍 检查 Nginx 配置语法...")
if run(["sudo", "nginx", "-t"], check=False):
print("✅ 配置检查通过,正在重启 Nginx...")
run(["sudo", "systemctl", "restart", "nginx"])
else:
print("⚠️ Nginx 配置检测未通过,请检查。")
print("✅ 卸载完成。")
# ============================================================
# 证书生成逻辑
# ============================================================
def generate_cert(domain=None):
if domain:
print(f"🔹 为域名 {domain} 生成或更新证书standalone 模式)...")
cmd = ["sudo", "certbot", "certonly", "--standalone", "-d", domain]
else:
print("🔹 为所有 Nginx 域名生成证书...")
cmd = ["sudo", "certbot", "certonly", "--nginx"]
run(cmd, check=False)
print("✅ 证书任务完成。")
# ============================================================
# CLI 主入口
# ============================================================
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Manage Nginx site configs and certificates"
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--install", action="store_true", help="Install Nginx configs")
group.add_argument(
"--uninstall", action="store_true", help="Uninstall Nginx configs"
)
group.add_argument(
"--cert",
nargs="?",
const=True,
help="Generate SSL certs (optionally specify domain)",
)
args = parser.parse_args()
require_root()
if args.install:
install_nginx_configs()
elif args.uninstall:
uninstall_nginx_configs()
elif args.cert:
if args.cert is True:
generate_cert(None)
else:
generate_cert(args.cert)