Files
hk4e-gm-clone/core/ssh.py
T

167 lines
6.1 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.
"""SSH 服务端管理 —— 复刻 hk4eGM.Helpers.SshUtil + SshViewModel。
原程序的服务类型(枚举):GameServer / MuipServer / GateServer / NodeServer /
DbGate / Dispatch / Via / Sdk / MultiServer。
启动方式(从 IL 还原):
SDK : screen -dmS sdkserver; screen -S sdkserver -X stuff 'cd <目录> && java -jar <jar>\\n'
Via : cd <目录>; nohup ./ViaGenshin >/dev/null 2>&1 &
其它 : cd <目录>/<服务>; nohup ./<服务> -i <绑定地址> >/dev/null 2>&1 &
停止:kill -15 <pid>,等待超时后 kill -9
状态:pgrep -f <进程名> + top -b -n 1 -E m | grep <进程名> | awk '{print $6"\\t"$9}'
日志:ls -f <目录>/logs、rm -rf 清理
"""
from __future__ import annotations
import re
import time
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional
try:
import paramiko
except Exception: # pragma: no cover
paramiko = None
@dataclass
class ServiceDef:
key: str
label: str
process: str
kind: str = "java" # java / via / sdk
SERVICES: List[ServiceDef] = [
ServiceDef("GameServer", "GameServer 游戏服", "GameServer"),
ServiceDef("MuipServer", "MuipServer GM接口", "MuipServer"),
ServiceDef("GateServer", "GateServer 网关", "GateServer"),
ServiceDef("NodeServer", "NodeServer 节点", "NodeServer"),
ServiceDef("DbGate", "DbGate 数据库网关", "DbGate"),
ServiceDef("Dispatch", "Dispatch 调度", "Dispatch"),
ServiceDef("Via", "Via 代理", "ViaGenshin", "via"),
ServiceDef("Sdk", "SDK 登录服", "sdkserver", "sdk"),
ServiceDef("MultiServer", "MultiServer 多服", "MultiServer"),
]
SERVICE_MAP = {s.key: s for s in SERVICES}
class SshError(Exception):
pass
class SshClient:
def __init__(self, cfg, log: Optional[Callable[[str], None]] = None):
self.cfg = cfg
self.log = log or (lambda m: None)
self._client = None
# ------------------------------------------------------------------ 连接
@property
def connected(self) -> bool:
c = self._client
if c is None:
return False
t = c.get_transport()
return bool(t and t.is_active())
def connect(self, timeout: float = 8.0) -> str:
if paramiko is None:
raise SshError("未安装 paramiko:pip install paramiko")
self.close()
host = self.cfg.get("SSH", "IP地址", "127.0.0.1")
port = self.cfg.get_int("SSH", "端口", 22)
user = self.cfg.get("SSH", "用户名", "root")
pwd = self.cfg.get("SSH", "密码", "")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=host, port=port, username=user, password=pwd,
timeout=timeout, banner_timeout=timeout, auth_timeout=timeout,
look_for_keys=False, allow_agent=False)
except Exception as exc:
raise SshError(f"SSH 连接失败:{exc}")
self._client = client
return "SSH 连接成功"
def close(self) -> None:
if self._client is not None:
try:
self._client.close()
except Exception:
pass
self._client = None
# ------------------------------------------------------------------ 执行
def run(self, command: str, timeout: float = 25.0) -> str:
if not self.connected:
self.connect()
assert self._client is not None
wrapped = 'bash -l -c "%s"' % command.replace('"', '\\"')
try:
stdin, stdout, stderr = self._client.exec_command(wrapped, timeout=timeout)
out = stdout.read().decode("utf-8", "replace")
err = stderr.read().decode("utf-8", "replace")
return (out + err).strip()
except Exception as exc:
raise SshError(f"命令执行失败:{exc}")
# ------------------------------------------------------------------ 业务
@property
def server_dir(self) -> str:
return self.cfg.get("SSH", "服务目录", "/genshin/srv").rstrip("/")
def is_running(self, svc: ServiceDef) -> Optional[str]:
"""返回 pid,未运行返回 None。"""
out = self.run(f"pgrep -f {svc.process}")
pids = [x for x in out.split() if x.isdigit()]
return pids[0] if pids else None
def resource(self, svc: ServiceDef) -> str:
"""CPU% / MEM% 两列(原程序 top + awk 方案)。"""
cmd = (f"top -b -n 1 -E m | grep {svc.process} | "
f"awk '{{print $6\"\\t\"$9}}' | head -n 1")
return self.run(cmd).strip()
def start(self, svc: ServiceDef, bind: str = "0.0.0.0") -> str:
d = self.server_dir
if svc.kind == "sdk":
jar = f"{d}/sdk/sdk-server.jar"
cmd = (f"screen -S sdkserver -X quit; "
f"screen -dmS sdkserver; "
f"screen -S sdkserver -X stuff 'cd {d}/sdk && java -jar {jar}\\n'")
elif svc.kind == "via":
cmd = f"cd {d} ; nohup ./ViaGenshin >/dev/null 2>&1 &"
else:
cmd = f"cd {d}/{svc.key} ; nohup ./{svc.key} -i {bind} >/dev/null 2>&1 &"
return self.run(cmd)
def stop(self, svc: ServiceDef, wait_seconds: int = 12) -> str:
pid = self.is_running(svc)
if not pid:
return f"{svc.label} 未运行"
self.run(f"kill -15 {pid}")
deadline = time.time() + wait_seconds
while time.time() < deadline:
if not self.is_running(svc):
return f"{svc.label} 已关闭({pid})"
time.sleep(0.8)
self.run(f"kill -9 {pid}")
return f"{svc.label} 等待超时,已强制关闭({pid})"
def status_line(self, svc: ServiceDef) -> str:
pid = self.is_running(svc)
if not pid:
return "未运行"
res = self.resource(svc)
return f"运行中 PID={pid} {res}"
def clear_logs(self) -> str:
d = self.server_dir
return self.run(f"rm -rf {d}/logs/*") or "日志已清理"
def list_logs(self) -> str:
d = self.server_dir
return self.run(f"ls -f {d}/logs | head -n 50")