# -*- coding: utf-8 -*- """随身 WiFi(Debian)远程执行小工具。 用法: python _build/devssh.py "命令" # 跑一条命令 python _build/devssh.py --script 文件 # 跑一段脚本 """ from __future__ import annotations import sys import time from pathlib import Path import paramiko # 随身 WiFi(Debian)的地址。 # # 这台设备跟着教室网络走,地址会变: # 192.168.2.156 -> 192.168.10.105(换网络了) # 所以优先读环境变量 YKXMZ_DEV_HOST,没有才用下面的默认值。 # 换网络时不用改代码: # $env:YKXMZ_DEV_HOST = "192.168.10.105" import os HOST = os.environ.get("YKXMZ_DEV_HOST", "192.168.10.105") USER = "root" PASSWORD = os.environ.get("YKXMZ_DEV_PASS", "1313144") # 旧地址留一份,方便回退或同时探测 HOST_FALLBACKS = ("192.168.10.105", "192.168.2.156") def run(command: str, timeout: int = 600, quiet: bool = False) -> tuple: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(HOST, username=USER, password=PASSWORD, timeout=15, banner_timeout=20, auth_timeout=20, look_for_keys=False, allow_agent=False) try: _stdin, stdout, stderr = client.exec_command(command, timeout=timeout) out = stdout.read().decode("utf-8", "replace") err = stderr.read().decode("utf-8", "replace") code = stdout.channel.recv_exit_status() if not quiet: if out.strip(): print(out.rstrip()) if err.strip(): print("[stderr] " + err.rstrip()) return code, out, err finally: client.close() def upload(local: str, remote: str, mode: int = 0o644) -> None: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(HOST, username=USER, password=PASSWORD, timeout=15, look_for_keys=False, allow_agent=False) try: sftp = client.open_sftp() sftp.put(local, remote) sftp.chmod(remote, mode) sftp.close() print(f" 已上传 {Path(local).name} -> {remote}") finally: client.close() def download(remote: str, local: str) -> None: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(HOST, username=USER, password=PASSWORD, timeout=15, look_for_keys=False, allow_agent=False) try: sftp = client.open_sftp() sftp.get(remote, local) sftp.close() print(f" 已下载 {remote} -> {local}") finally: client.close() if __name__ == "__main__": if len(sys.argv) < 2: print(__doc__) sys.exit(1) if sys.argv[1] == "--script": run(Path(sys.argv[2]).read_text(encoding="utf-8"), timeout=600) else: args = sys.argv[1:] timeout = 600 if args and args[0] == '--timeout': timeout = int(args[1]) args = args[2:] run(" ".join(args), timeout=timeout)