#!/usr/bin/env python3 """Interactive front end for the existing Debian installers (stdlib only).""" import argparse import getpass import json import os import platform import posixpath import re import shutil import stat import subprocess import sys import tempfile import time import urllib.parse import urllib.error import urllib.request from pathlib import Path SOURCE = Path(__file__).resolve().parent.parent ENVIRONMENT = Path('/etc/sea-vhost/sea-vhost.env') CONFIG = Path('/var/lib/sea-vhost/config.json') NODE_CONFIG = Path('/etc/sea-vhost-node/config.json') PANEL_CREDENTIALS = Path('/var/lib/sea-vhost-panel/credentials.json') PANEL_REGISTRY = Path('/var/lib/sea-vhost-panel/resources.json') ROLES = {'combined': '主控兼本机托管', 'controller': '独立主控', 'node': '被控节点'} class InstallError(Exception): pass def run(args, **kwargs): return subprocess.run([str(a) for a in args], check=True, **kwargs) class Console: def ask(self, label, default=''): value = input(f'{label}' + (f' [{default}]' if default else '') + ':').strip() return value or default def confirm(self, label, default=True): while True: value = self.ask(label + (' [Y/n]' if default else ' [y/N]')).lower() if not value: return default if value in ('y', 'yes', '是'): return True if value in ('n', 'no', '否'): return False print('请输入 y 或 n。') def secret(self, label): return getpass.getpass(label + ':').strip() def read_json(file, protect=False): # No following links, unbounded reads or accepting a writable borrowed key file. fd = os.open(file, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024: raise InstallError('配置必须是小于 1 MiB 的普通文件。') if protect: if info.st_uid != 0: raise InstallError('配对文件须由 root 所有,请先复制到 /root。') os.fchmod(fd, 0o600) with os.fdopen(fd, 'r', encoding='utf-8') as stream: fd = -1 value = json.load(stream) if not isinstance(value, dict): raise InstallError('配置内容必须是 JSON 对象。') return value finally: if fd != -1: os.close(fd) def private_json(file, value): fd = os.open(file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, 'w', encoding='utf-8') as stream: json.dump(value, stream, ensure_ascii=False) stream.write('\n') def environment(): if not ENVIRONMENT.exists(): return {} if ENVIRONMENT.is_symlink() or not ENVIRONMENT.is_file(): raise InstallError('现有环境文件不是安全的普通文件。') info = ENVIRONMENT.stat() if info.st_uid != 0 or info.st_mode & 0o022: raise InstallError('现有环境文件须由 root 所有且不可被组或其他用户修改。') # Deliberately do not source shell text from this file. return dict(line.split('=', 1) for line in ENVIRONMENT.read_text().splitlines() if line and not line.startswith('#') and '=' in line) def check_role(role, values): if role == 'node': if CONFIG.exists() or values and values.get('SEA_NODE_STATELESS') != 'true': raise InstallError('检测到主控或单机配置,不能原地转换为被控。') if PANEL_REGISTRY.exists(): raise InstallError('检测到本机资源登记表,请先完成现有主机迁移。') elif NODE_CONFIG.exists() or values.get('SEA_NODE_STATELESS') == 'true': raise InstallError('检测到被控配置,不能原地转换为主控。') elif values and (values.get('SEA_CONTROLLER_ONLY') == 'true') != (role == 'controller'): raise InstallError('已有安装角色不同;请在另一台服务器安装该角色。') elif role == 'controller' and PANEL_CREDENTIALS.exists(): raise InstallError('检测到本机宝塔代理凭据,不能直接转换为独立主控。') def check_build(role): binaries = ['sea-vhost-node', 'sea-vhost-agent', 'sea-vhost-panel-broker'] if role == 'node' else ['sea-vhost-api'] if role == 'combined': binaries += ['sea-vhost-agent', 'sea-vhost-panel-broker'] files = [SOURCE / 'build/bin' / name for name in binaries] if role != 'node': files.append(SOURCE / 'build/web/index.html') for file in files: if file.is_symlink() or not file.is_file(): raise InstallError('安装包不完整,请解压完整的 sea-vhost-linux-amd64.tar.gz 后再运行。') def panel_url(value): try: parsed = urllib.parse.urlsplit(value) port = parsed.port except ValueError: raise InstallError('宝塔地址或端口无效。') from None if (parsed.scheme not in ('http', 'https') or parsed.hostname not in ('127.0.0.1', 'localhost', '::1') or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/') or port is not None and not 1 <= port <= 65535): raise InstallError('宝塔地址只能是本机回环 HTTP/HTTPS 地址,不包含安全入口路径。') return value.rstrip('/') def detect_panel_url(): data = Path('/www/server/panel/data') try: port = int((data / 'port.pl').read_text().strip()) if not 1 <= port <= 65535: raise ValueError() except (OSError, ValueError): port = 8888 return ('https' if (data / 'ssl.pl').exists() else 'http') + f'://127.0.0.1:{port}' def credentials(ui): saved = read_json(PANEL_CREDENTIALS) if PANEL_CREDENTIALS.exists() else {} if saved and ui.confirm('复用本机已保存的宝塔凭据'): panel_url(saved.get('url', '')) if saved.get('version') != 1 or len(saved.get('api_key', '')) < 16: raise InstallError('已有宝塔凭据不完整,请重新填写。') return saved while True: try: url = panel_url(ui.ask('本机宝塔 API 地址', detect_panel_url())) break except InstallError as error: print(error) while True: key = ui.secret('宝塔 API 密钥(输入隐藏)') if len(key) >= 16 and not any(c.isspace() for c in key): break print('密钥格式无效,请重新输入。') insecure = url.startswith('https:') and ui.confirm('本机宝塔使用自签名证书,跳过其证书校验') return {'version': 1, 'url': url, 'api_key': key, 'tls_insecure': insecure} def validate_pair(config): identity = config.get('identity', {}) root = config.get('tenantRoot', '') if (not isinstance(identity, dict) or type(identity.get('nodeId')) is not int or identity['nodeId'] < 2 or not re.fullmatch(r'/www/wwwroot/[A-Za-z0-9_/-]+', root) or posixpath.normpath(root) != root or '..' in root.split('/') or config.get('brokerSocket') != '/run/sea-vhost-panel/broker.sock' or config.get('agentSocket') != '/run/sea-vhost/agent.sock'): raise InstallError('配对文件的节点、目录或 Socket 配置无效。') if not re.fullmatch(r'(?:\[[0-9a-fA-F:]+\]|[0-9.]*):([0-9]{1,5})', config.get('address', '')): raise InstallError('配对文件的监听地址无效。') port = int(config['address'].rsplit(':', 1)[1]) if not 1024 <= port <= 65535: raise InstallError('被控监听端口须为 1024–65535。') if not all(isinstance(identity.get(k), str) and identity[k] for k in ('caPem', 'certificate', 'privateKey', 'clientSpki')): raise InstallError('配对文件缺少身份材料。') return identity['nodeId'], root def wait_services(units, attempts=20): consecutive = 0 for _ in range(attempts): if all(subprocess.run(['systemctl', 'is-active', '--quiet', unit], check=False).returncode == 0 for unit in units): consecutive += 1 if consecutive >= 2: return else: consecutive = 0 time.sleep(1) raise InstallError('服务未全部就绪。检查命令:journalctl -u ' + ' -u '.join(units) + ' -n 60 --no-pager') class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): raise InstallError('本机健康检查意外返回重定向,拒绝继续。') def wait_api(values, timeout=660): address = values.get('SEA_ADDR', '127.0.0.1:8080') if not re.fullmatch(r'127\.0\.0\.1:[0-9]{1,5}', address) or not 1 <= int(address.split(':')[1]) <= 65535: raise InstallError('无法自动核验现有 API 地址,请使用 127.0.0.1 的监听地址。') opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) deadline = time.monotonic() + timeout print('正在等待 API 完成数据库迁移与主机身份核验……') while time.monotonic() < deadline: try: with opener.open('http://' + address + '/healthz', timeout=3) as response: if response.status == 200 and json.loads(response.read(4096)).get('status') in ('ok', 'setup_required'): return except (OSError, urllib.error.URLError, ValueError): pass time.sleep(1) raise InstallError('API 健康检查未通过,不能报告安装成功。请执行 journalctl -u sea-vhost-api -n 60 --no-pager;修复后重跑向导。') def install_node(ui): if not Path('/www/server/panel').is_dir() or not Path('/www/server/nginx/sbin/nginx').is_file(): raise InstallError('被控需要本机宝塔和 Nginx。') if not Path('/www/server/pure-ftpd/bin/pure-pw').is_file(): raise InstallError('请先在宝塔安装免费 Pure-FTPd,再运行被控向导。') candidates = sorted(Path('/root').glob('sea-node-*.json')) default = str(NODE_CONFIG) if NODE_CONFIG.exists() else str(candidates[0]) if len(candidates) == 1 else '' pairing = Path(ui.ask('主控下载的配对文件路径', default)).expanduser() # An installed config is intentionally group-readable by the non-root node. # Do not chmod it to 0600 while the user is still answering/cancelling prompts. installed_pair = NODE_CONFIG.exists() and pairing.samefile(NODE_CONFIG) config = read_json(pairing, protect=not installed_pair) node, root = validate_pair(config) if NODE_CONFIG.exists(): old = read_json(NODE_CONFIG) if old.get('identity', {}).get('nodeId') != node or old.get('tenantRoot') != root: raise InstallError('配对文件与现有节点编号或根目录不同,不能直接覆盖。') creds = credentials(ui) print(f'\n安装角色:被控 #{node}\n主机目录:{root}\n监听地址:{config["address"]}\n宝塔地址:{creds["url"]}') if not ui.confirm('开始安装并启动被控'): return False with tempfile.TemporaryDirectory(prefix='sea-vhost-install-', dir='/run') as directory: pair_file, panel_file = Path(directory) / 'pair.json', Path(directory) / 'panel.json' private_json(pair_file, config) private_json(panel_file, creds) run(['bash', SOURCE / 'deploy/install-node.sh', pair_file, panel_file]) units = ['sea-vhost-agent', 'sea-vhost-panel-broker', 'sea-vhost-node'] wait_services(units) print('\n被控安装完成,服务已启动。回到主控「节点管理」,点击「启用」即可自动探测并连接。') print('被控不保存平台数据库;无需额外填写主控数据库或管理员信息。') return True def valid_domain(value): return len(value) <= 253 and '.' in value and all( re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', label) for label in value.split('.')) def certificate_for(domain): for base in (Path('/www/server/panel/vhost/cert'), Path('/www/server/panel/vhost/ssl'), Path('/etc/letsencrypt/live')): if not base.is_dir(): continue ordered = [base / domain] + sorted(p for p in base.iterdir() if p.name != domain) for directory in ordered: cert, key = directory / 'fullchain.pem', directory / 'privkey.pem' if not cert.is_file() or not key.is_file(): continue if certificate_covers(cert, domain): return cert, key return None def certificate_covers(cert, domain): return all(subprocess.run(['openssl', 'x509', '-in', str(cert)] + args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False).returncode == 0 for args in (['-checkhost', domain, '-noout'], ['-checkend', '0', '-noout'])) def nginx_plan(ui, values): if not ui.confirm('自动配置管理站点 HTTPS 与反向代理(复用已有证书)'): return None nginx = Path('/www/server/nginx/sbin/nginx') if nginx.is_file(): vhosts = Path('/www/server/panel/vhost/nginx') reload_command = [str(nginx), '-s', 'reload'] else: binary = shutil.which('nginx') if not binary: print('本机未检测到 Nginx,本次仅安装主控程序。配置好管理站点后可再次运行向导。') return None nginx, vhosts, reload_command = Path(binary), Path('/etc/nginx/conf.d'), ['systemctl', 'reload', 'nginx'] while True: domain = ui.ask('管理域名(不含协议和路径)', 'host.ser888.cn').lower() if valid_domain(domain): break print('请输入有效的域名。') addr = values.get('SEA_ADDR', '127.0.0.1:8080') if not re.fullmatch(r'127\.0\.0\.1:[0-9]{1,5}', addr) or not 1 <= int(addr.split(':')[1]) <= 65535: raise InstallError('现有 API 监听地址不是受支持的本机地址,保留现有 Nginx 配置后重试。') found = certificate_for(domain) if not found: print('未检测到覆盖该管理域名的有效证书。可输入证书路径,或留空后自行配置站点。') cert = ui.ask('完整证书链路径(留空跳过站点配置)') if not cert: return None key = ui.ask('证书私钥路径') found = (Path(cert), Path(key)) for file in found: if not file.is_absolute() or not file.is_file() or re.search(r'[\s;{}"\'\\$]', str(file)): raise InstallError('证书路径须是可读绝对路径且不包含 Nginx 特殊字符。') if not certificate_covers(found[0], domain): raise InstallError('证书已过期或未覆盖管理域名,请更换后重试。') target = vhosts / 'sea-vhost-console.conf' if target.is_symlink() or target.exists() and not target.is_file(): raise InstallError('管理站点配置路径不是安全的普通文件。') for file in vhosts.glob('*.conf'): if file == target: continue text = file.read_text(errors='replace') if any(domain in names.split() for names in re.findall(r'^\s*server_name\s+([^;]+);', text, re.M)): if 'root /opt/sea-vhost/web;' in text or re.search(r'root\s+/opt/sea-vhost/web\s*;', text): print(f'检测到已有 Sea vHost 管理站点,保留 {file}。') run([nginx, '-t']) return {'domain': domain, 'existing': True} raise InstallError(f'域名已由其他 Nginx 站点使用:{file}。不会覆盖;可重新运行并跳过自动配置。') text = (SOURCE / 'deploy/nginx/sea-vhost.conf').read_text() text = text.replace('host.ser888.cn', domain) text = text.replace(f'/www/server/panel/vhost/cert/{domain}/fullchain.pem', str(found[0])) text = text.replace(f'/www/server/panel/vhost/cert/{domain}/privkey.pem', str(found[1])) text = text.replace('127.0.0.1:8080', addr) return {'domain': domain, 'existing': False, 'target': target, 'text': text, 'nginx': nginx, 'reload': reload_command} def apply_nginx(plan): if not plan or plan['existing']: return target = plan['target'] previous = target.read_bytes() if target.exists() else None if previous is not None: # Backups live outside the *.conf include namespace, with exclusive creation. with tempfile.NamedTemporaryFile(prefix=target.name + '.', suffix='.bak', dir=target.parent, delete=False) as backup: backup.write(previous) print(f'Nginx 原配置备份:{backup.name}') try: atomic_config(target, plan['text'].encode()) run([plan['nginx'], '-t']) run(plan['reload']) except (OSError, subprocess.CalledProcessError): if previous is None: target.unlink(missing_ok=True) else: atomic_config(target, previous) # Reload again so a partially successful first reload cannot retain new config. subprocess.run([str(v) for v in plan['reload']], check=False) raise InstallError('Nginx 检查或重载失败,已恢复配置;主控程序仍保留,可修复后重跑向导。') from None def atomic_config(target, content): if target.is_symlink() or target.exists() and not target.is_file(): raise InstallError('拒绝写入非普通 Nginx 配置文件。') with tempfile.NamedTemporaryFile(dir=target.parent, prefix='.sea-vhost-', delete=False) as stream: temporary = Path(stream.name) try: stream.write(content) stream.flush() os.fchmod(stream.fileno(), 0o644) except BaseException: temporary.unlink(missing_ok=True) raise try: os.replace(temporary, target) finally: temporary.unlink(missing_ok=True) def install_controller(ui, role, values): if role == 'combined' and not Path('/www/server/panel').is_dir(): raise InstallError('兼本机托管需要本机宝塔;没有宝塔时请选择独立主控。') plan = nginx_plan(ui, values) print(f'\n安装角色:{ROLES[role]}\n平台数据:保留已有配置;首次安装的数据库与管理员信息在 Web 安装页填写') if plan: print('管理地址:https://' + plan['domain']) if not ui.confirm('开始安装/更新并启动服务'): return False script = 'install-controller.sh' if role == 'controller' else 'install.sh' run(['bash', SOURCE / 'deploy' / script, '--non-interactive']) units = ['sea-vhost-api'] if role == 'controller' else ['sea-vhost-agent', 'sea-vhost-panel-broker', 'sea-vhost-api'] run(['systemctl', 'enable', *units]) run(['systemctl', 'restart', *units]) wait_services(units) wait_api(values) apply_nginx(plan) print('\n主控安装完成,服务已启动。') if plan: print('打开 https://' + plan['domain'] + '/ 完成 Web 安装;已安装则直接登录。') else: print('管理站点根目录:/opt/sea-vhost/web;/api/ 反代至 http://' + values.get('SEA_ADDR', '127.0.0.1:8080')) if not CONFIG.exists(): token = environment().get('SEA_SETUP_TOKEN', '') if token: print('Web 安装令牌(请保密):' + token) return True def main(argv=None): parser = argparse.ArgumentParser(description='Sea vHost 中文交互式安装向导;保留现有数据,不自动转换安装角色。') parser.add_argument('--role', choices=ROLES, help='预选安装角色') options = parser.parse_args(argv) if platform.system() != 'Linux' or platform.machine() not in ('x86_64', 'amd64'): raise InstallError('当前安装包仅支持 Debian Linux amd64。') if os.geteuid() != 0: raise InstallError('请使用 root 运行安装向导。') if not sys.stdin.isatty(): raise InstallError('交互向导需要终端;自动化部署请使用原脚本的 --non-interactive 模式。') os.umask(0o077) ui = Console() values = environment() print('\nSea vHost 安装向导\n回车采用默认值,Ctrl+C 取消;密码输入不会显示。\n') role = options.role if not role: default = '3' if NODE_CONFIG.exists() else '2' if values.get('SEA_CONTROLLER_ONLY') == 'true' else '1' print('1. 主控兼本机托管(已有宝塔的服务器)\n2. 独立主控(仅管理其他被控)\n3. 被控节点(已有宝塔的服务器)') while not role: role = {'1': 'combined', '2': 'controller', '3': 'node'}.get(ui.ask('选择安装角色', default)) if not role: print('请输入 1、2 或 3。') check_role(role, values) check_build(role) for command in ('bash', 'systemctl', 'openssl'): if not shutil.which(command): raise InstallError(f'缺少必要命令 {command},请安装后重试。') completed = install_node(ui) if role == 'node' else install_controller(ui, role, values) if not completed: print('安装已取消。') return 0 if __name__ == '__main__': try: sys.exit(main()) except (KeyboardInterrupt, EOFError): print('\n安装已取消;已完成的安装步骤会保留,可再次运行向导继续。', file=sys.stderr) sys.exit(130) except subprocess.CalledProcessError as error: print(f'\n安装命令失败(退出码 {error.returncode}),请检查上方输出;修复后可重新运行向导。', file=sys.stderr) sys.exit(1) except (InstallError, OSError, ValueError, TypeError, KeyError) as error: # Never print config contents, subprocess input or stored credentials. print(f'\n安装未完成:{error}', file=sys.stderr) sys.exit(1)