CLI 视觉升级:tui.py 真彩色界面
- 配色与 GUI 同源(石墨底/青绿点缀),支持 NO_COLOR 与非 tty 自动降级纯文本 - 向导:对齐横幅、❯ 方向键选择菜单(↑↓/数字/回车,q 取消),彩色表单提示 - 隧道运行时实时面板:状态·运行时长·累计连接·滚动日志,原地刷新 - Ctrl+C 退出时面板干净收起;非交互终端自动退化为编号选择
This commit is contained in:
@@ -23,6 +23,7 @@ sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from engine import TunnelManager, probe_host # noqa: E402
|
||||
from storage import Store, data_root # noqa: E402
|
||||
import tui # noqa: E402
|
||||
|
||||
|
||||
def _print(msg: str) -> None:
|
||||
@@ -30,26 +31,32 @@ def _print(msg: str) -> None:
|
||||
|
||||
|
||||
class _QuietEmit:
|
||||
"""CLI 模式下把引擎事件打到终端。"""
|
||||
"""引擎事件 → 运行面板(无面板时打印到终端)。"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, dash: "tui.Dashboard | None" = None):
|
||||
self._last: dict[str, str] = {}
|
||||
self._dash = dash
|
||||
|
||||
def __call__(self, ev: dict) -> None:
|
||||
if ev.get("type") == "tunnel":
|
||||
if self._last.get(ev["id"]) == ev["status"]:
|
||||
return # 状态未变(如连接计数刷新),不重复打印
|
||||
return # 状态未变(如连接计数刷新)
|
||||
self._last[ev["id"]] = ev["status"]
|
||||
t = ev["status"]
|
||||
if t == "connected":
|
||||
_print("[隧道] 已连接")
|
||||
elif t == "error":
|
||||
_print(f"[隧道] 连接失败: {ev.get('error', '')}")
|
||||
if ev["status"] == "error" and self._dash:
|
||||
self._dash.log(tui.err(f"✘ {ev.get('error', '')}"))
|
||||
elif not self._dash:
|
||||
if ev["status"] == "connected":
|
||||
_print(tui.ok("[隧道] 已连接"))
|
||||
elif ev["status"] == "error":
|
||||
_print(tui.err(f"[隧道] 连接失败: {ev.get('error', '')}"))
|
||||
elif ev.get("type") == "log":
|
||||
e = ev["entry"]
|
||||
lv = e["level"]
|
||||
mark = {"info": "·", "success": "✔", "warn": "!", "error": "×"}.get(lv, "·")
|
||||
_print(f"[{e['t']}] {mark} {e['msg']}")
|
||||
mark = {"info": "·", "success": "✔", "warn": "!", "error": "×"}.get(e["level"], "·")
|
||||
line = f"{e['t']} {mark} {e['msg']}"
|
||||
if self._dash:
|
||||
self._dash.log(line)
|
||||
else:
|
||||
_print(line)
|
||||
|
||||
|
||||
def find_host(store: Store, ref: str):
|
||||
@@ -113,19 +120,22 @@ def cmd_tunnel_add(store, args) -> int:
|
||||
def cmd_list(store, _args) -> int:
|
||||
if store.warn_plaintext:
|
||||
_print("提示: 当前平台密码以明文保存于配置文件(权限已设为仅本用户可读)。")
|
||||
_print("主机:")
|
||||
print(tui.bold("主机"))
|
||||
if not store.data["hosts"]:
|
||||
_print(" (无) 添加: ssh-tunnel host add <名称> user@host")
|
||||
print(tui.faint(" (无) ssh-tunnel 进入向导添加"))
|
||||
for h in store.data["hosts"]:
|
||||
_print(f" {h['name']} {h['username']}@{h['hostname']}:{h['port']} "
|
||||
f"{'私钥' if h.get('auth') == 'key' else '密码'}")
|
||||
_print("隧道:")
|
||||
auth = "私钥" if h.get("auth") == "key" else "密码"
|
||||
print(f" {tui.accent('▣')} {h['name']} "
|
||||
f"{tui.dim(f'{h["username"]}@{h["hostname"]}:{h["port"]}')} {tui.faint(auth)}")
|
||||
print(tui.bold("隧道"))
|
||||
if not store.data["tunnels"]:
|
||||
_print(" (无) 添加: ssh-tunnel tunnel add <名称> --host <主机> --lp 本地端口 --rp 远程端口")
|
||||
print(tui.faint(" (无) ssh-tunnel 进入向导添加"))
|
||||
for t in store.data["tunnels"]:
|
||||
h = next((x for x in store.data["hosts"] if x["id"] == t["host_id"]), None)
|
||||
hn = h["name"] if h else "(主机缺失)"
|
||||
_print(f" {t['name']} 127.0.0.1:{t['local_port']} → {t['remote_host']}:{t['remote_port']} 经 {hn}")
|
||||
print(f" {tui.accent('⇄')} {t['name']} "
|
||||
f"{tui.dim(f'127.0.0.1:{t["local_port"]} → {t["remote_host"]}:{t["remote_port"]}')} "
|
||||
f"{tui.faint(f'经 {hn}')}")
|
||||
return 0
|
||||
|
||||
|
||||
@@ -165,23 +175,36 @@ def cmd_remove(store, args) -> int:
|
||||
|
||||
|
||||
def run_foreground(store: Store, chosen: list) -> int:
|
||||
"""前台运行选中的隧道,Ctrl+C 退出。"""
|
||||
"""前台运行选中的隧道,Ctrl+C 退出。tty 下显示实时状态面板。"""
|
||||
hosts_by_id = {h["id"]: h for h in store.data["hosts"]}
|
||||
mgr = TunnelManager(_QuietEmit(), data_root())
|
||||
dash = tui.Dashboard()
|
||||
mgr = TunnelManager(_QuietEmit(dash), data_root())
|
||||
mgr.apply_config(chosen, hosts_by_id)
|
||||
|
||||
if store.warn_plaintext:
|
||||
_print("提示: 当前平台密码以明文保存于配置文件(权限已设为仅本用户可读)。")
|
||||
names = ", ".join(t["name"] for t in chosen)
|
||||
_print(f"启动隧道: {names} — Ctrl+C 退出")
|
||||
print()
|
||||
print(tui.faint(" " + ", ".join(t["name"] for t in chosen) + " — Ctrl+C 退出"))
|
||||
|
||||
stopping = False
|
||||
|
||||
def _stats():
|
||||
return [{
|
||||
"name": t.cfg.get("name", t.cfg["id"]),
|
||||
"local_port": t.cfg["local_port"],
|
||||
"remote": f"{t.cfg['remote_host']}:{t.cfg['remote_port']}",
|
||||
"status": t.status, "started_at": t.started_at,
|
||||
"conns": t.conn_count, "error": t.error,
|
||||
} for t in mgr.tunnels.values()]
|
||||
|
||||
def _stop(*_a):
|
||||
nonlocal stopping
|
||||
if not stopping:
|
||||
stopping = True
|
||||
_print("\n正在断开所有隧道 ...")
|
||||
print() # 光标移到面板下方行首
|
||||
dash.close()
|
||||
_print("正在断开所有隧道 ...")
|
||||
sys.stdout.flush()
|
||||
mgr.stop_all()
|
||||
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
@@ -190,13 +213,15 @@ def run_foreground(store: Store, chosen: list) -> int:
|
||||
t.start()
|
||||
try:
|
||||
while not stopping:
|
||||
time.sleep(0.3)
|
||||
alive = [t for t in mgr.tunnels.values() if t.status != "stopped"]
|
||||
if not alive:
|
||||
_print("所有隧道已停止。")
|
||||
time.sleep(0.5)
|
||||
dash.update(_stats())
|
||||
if not [t for t in mgr.tunnels.values() if t.status != "stopped"]:
|
||||
dash.close()
|
||||
_print(tui.err("所有隧道已停止。"))
|
||||
return 1
|
||||
except KeyboardInterrupt:
|
||||
_stop()
|
||||
dash.close()
|
||||
return 0
|
||||
|
||||
|
||||
@@ -269,34 +294,31 @@ def _ask_secret(prompt: str) -> str:
|
||||
def _wizard_pick_host(store: Store):
|
||||
"""选择已有主机或新建;返回主机 dict 或 None(取消)。"""
|
||||
hosts = store.data["hosts"]
|
||||
_print("\n── 第 1 步:选择 SSH 主机 ──")
|
||||
for i, h in enumerate(hosts, 1):
|
||||
_print(f" {i}. {h['name']} ({h['username']}@{h['hostname']}:{h['port']})")
|
||||
_print(f" {len(hosts) + 1}. 新增主机")
|
||||
|
||||
while True:
|
||||
sel = _ask(f"请选择 [1-{len(hosts) + 1}]", str(len(hosts) + 1 if not hosts else "1"))
|
||||
if not sel.isdigit() or not (1 <= int(sel) <= len(hosts) + 1):
|
||||
_print(" 无效选择,请重新输入")
|
||||
continue
|
||||
n = int(sel)
|
||||
if n <= len(hosts):
|
||||
return hosts[n - 1]
|
||||
return _wizard_new_host(store)
|
||||
print()
|
||||
print(tui.bold("◇ SSH 主机"))
|
||||
opts = [f"{h['name']} ({h['username']}@{h['hostname']}:{h['port']})" for h in hosts]
|
||||
opts.append(tui.dim("+ 新增主机") if len(hosts) else "+ 新增主机")
|
||||
n = tui.select(" 选择要使用的主机:", opts, default=len(hosts) if not hosts else 0)
|
||||
if n is None:
|
||||
return None
|
||||
if n < len(hosts):
|
||||
return hosts[n]
|
||||
return _wizard_new_host(store)
|
||||
|
||||
|
||||
def _wizard_new_host(store: Store):
|
||||
_print("\n新增主机(带 * 的为必填):")
|
||||
print()
|
||||
print(tui.bold("◇ 新增主机") + tui.faint(" (带 * 为必填)"))
|
||||
while True:
|
||||
target = _ask(" * SSH 登录目标 (格式 用户名@主机,如 root@1.2.3.4): ")
|
||||
target = _ask(" " + tui.accent("SSH 登录目标") + tui.faint(" (用户名@主机,如 root@1.2.3.4)") + ": ")
|
||||
if "@" in target and len(target.split("@")) == 2 and target.split("@")[1]:
|
||||
break
|
||||
_print(" 格式不对,应类似 root@1.2.3.4")
|
||||
print(tui.warn(" 格式不对,应类似 root@1.2.3.4"))
|
||||
user, hostaddr = target.rsplit("@", 1)
|
||||
port = _ask_port(" SSH 端口 [22]: ", 22)
|
||||
auth = _ask(" 认证方式 1) 密码 2) 私钥 [1]: ", "1")
|
||||
port = _ask_port(" " + tui.accent("SSH 端口") + tui.faint(" [22]"), 22)
|
||||
auth = _ask(" " + tui.accent("认证方式") + tui.faint(" 1)密码 2)私钥 [1]"), "1")
|
||||
while auth not in ("1", "2"):
|
||||
auth = _ask(" 请输入 1 或 2: ", "1")
|
||||
auth = _ask(" 请输入 1 或 2: ", "1")
|
||||
|
||||
rec = {
|
||||
"id": Store.new_id(), "name": "", "hostname": hostaddr, "port": port,
|
||||
@@ -304,61 +326,59 @@ def _wizard_new_host(store: Store):
|
||||
"password": "", "key_path": "", "key_passphrase": "", "note": "",
|
||||
}
|
||||
if rec["auth"] == "key":
|
||||
rec["key_path"] = _ask(" * 私钥文件路径 (如 ~/.ssh/id_rsa): ")
|
||||
rec["key_path"] = _ask(" " + tui.accent("* 私钥文件路径") + tui.faint(" (如 ~/.ssh/id_rsa)") + ": ")
|
||||
rec["key_passphrase"] = _ask_secret(" 私钥口令 (没有则直接回车): ")
|
||||
else:
|
||||
rec["password"] = _ask_secret(" * 登录密码 (输入时不显示): ")
|
||||
rec["name"] = _ask(" 主机备注名 [默认取地址]: ", hostaddr)
|
||||
rec["password"] = _ask_secret(" " + tui.accent("* 登录密码") + tui.faint(" (输入时不显示)") + ": ")
|
||||
rec["name"] = _ask(" " + tui.accent("主机备注名") + tui.faint(f" [{hostaddr}]") + ": ", hostaddr)
|
||||
|
||||
# 连通测试,失败可重试输入
|
||||
while True:
|
||||
_print(f"正在测试 {user}@{hostaddr}:{port} ...")
|
||||
print(tui.faint(f" 正在测试 {user}@{hostaddr}:{port} ..."))
|
||||
ok, msg = probe_host(rec, data_root() / "known_hosts")
|
||||
_print((" ✔ " if ok else " ✘ ") + msg)
|
||||
print((" " + tui.ok("✔ ") + tui.ok(msg)) if ok else (" " + tui.err("✘ ") + tui.err(msg)))
|
||||
if ok:
|
||||
break
|
||||
retry = _ask(" 连接失败。重试请回车,修改密码输入 p,放弃输入 q [回车重试]: ", "")
|
||||
retry = _ask(" " + tui.warn("连接失败") + tui.faint(" — 回车重试 / p 改密码 / q 放弃") + ": ", "")
|
||||
if retry.lower() == "q":
|
||||
return None
|
||||
if retry.lower() == "p" and rec["auth"] == "password":
|
||||
rec["password"] = _ask_secret(" * 重新输入登录密码: ")
|
||||
rec["password"] = _ask_secret(" 重新输入登录密码: ")
|
||||
|
||||
store.data["hosts"].append(rec)
|
||||
store.save()
|
||||
_print(f"已保存主机「{rec['name']}」")
|
||||
print(" " + tui.ok(f"已保存主机「{rec['name']}」"))
|
||||
return rec
|
||||
|
||||
|
||||
def _wizard_pick_tunnel(store: Store, host: dict):
|
||||
"""选择该主机的已有隧道或新建;返回隧道 dict 或 None。"""
|
||||
ts = [t for t in store.data["tunnels"] if t["host_id"] == host["id"]]
|
||||
_print("\n── 第 2 步:配置隧道 ──")
|
||||
for i, t in enumerate(ts, 1):
|
||||
_print(f" {i}. {t['name']} (127.0.0.1:{t['local_port']} → {t['remote_host']}:{t['remote_port']})")
|
||||
_print(f" {len(ts) + 1}. 新建隧道")
|
||||
|
||||
while True:
|
||||
sel = _ask(f"请选择 [1-{len(ts) + 1}]", str(len(ts) + 1 if not ts else "1"))
|
||||
if not sel.isdigit() or not (1 <= int(sel) <= len(ts) + 1):
|
||||
_print(" 无效选择,请重新输入")
|
||||
continue
|
||||
n = int(sel)
|
||||
if n <= len(ts):
|
||||
return ts[n - 1]
|
||||
return _wizard_new_tunnel(store, host)
|
||||
print()
|
||||
print(tui.bold("◇ 隧道"))
|
||||
opts = [f"{t['name']} (127.0.0.1:{t['local_port']} → {t['remote_host']}:{t['remote_port']})"
|
||||
for t in ts]
|
||||
opts.append("+ 新建隧道")
|
||||
n = tui.select(" 选择要启动的隧道:", opts, default=len(ts) if not ts else 0)
|
||||
if n is None:
|
||||
return None
|
||||
if n < len(ts):
|
||||
return ts[n]
|
||||
return _wizard_new_tunnel(store, host)
|
||||
|
||||
|
||||
def _wizard_new_tunnel(store: Store, host: dict):
|
||||
_print("\n新建隧道:把远程主机上的服务映射到本机端口")
|
||||
_print(" (远程服务只监听 127.0.0.1 时,远程地址保持默认即可)")
|
||||
rh = _ask(" 远程服务地址 [127.0.0.1]: ", "127.0.0.1")
|
||||
rp = _ask_port(" * 远程服务端口 (如 3000): ")
|
||||
lp = _ask_port(f" 本地端口 [{rp}]: ", rp)
|
||||
print()
|
||||
print(tui.bold("◇ 新建隧道") + tui.faint(" 把远程主机上的服务映射到本机端口"))
|
||||
print(tui.faint(" (远程服务只监听 127.0.0.1 时,远程地址保持默认即可)"))
|
||||
rh = _ask(" " + tui.accent("远程服务地址") + tui.faint(" [127.0.0.1]") + ": ", "127.0.0.1")
|
||||
rp = _ask_port(" " + tui.accent("* 远程服务端口") + tui.faint(" (如 3000)") + ": ")
|
||||
lp = _ask_port(" " + tui.accent("本地端口") + tui.faint(f" [{rp}]") + ": ", rp)
|
||||
for t in store.data["tunnels"]:
|
||||
if t["local_port"] == lp:
|
||||
_print(f" 本地端口 {lp} 已被隧道「{t['name']}」占用")
|
||||
print(tui.warn(f" 本地端口 {lp} 已被隧道「{t['name']}」占用"))
|
||||
lp = _ask_port(" 换一个本地端口: ")
|
||||
name = _ask(f" 隧道备注名 [{rh}:{rp}]: ", f"{rh}:{rp}")
|
||||
name = _ask(" " + tui.accent("隧道备注名") + tui.faint(f" [{rh}:{rp}]") + ": ", f"{rh}:{rp}")
|
||||
rec = {
|
||||
"id": Store.new_id(), "name": name, "host_id": host["id"],
|
||||
"local_port": lp, "remote_host": rh, "remote_port": rp,
|
||||
@@ -366,17 +386,20 @@ def _wizard_new_tunnel(store: Store, host: dict):
|
||||
}
|
||||
store.data["tunnels"].append(rec)
|
||||
store.save()
|
||||
_print(f"已保存隧道「{name}」")
|
||||
print(" " + tui.ok(f"已保存隧道「{name}」"))
|
||||
return rec
|
||||
|
||||
|
||||
def wizard(store: Store) -> int:
|
||||
_ensure_tty_stdin()
|
||||
_print("╭─────────────────────────────╮")
|
||||
_print("│ SSH 隧道配置向导 │")
|
||||
_print("╰─────────────────────────────╯")
|
||||
_print("按中文提示输入,直接回车采用 [方括号] 里的默认值;Ctrl+C 随时退出。")
|
||||
_print(f"配置文件: {store.path}")
|
||||
title = "SSH 隧道配置向导"
|
||||
sub = "回车采用 [方括号] 默认值 · Ctrl+C 随时退出"
|
||||
w = max(tui.disp_len(title) + 4, tui.disp_len(sub) + 4, 40)
|
||||
print()
|
||||
print(tui.accent("╭─ ") + tui.bold(title) + " " + tui.accent("─" * (w - tui.disp_len(title) - 3) + "╮"))
|
||||
print(tui.accent("│") + " " + tui.faint(sub) + " " * (w - tui.disp_len(sub) - 2) + tui.accent("│"))
|
||||
print(tui.accent("╰" + "─" * w + "╯"))
|
||||
print(tui.faint(f" 配置文件: {store.path}"))
|
||||
|
||||
if store.warn_plaintext:
|
||||
_print("提示: 当前平台密码以明文保存于配置文件(权限已设为仅本用户可读)。")
|
||||
|
||||
Reference in New Issue
Block a user