@hfyjq/crannia 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +48 -45
- package/README.md +1 -1
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON-linux.md +174 -0
- package/THIRD-PARTY-PYTHON.md +176 -162
- package/THIRD-PARTY.md +323 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +677 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/provider_loader.py +4 -7
- package/bus/loaders/skill_loader.py +46 -27
- package/bus/loaders/skill_md.py +9 -9
- package/bus/mcp_disabled.py +4 -6
- package/bus/quarantine.py +10 -13
- package/bus/registry.py +2315 -2284
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/handler.py +3 -3
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/handler.py +32 -32
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/handler.py +33 -33
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +24 -24
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +21 -21
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/converter.py +1 -1
- package/channels/wechat_channel/handler.py +8 -8
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/core/activity.py +753 -709
- package/core/agent_loop.py +7673 -7523
- package/core/allowlist.py +2 -3
- package/core/approval.py +36 -26
- package/core/approval_timeout.py +256 -228
- package/core/artifacts.py +3 -3
- package/core/attachment_gc.py +21 -0
- package/core/auto_review.py +2 -2
- package/core/browser/cdp.py +5 -2
- package/core/browser/discover.py +55 -19
- package/core/browser/session.py +4 -4
- package/core/cache_break_detector.py +97 -0
- package/core/cache_breakpoints.py +103 -0
- package/core/cache_policies.py +255 -0
- package/core/cancellation.py +3 -3
- package/core/channel_configs.py +3 -3
- package/core/channel_turns.py +13 -13
- package/core/child_approval.py +2 -3
- package/core/code_intel.py +11 -11
- package/core/command_policy.py +13 -7
- package/core/computer/annotate.py +231 -11
- package/core/computer/capture.py +140 -1
- package/core/computer/guard.py +7 -4
- package/core/computer/input.py +452 -26
- package/core/computer/session.py +563 -381
- package/core/computer/tools.py +2170 -928
- package/core/computer/uia.py +100 -1
- package/core/computer/watch.py +1 -1
- package/core/computer/win32.py +302 -7
- package/core/config_requirements.py +205 -205
- package/core/cron/runner.py +4 -4
- package/core/daily_log.py +2 -2
- package/core/dedup.py +2 -2
- package/core/egress_channels.py +326 -0
- package/core/egress_gate.py +96 -8
- package/core/egress_preapproved.py +59 -3
- package/core/endpoint.py +141 -141
- package/core/events.py +17 -8
- package/core/extension.py +2 -2
- package/core/file_history.py +15 -15
- package/core/file_tools.py +3 -3
- package/core/github_config.py +1 -1
- package/core/group_digest.py +3 -4
- package/core/group_minutes.py +5 -5
- package/core/group_reply.py +24 -0
- package/core/groups.py +5 -9
- package/core/hooks.py +15 -15
- package/core/i18n.py +2 -2
- package/core/ice/canary.py +3 -3
- package/core/ice/net_heuristics.py +2 -2
- package/core/im_routing.py +3 -3
- package/core/image_input.py +183 -43
- package/core/inbound.py +3 -3
- package/core/jobs.py +6 -6
- package/core/last_good.py +150 -150
- package/core/leaf_md.py +3 -3
- package/core/llm_errors.py +37 -28
- package/core/mail_config.py +2 -2
- package/core/memory/compressor.py +8 -8
- package/core/memory/manager.py +30 -45
- package/core/memory/session_memory.py +1 -2
- package/core/memory/short_term.py +4 -4
- package/core/memory_extract.py +1 -1
- package/core/memory_organize.py +8 -8
- package/core/memory_store.py +7 -9
- package/core/memory_transfer.py +2 -2
- package/core/model_capabilities.py +2 -2
- package/core/model_configs.py +219 -68
- package/core/model_profiles.py +333 -0
- package/core/modes.py +12 -11
- package/core/net_proxy.py +3 -3
- package/core/pipeline/scheduler.py +48 -43
- package/core/pipeline/stage.py +3 -0
- package/core/pipeline/stages/agent_loop.py +36 -15
- package/core/pipeline/stages/group_reply.py +22 -20
- package/core/pipeline/stages/post_process.py +7 -7
- package/core/pipeline/stages/pre_process.py +369 -77
- package/core/prompt_assembler.py +13 -4
- package/core/recycle.py +227 -16
- package/core/response_language.py +1 -1
- package/core/retention.py +2 -2
- package/core/rg.py +4 -3
- package/core/security.py +26 -8
- package/core/services.py +8 -8
- package/core/session_model.py +3 -5
- package/core/session_pool.py +35 -5
- package/core/session_recap.py +40 -3
- package/core/session_workspace.py +2 -3
- package/core/settings_baseline.py +2 -2
- package/core/settings_transfer.py +25 -1
- package/core/shell.py +52 -20
- package/core/side_call.py +3 -3
- package/core/skill_config.py +164 -0
- package/core/skill_factory.py +2 -2
- package/core/skill_guidance.py +2 -4
- package/core/skill_index.py +3 -4
- package/core/skill_settings.py +1 -1
- package/core/skill_sources.py +7 -7
- package/core/ssh_config.py +129 -0
- package/core/state_registry.py +67 -5
- package/core/subagent.py +28 -5
- package/core/subagent_defs.py +3 -3
- package/core/summarizer.py +4 -5
- package/core/tasks_notify.py +6 -6
- package/core/tiers.py +2 -2
- package/core/todos.py +1 -1
- package/core/token_calibrator.py +1 -4
- package/core/tool_outcome.py +108 -108
- package/core/touched_files.py +1 -1
- package/core/trace.py +12 -3
- package/core/unlock.py +4 -4
- package/core/update_tui.py +184 -158
- package/core/updater.py +5 -3
- package/core/version.py +14 -14
- package/core/vision_budget.py +235 -0
- package/core/web_cache.py +152 -152
- package/core/web_request.py +474 -0
- package/core/window_estimate.py +1 -1
- package/core/workspace.py +56 -26
- package/crannia_tray.py +278 -278
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +1876 -1762
- package/main.py +154 -154
- package/mcpx/client.py +12 -1
- package/mcpx/manager.py +530 -522
- package/mcpx/servers/web_search.py +5 -13
- package/package.json +15 -23
- package/providers/anthropic/client.py +35 -33
- package/providers/base.py +13 -13
- package/providers/cache_policies.json +294 -0
- package/providers/cost_table.json +3779 -3779
- package/providers/lmstudio/client.py +2 -2
- package/providers/model_capabilities.json +6665 -6665
- package/providers/model_profiles.json +629 -0
- package/providers/ollama/client.py +2 -2
- package/providers/openai_compat.py +37 -16
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +2 -2
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/vision_profiles.json +89 -0
- package/providers/window_table.json +8909 -8909
- package/requirements.txt +59 -51
- package/sbom-linux-x64.json +4580 -0
- package/sbom.json +4600 -4413
- package/skills/diagram/SKILL.md +47 -0
- package/skills/diagram/__init__.py +1 -0
- package/skills/diagram/handler.py +294 -0
- package/skills/diagram/layout.py +174 -0
- package/skills/diagram/manifest.yaml +106 -0
- package/skills/diagram/mermaid.py +170 -0
- package/skills/diagram/svg.py +223 -0
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +33 -11
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +1 -1
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +1 -1
- package/skills/media_gen/manifest.yaml +93 -93
- package/skills/netops/SKILL.md +45 -0
- package/skills/netops/__init__.py +1 -0
- package/skills/netops/handler.py +418 -0
- package/skills/netops/manifest.yaml +118 -0
- package/skills/office_parser/_excel_io.py +3 -3
- package/skills/office_parser/handler.py +2 -2
- package/skills/office_parser/ppt_tools.py +1 -1
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +40 -21
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +3 -3
- package/skills/ssh/SKILL.md +81 -0
- package/skills/ssh/__init__.py +1 -0
- package/skills/ssh/handler.py +609 -0
- package/skills/ssh/manifest.yaml +182 -0
- package/tui/crannia.cmd +134 -134
- package/tui/crannia.sh +82 -0
- package/tui/crannia_tui/__init__.py +1 -1
- package/tui/crannia_tui/app.py +240 -17
- package/tui/crannia_tui/app.tcss +21 -0
- package/tui/crannia_tui/clipboard.py +78 -10
- package/tui/crannia_tui/commands.py +37 -0
- package/tui/crannia_tui/events.py +6 -0
- package/tui/crannia_tui/i18n.py +164 -164
- package/tui/crannia_tui/locales/en.json +32 -7
- package/tui/crannia_tui/paths.py +4 -1
- package/tui/crannia_tui/profile.py +178 -169
- package/tui/crannia_tui/settings.py +134 -134
- package/tui/crannia_tui/setup.py +44 -5
- package/tui/crannia_tui/ui.py +156 -16
- package/tui/crannia_tui/update.py +393 -389
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +30 -14
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/linux-x64/rg +0 -0
- package/vendor/ripgrep/package-source.json +15 -16
- package/web/__main__.py +12 -15
- package/web/server.py +8481 -8594
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""SSH 客户端工具 —— 远端执行命令 / 传文件 / 探活。
|
|
3
|
+
|
|
4
|
+
## 这条路的四道闸( / 出网权限重构 §3、§7)
|
|
5
|
+
|
|
6
|
+
1. 出网审批 —— 每次调用先过 `core/egress_gate`,subject 是
|
|
7
|
+
`ssh:user@host`(决定 2);四选项:同意本次 / 本次对话不再问 /
|
|
8
|
+
永久信任(写 `data/allowlist.json` 的 `egress` 格)/ 不同意。
|
|
9
|
+
2. 主机密钥严格 —— 默认 `RejectPolicy`:未知主机拒,用户点
|
|
10
|
+
「信任此主机并继续」才把指纹写进框架自己的
|
|
11
|
+
`data/runtime/ssh/known_hosts`(决定 4:不碰 `~/.ssh/known_hosts`);
|
|
12
|
+
密钥与记录不一致(`BadHostKeyException`)一律拒,不给"警告并继续"。
|
|
13
|
+
3. 路径 —— `ssh_upload` 的本地源过 `validate_path(..., "read")`
|
|
14
|
+
(`.env` / `data/settings.json` 读不到);`ssh_download` 的落点必须
|
|
15
|
+
在工作区(`validate_path(..., "write")`)。
|
|
16
|
+
4. 审计 —— 每次调用写一行 `EGRESS channel=ssh …`(`permission` 是
|
|
17
|
+
read 也写:出网的风险与工具权限档无关)。
|
|
18
|
+
|
|
19
|
+
## 凭据
|
|
20
|
+
|
|
21
|
+
私钥 / 口令 / 密码只在 `core/ssh_config` 读,绝不进工具参数;
|
|
22
|
+
回执只出现条目名与主机。密码认证(决定 13)优先引导公钥,但没有密码
|
|
23
|
+
认证就配不了新机器 —— 新树莓派常常只有密码。
|
|
24
|
+
|
|
25
|
+
`sudo`(决定 14):命令以 `sudo` 开头、且该条目配了 `sudo_password` 时,
|
|
26
|
+
改写成 `sudo -S` 并把密码写进远端 stdin(没有 TTY 时这是唯一的路)。
|
|
27
|
+
这是本工具的便利,不是命令解析器 —— 只认行首那一个词。
|
|
28
|
+
|
|
29
|
+
## 超时与长任务(决定 15)
|
|
30
|
+
|
|
31
|
+
超过 `timeout_s` 的命令会被中断。`apt upgrade` / 编译这类请自己用
|
|
32
|
+
`nohup ... > log 2>&1 &` 起、再用 `ssh_exec("tail -n 50 log")` 轮询;
|
|
33
|
+
P3 会把它们挂进后台作业。
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import base64
|
|
39
|
+
import hashlib
|
|
40
|
+
import time
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from typing import Any
|
|
43
|
+
|
|
44
|
+
from core import ssh_config
|
|
45
|
+
from core.i18n import t as tr, tr_fmt as trf
|
|
46
|
+
|
|
47
|
+
__all__ = ["init", "ssh_exec", "ssh_upload", "ssh_download", "ssh_probe"]
|
|
48
|
+
|
|
49
|
+
MAX_OUTPUT = 64 * 1024
|
|
50
|
+
DEFAULT_TIMEOUT = 20.0
|
|
51
|
+
|
|
52
|
+
#: 由 `bus` 在装载时注入(`init(security_guard)`)。
|
|
53
|
+
_guard = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def init(security_guard=None) -> None:
|
|
57
|
+
global _guard
|
|
58
|
+
_guard = security_guard
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _ok(tool: str, data: dict, t0: float, **extra) -> dict:
|
|
62
|
+
out = {"success": True, "tool": tool, "data": data, "error": "",
|
|
63
|
+
"duration_ms": int((time.monotonic() - t0) * 1000)}
|
|
64
|
+
out.update(extra)
|
|
65
|
+
return out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _err(tool: str, msg: str, t0: float, **extra) -> dict:
|
|
69
|
+
out = {"success": False, "tool": tool, "data": {}, "error": msg,
|
|
70
|
+
"duration_ms": int((time.monotonic() - t0) * 1000)}
|
|
71
|
+
out.update(extra)
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _audit(action: str, target: str, grant: str = "", verdict: str = "") -> None:
|
|
76
|
+
"""写一行 EGRESS 审计。失败不影响调用(只印一行)。"""
|
|
77
|
+
if _guard is None:
|
|
78
|
+
return
|
|
79
|
+
try:
|
|
80
|
+
_guard.record_egress("ssh", target, action, grant, verdict)
|
|
81
|
+
except Exception as exc: # noqa: BLE001
|
|
82
|
+
print(f"[ssh] audit write failed ({type(exc).__name__}: {exc})")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _mdns_hint(host: str) -> str:
|
|
86
|
+
"""`.local` 的解析失败在 Windows 上极常见 —— 给一句路线,不假装成功。"""
|
|
87
|
+
if str(host or "").lower().endswith(".local"):
|
|
88
|
+
return ("(`.local` 在 Windows 上常常解析不了 —— 改用 IP,"
|
|
89
|
+
"或安装 Bonjour / 用路由器的设备列表找地址。)")
|
|
90
|
+
return ""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _gate(tool_name: str, host: str, action: str, *, user: str = "",
|
|
94
|
+
key_name: str = "", timeout_hint: str = ""):
|
|
95
|
+
"""出网审批。放行返回 `None`;要问返回载荷,调用方直接返回它。
|
|
96
|
+
|
|
97
|
+
subject 由 `core.egress_gate.subject_from_args` 算 —— 与自动/完全权限
|
|
98
|
+
预授权那一条同一个函数(写入与匹配同形)。
|
|
99
|
+
"""
|
|
100
|
+
from core.egress_gate import subject_from_args, gate_for
|
|
101
|
+
|
|
102
|
+
args = {"host": host, "user": user, "key_name": key_name}
|
|
103
|
+
subj = subject_from_args(tool_name, args)
|
|
104
|
+
if not subj:
|
|
105
|
+
return None # 空目标在下面由参数校验挡掉
|
|
106
|
+
# 键是模板(`{host}` 这类)—— 先翻再填,英文译文才能改语序。
|
|
107
|
+
body = trf("Crannia 想通过 SSH 连接到 **{host}**({action})。\n"
|
|
108
|
+
"目标:`{target}`", host, tr(action), subj)
|
|
109
|
+
if timeout_hint:
|
|
110
|
+
body += "\n" + timeout_hint
|
|
111
|
+
return gate_for(subj, tool_name=tool_name, body=body)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _hostkey_pending(tool_name: str, subject: str, host: str, port: int,
|
|
115
|
+
key) -> dict:
|
|
116
|
+
"""未知主机的信任载荷(`kind=ssh_hostkey`)。"""
|
|
117
|
+
from core.approval import pending_payload
|
|
118
|
+
|
|
119
|
+
line = "%s %s %s" % (host, key.get_name(), key.get_base64())
|
|
120
|
+
fp = "SHA256:" + base64.b64encode(
|
|
121
|
+
hashlib.sha256(key.asbytes()).digest()).decode("ascii").rstrip("=")
|
|
122
|
+
body = trf("Crannia 第一次连接 **{host}**。\n"
|
|
123
|
+
"主机密钥:{keytype}\n指纹:{fp}\n"
|
|
124
|
+
"核对指纹确实是你要连的那台机器,再选择信任。",
|
|
125
|
+
host, key.get_name(), fp)
|
|
126
|
+
return pending_payload(
|
|
127
|
+
"ssh_hostkey",
|
|
128
|
+
body=body,
|
|
129
|
+
footer=True,
|
|
130
|
+
subject=subject,
|
|
131
|
+
detail="%s %s" % (host, fp),
|
|
132
|
+
host=host,
|
|
133
|
+
port=int(port),
|
|
134
|
+
host_key_line=line,
|
|
135
|
+
fingerprint=fp,
|
|
136
|
+
tool=tool_name,
|
|
137
|
+
status="pending_ssh_hostkey_approval",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _fetch_host_key(host: str, port: int, timeout: float):
|
|
142
|
+
"""连一次取主机公钥(不认证)。取不到返回 `(None, 原因)`。"""
|
|
143
|
+
import paramiko
|
|
144
|
+
t = None
|
|
145
|
+
try:
|
|
146
|
+
t = paramiko.Transport((host, int(port)))
|
|
147
|
+
t.start_client(timeout=float(timeout))
|
|
148
|
+
return t.get_remote_server_key(), ""
|
|
149
|
+
except Exception as exc: # noqa: BLE001
|
|
150
|
+
return None, "%s: %s" % (type(exc).__name__, exc)
|
|
151
|
+
finally:
|
|
152
|
+
if t is not None:
|
|
153
|
+
try:
|
|
154
|
+
t.close()
|
|
155
|
+
except Exception: # noqa: BLE001
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _connect(host: str, port: int, user: str, key_name: str, timeout: float,
|
|
160
|
+
tool_name: str):
|
|
161
|
+
"""建连接。返回 `(client, error_msg, pending_payload)`。
|
|
162
|
+
|
|
163
|
+
`pending_payload` 非 `None` 表示"要先问用户"(未知主机密钥)——
|
|
164
|
+
调用方原样把它当回执返回(`agent_loop` 认 `pending_` 前缀)。
|
|
165
|
+
"""
|
|
166
|
+
try:
|
|
167
|
+
import paramiko # noqa: F401
|
|
168
|
+
except ImportError:
|
|
169
|
+
return None, ("缺少 paramiko(LGPL-2.1)。请 `pip install paramiko`,"
|
|
170
|
+
"或在设置页 → 技能 → SSH 里查看配置。"), None
|
|
171
|
+
|
|
172
|
+
entry = ssh_config.resolve_entry(str(key_name or ""))
|
|
173
|
+
u = str(user or entry.get("user") or "").strip()
|
|
174
|
+
key = str(entry.get("key_path") or "").strip()
|
|
175
|
+
ph = str(entry.get("passphrase") or "").strip()
|
|
176
|
+
pw = str(entry.get("password") or "").strip()
|
|
177
|
+
if not key and not pw:
|
|
178
|
+
return None, ("没配 SSH 凭据。去设置页 → 技能 → SSH 填私钥路径或密码"
|
|
179
|
+
"(不要放在工具参数里)。"), None
|
|
180
|
+
if key:
|
|
181
|
+
p = Path(key).expanduser()
|
|
182
|
+
if not p.is_file():
|
|
183
|
+
return None, "私钥文件不存在:%s(条目 %s)" % (p.name, entry.get("name")), None
|
|
184
|
+
|
|
185
|
+
import paramiko
|
|
186
|
+
subj = _subject_of(u, host)
|
|
187
|
+
cli = paramiko.SSHClient()
|
|
188
|
+
# 读两份:用户自己的(他手动连过的直接能用)+ 框架自己的(信任审批写的)。
|
|
189
|
+
try:
|
|
190
|
+
cli.load_system_host_keys()
|
|
191
|
+
except Exception as exc: # noqa: BLE001
|
|
192
|
+
print(f"[ssh] failed to read system known_hosts (treated as empty): {type(exc).__name__}: {exc}")
|
|
193
|
+
try:
|
|
194
|
+
kh = ssh_config.known_hosts_path()
|
|
195
|
+
if kh.exists():
|
|
196
|
+
cli.load_host_keys(str(kh))
|
|
197
|
+
except Exception as exc: # noqa: BLE001
|
|
198
|
+
print(f"[ssh] failed to read framework known_hosts (treated as empty): {type(exc).__name__}: {exc}")
|
|
199
|
+
# 严格:未知主机一律拒(不给"警告并继续")。
|
|
200
|
+
cli.set_missing_host_key_policy(paramiko.RejectPolicy())
|
|
201
|
+
|
|
202
|
+
kwargs: dict[str, Any] = {
|
|
203
|
+
"hostname": host, "port": int(port),
|
|
204
|
+
"username": u or None, "timeout": float(timeout),
|
|
205
|
+
"allow_agent": False, "look_for_keys": False,
|
|
206
|
+
}
|
|
207
|
+
if pw and not key:
|
|
208
|
+
kwargs["password"] = pw
|
|
209
|
+
else:
|
|
210
|
+
kwargs["key_filename"] = str(Path(key).expanduser())
|
|
211
|
+
kwargs["passphrase"] = ph or None
|
|
212
|
+
|
|
213
|
+
try:
|
|
214
|
+
cli.connect(**kwargs)
|
|
215
|
+
return cli, "", None
|
|
216
|
+
except paramiko.BadHostKeyException:
|
|
217
|
+
try:
|
|
218
|
+
cli.close()
|
|
219
|
+
except Exception: # noqa: BLE001
|
|
220
|
+
pass
|
|
221
|
+
return None, (
|
|
222
|
+
"主机密钥与已记录的不一致:%s。这可能是中间人攻击,也可能是"
|
|
223
|
+
"机器重装过。请先在终端里确认指纹;确认无误后,把 "
|
|
224
|
+
"data/runtime/ssh/known_hosts 里那一行删掉再重试。"
|
|
225
|
+
% host), None
|
|
226
|
+
except paramiko.SSHException as exc:
|
|
227
|
+
try:
|
|
228
|
+
cli.close()
|
|
229
|
+
except Exception: # noqa: BLE001
|
|
230
|
+
pass
|
|
231
|
+
if "not found in known_hosts" not in str(exc):
|
|
232
|
+
return None, "%s: %s" % (type(exc).__name__, exc), None
|
|
233
|
+
# 未知主机 —— 取指纹,问用户。取不到就给路线(不回退到不校验)。
|
|
234
|
+
hk, why = _fetch_host_key(host, int(port), float(timeout))
|
|
235
|
+
if hk is None:
|
|
236
|
+
return None, ("未知主机 %s,且取不到它的主机密钥(%s)。"
|
|
237
|
+
"可以先用终端 ssh 连一次,把指纹记下来。" % (host, why)), None
|
|
238
|
+
return None, "", _hostkey_pending(tool_name, subj, host, int(port), hk)
|
|
239
|
+
except Exception as exc: # noqa: BLE001
|
|
240
|
+
try:
|
|
241
|
+
cli.close()
|
|
242
|
+
except Exception: # noqa: BLE001
|
|
243
|
+
pass
|
|
244
|
+
msg = "%s: %s" % (type(exc).__name__, exc)
|
|
245
|
+
return None, msg + _mdns_hint(host), None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _subject_of(user: str, host: str) -> str:
|
|
249
|
+
from core.egress_gate import ssh_subject
|
|
250
|
+
return ssh_subject(user, host)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# 工具
|
|
254
|
+
|
|
255
|
+
def ssh_exec(host: str, command: str, port: int = 22, user: str = "",
|
|
256
|
+
key_name: str = "", timeout_s: float = DEFAULT_TIMEOUT) -> dict:
|
|
257
|
+
"""在远端执行一条命令,回 stdout/stderr/exit_code(输出有上限)。"""
|
|
258
|
+
t0 = time.monotonic()
|
|
259
|
+
target = str(host or "").strip()
|
|
260
|
+
cmd = str(command or "").strip()
|
|
261
|
+
if not target or not cmd:
|
|
262
|
+
return _err("ssh_exec", "host 与 command 都不能为空", t0)
|
|
263
|
+
|
|
264
|
+
gate = _gate("ssh_exec", target, "执行命令", user=str(user),
|
|
265
|
+
key_name=str(key_name))
|
|
266
|
+
if gate is not None:
|
|
267
|
+
_audit("exec", target, "", "asked")
|
|
268
|
+
return gate
|
|
269
|
+
|
|
270
|
+
cli, why, pend = _connect(target, int(port), str(user), str(key_name),
|
|
271
|
+
float(timeout_s), "ssh_exec")
|
|
272
|
+
if pend is not None:
|
|
273
|
+
_audit("exec", target, "", "asked")
|
|
274
|
+
return pend
|
|
275
|
+
if cli is None:
|
|
276
|
+
_audit("exec", target, "granted", "error")
|
|
277
|
+
return _err("ssh_exec", why, t0)
|
|
278
|
+
|
|
279
|
+
entry = ssh_config.resolve_entry(str(key_name or ""))
|
|
280
|
+
sudo_pw = str(entry.get("sudo_password") or "").strip()
|
|
281
|
+
use_sudo_stdin = bool(sudo_pw) and cmd.startswith("sudo ")
|
|
282
|
+
try:
|
|
283
|
+
if use_sudo_stdin:
|
|
284
|
+
# 没有 TTY 时 `sudo` 读 stdin —— `-S` 让它从管道读密码,
|
|
285
|
+
# `-p ''` 免得提示语混进 stderr。
|
|
286
|
+
cmd = "sudo -S -p '' " + cmd[len("sudo "):]
|
|
287
|
+
stdin, stdout, stderr = cli.exec_command(cmd, timeout=float(timeout_s))
|
|
288
|
+
if use_sudo_stdin:
|
|
289
|
+
try:
|
|
290
|
+
stdin.write(sudo_pw + "\n")
|
|
291
|
+
stdin.flush()
|
|
292
|
+
except Exception: # noqa: BLE001
|
|
293
|
+
pass
|
|
294
|
+
out_b = stdout.read(MAX_OUTPUT)
|
|
295
|
+
err_b = stderr.read(MAX_OUTPUT)
|
|
296
|
+
code = stdout.channel.recv_exit_status()
|
|
297
|
+
data = {"host": target, "command": cmd,
|
|
298
|
+
"stdout": out_b.decode("utf-8", "replace"),
|
|
299
|
+
"stderr": err_b.decode("utf-8", "replace"),
|
|
300
|
+
"exit_code": code}
|
|
301
|
+
_audit("exec", target, "granted", "ok")
|
|
302
|
+
return _ok("ssh_exec", data, t0,
|
|
303
|
+
truncated=len(out_b) >= MAX_OUTPUT or len(err_b) >= MAX_OUTPUT)
|
|
304
|
+
except Exception as exc: # noqa: BLE001
|
|
305
|
+
_audit("exec", target, "granted", "error")
|
|
306
|
+
msg = "%s: %s" % (type(exc).__name__, exc)
|
|
307
|
+
if "timed out" in msg.lower() or "timeout" in msg.lower():
|
|
308
|
+
msg += ("。长任务请用 `nohup <命令> > /tmp/x.log 2>&1 &` 起,"
|
|
309
|
+
"再用 ssh_exec(\"tail -n 50 /tmp/x.log\") 轮询。")
|
|
310
|
+
return _err("ssh_exec", msg, t0)
|
|
311
|
+
finally:
|
|
312
|
+
try:
|
|
313
|
+
cli.close()
|
|
314
|
+
except Exception: # noqa: BLE001
|
|
315
|
+
pass
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def ssh_upload(host: str, local_path: str, remote_path: str,
|
|
319
|
+
port: int = 22, user: str = "", key_name: str = "",
|
|
320
|
+
timeout_s: float = DEFAULT_TIMEOUT) -> dict:
|
|
321
|
+
"""本地文件 → 远端(SFTP),远端目录不会自动创建。"""
|
|
322
|
+
t0 = time.monotonic()
|
|
323
|
+
src = Path(str(local_path or ""))
|
|
324
|
+
if not src.is_file():
|
|
325
|
+
return _err("ssh_upload", "本地文件不存在:%s" % src.name, t0)
|
|
326
|
+
# 本地源过路径三级分类:`.env` 一族读不到(FORBIDDEN),
|
|
327
|
+
# 用户划的规避目录也不行 —— 这是"读本地文件外发"的那道闸。
|
|
328
|
+
try:
|
|
329
|
+
if _guard is not None:
|
|
330
|
+
_guard.validate_path(str(src), "read")
|
|
331
|
+
except Exception as exc: # noqa: BLE001
|
|
332
|
+
_audit("upload", str(host or ""), "", "error")
|
|
333
|
+
return _err("ssh_upload", "不能上传这个文件:%s" % exc, t0)
|
|
334
|
+
|
|
335
|
+
gate = _gate("ssh_upload", str(host or ""), "上传文件",
|
|
336
|
+
user=str(user), key_name=str(key_name))
|
|
337
|
+
if gate is not None:
|
|
338
|
+
_audit("upload", str(host or ""), "", "asked")
|
|
339
|
+
return gate
|
|
340
|
+
|
|
341
|
+
cli, why, pend = _connect(str(host or ""), int(port), str(user),
|
|
342
|
+
str(key_name), float(timeout_s), "ssh_upload")
|
|
343
|
+
if pend is not None:
|
|
344
|
+
_audit("upload", str(host or ""), "", "asked")
|
|
345
|
+
return pend
|
|
346
|
+
if cli is None:
|
|
347
|
+
_audit("upload", str(host or ""), "granted", "error")
|
|
348
|
+
return _err("ssh_upload", why, t0)
|
|
349
|
+
try:
|
|
350
|
+
with cli.open_sftp() as sftp:
|
|
351
|
+
sftp.put(str(src), str(remote_path or ""))
|
|
352
|
+
_audit("upload", str(host or ""), "granted", "ok")
|
|
353
|
+
return _ok("ssh_upload", {"host": host, "local": src.name,
|
|
354
|
+
"remote": remote_path,
|
|
355
|
+
"bytes": src.stat().st_size}, t0)
|
|
356
|
+
except Exception as exc: # noqa: BLE001
|
|
357
|
+
_audit("upload", str(host or ""), "granted", "error")
|
|
358
|
+
return _err("ssh_upload", "%s: %s" % (type(exc).__name__, exc), t0)
|
|
359
|
+
finally:
|
|
360
|
+
try:
|
|
361
|
+
cli.close()
|
|
362
|
+
except Exception: # noqa: BLE001
|
|
363
|
+
pass
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def ssh_download(host: str, remote_path: str, local_path: str,
|
|
367
|
+
port: int = 22, user: str = "", key_name: str = "",
|
|
368
|
+
timeout_s: float = DEFAULT_TIMEOUT) -> dict:
|
|
369
|
+
"""远端文件 → 本地(SFTP)。落点必须在工作区。"""
|
|
370
|
+
t0 = time.monotonic()
|
|
371
|
+
dst = Path(str(local_path or ""))
|
|
372
|
+
if not str(dst):
|
|
373
|
+
return _err("ssh_download", "local_path 不能为空", t0)
|
|
374
|
+
# 相对路径落在本段对话的默认输出目录(`primary_output_dir`),
|
|
375
|
+
# 然后把最终路径过一遍写权限 —— 区外写有它自己的一道审批。
|
|
376
|
+
try:
|
|
377
|
+
from core.workspace import primary_output_dir
|
|
378
|
+
if not dst.is_absolute():
|
|
379
|
+
dst = Path(primary_output_dir()) / dst
|
|
380
|
+
if _guard is not None:
|
|
381
|
+
_guard.validate_path(str(dst), "write")
|
|
382
|
+
except Exception as exc: # noqa: BLE001
|
|
383
|
+
_audit("download", str(host or ""), "", "error")
|
|
384
|
+
return _err("ssh_download", "不能写到这个位置:%s" % exc, t0)
|
|
385
|
+
|
|
386
|
+
gate = _gate("ssh_download", str(host or ""), "下载文件",
|
|
387
|
+
user=str(user), key_name=str(key_name))
|
|
388
|
+
if gate is not None:
|
|
389
|
+
_audit("download", str(host or ""), "", "asked")
|
|
390
|
+
return gate
|
|
391
|
+
|
|
392
|
+
cli, why, pend = _connect(str(host or ""), int(port), str(user),
|
|
393
|
+
str(key_name), float(timeout_s), "ssh_download")
|
|
394
|
+
if pend is not None:
|
|
395
|
+
_audit("download", str(host or ""), "", "asked")
|
|
396
|
+
return pend
|
|
397
|
+
if cli is None:
|
|
398
|
+
_audit("download", str(host or ""), "granted", "error")
|
|
399
|
+
return _err("ssh_download", why, t0)
|
|
400
|
+
try:
|
|
401
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
402
|
+
with cli.open_sftp() as sftp:
|
|
403
|
+
sftp.get(str(remote_path), str(dst))
|
|
404
|
+
_audit("download", str(host or ""), "granted", "ok")
|
|
405
|
+
return _ok("ssh_download", {"host": host, "remote": remote_path,
|
|
406
|
+
"local": str(dst),
|
|
407
|
+
"bytes": dst.stat().st_size}, t0)
|
|
408
|
+
except Exception as exc: # noqa: BLE001
|
|
409
|
+
_audit("download", str(host or ""), "granted", "error")
|
|
410
|
+
return _err("ssh_download", "%s: %s" % (type(exc).__name__, exc), t0)
|
|
411
|
+
finally:
|
|
412
|
+
try:
|
|
413
|
+
cli.close()
|
|
414
|
+
except Exception: # noqa: BLE001
|
|
415
|
+
pass
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def ssh_probe(host: str, port: int = 22, timeout_s: float = 5.0) -> dict:
|
|
419
|
+
"""探活:TCP 可达 + SSH banner。不需要凭据(只建 socket)。"""
|
|
420
|
+
t0 = time.monotonic()
|
|
421
|
+
target = str(host or "").strip()
|
|
422
|
+
if not target:
|
|
423
|
+
return _err("ssh_probe", "host 不能为空", t0)
|
|
424
|
+
gate = _gate("ssh_probe", target, "探活")
|
|
425
|
+
if gate is not None:
|
|
426
|
+
_audit("probe", target, "", "asked")
|
|
427
|
+
return gate
|
|
428
|
+
import socket
|
|
429
|
+
try:
|
|
430
|
+
with socket.create_connection((target, int(port)), timeout=float(timeout_s)) as s:
|
|
431
|
+
s.settimeout(float(timeout_s))
|
|
432
|
+
banner = ""
|
|
433
|
+
try:
|
|
434
|
+
banner = s.recv(256).decode("utf-8", "replace").strip()
|
|
435
|
+
except OSError:
|
|
436
|
+
pass
|
|
437
|
+
_audit("probe", target, "granted", "ok")
|
|
438
|
+
return _ok("ssh_probe", {"host": target, "port": int(port),
|
|
439
|
+
"reachable": True, "banner": banner[:200]}, t0)
|
|
440
|
+
except Exception as exc: # noqa: BLE001
|
|
441
|
+
_audit("probe", target, "granted", "error")
|
|
442
|
+
return _ok("ssh_probe", {"host": target, "port": int(port),
|
|
443
|
+
"reachable": False,
|
|
444
|
+
"reason": "%s: %s%s" % (type(exc).__name__, exc,
|
|
445
|
+
_mdns_hint(target))}, t0)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _bridge(sock_a, sock_b) -> None:
|
|
449
|
+
"""在两个 socket-like 之间双向搬字节(任一方向结束就半关)。"""
|
|
450
|
+
import socket as _socket
|
|
451
|
+
import threading as _threading
|
|
452
|
+
|
|
453
|
+
def one_way(src, dst) -> None:
|
|
454
|
+
try:
|
|
455
|
+
while True:
|
|
456
|
+
data = src.recv(16384)
|
|
457
|
+
if not data:
|
|
458
|
+
break
|
|
459
|
+
if hasattr(dst, "sendall"):
|
|
460
|
+
dst.sendall(data)
|
|
461
|
+
else:
|
|
462
|
+
dst.send(data)
|
|
463
|
+
except Exception: # noqa: BLE001
|
|
464
|
+
pass
|
|
465
|
+
finally:
|
|
466
|
+
try:
|
|
467
|
+
if hasattr(dst, "shutdown_write"):
|
|
468
|
+
dst.shutdown_write()
|
|
469
|
+
else:
|
|
470
|
+
dst.shutdown(_socket.SHUT_WR)
|
|
471
|
+
except Exception: # noqa: BLE001
|
|
472
|
+
pass
|
|
473
|
+
|
|
474
|
+
t = _threading.Thread(target=one_way, args=(sock_b, sock_a), daemon=True)
|
|
475
|
+
t.start()
|
|
476
|
+
one_way(sock_a, sock_b)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def ssh_forward(host: str, remote_host: str, remote_port: int,
|
|
480
|
+
local_port: int = 0, port: int = 22, user: str = "",
|
|
481
|
+
key_name: str = "", timeout_s: float = 20.0) -> dict:
|
|
482
|
+
"""本地端口转发:127.0.0.1:local_port → remote_host:remote_port(经 SSH)。
|
|
483
|
+
|
|
484
|
+
工具本身立刻返回,隧道跑在统一任务表里(`task` 工具可查、可取消;
|
|
485
|
+
`/clear` 会停掉它)。寿限跟作业表一致(30 分钟),到点自动收。
|
|
486
|
+
这是 nc / socat 的 relay 那一路的正规替身。
|
|
487
|
+
"""
|
|
488
|
+
t0 = time.monotonic()
|
|
489
|
+
target = str(host or "").strip()
|
|
490
|
+
rh = str(remote_host or "").strip()
|
|
491
|
+
if not target or not rh:
|
|
492
|
+
return _err("ssh_forward", "host 与 remote_host 都不能为空", t0)
|
|
493
|
+
try:
|
|
494
|
+
rport = int(remote_port)
|
|
495
|
+
lport = int(local_port or 0)
|
|
496
|
+
except (TypeError, ValueError):
|
|
497
|
+
return _err("ssh_forward", "端口必须是整数", t0)
|
|
498
|
+
if not (1 <= rport <= 65535) or not (0 <= lport <= 65535):
|
|
499
|
+
return _err("ssh_forward", "端口超出范围", t0)
|
|
500
|
+
|
|
501
|
+
gate = _gate("ssh_forward", target, "建立隧道", user=str(user),
|
|
502
|
+
key_name=str(key_name))
|
|
503
|
+
if gate is not None:
|
|
504
|
+
_audit("forward", target, "", "asked")
|
|
505
|
+
return gate
|
|
506
|
+
|
|
507
|
+
cli, why, pend = _connect(target, int(port), str(user), str(key_name),
|
|
508
|
+
float(timeout_s), "ssh_forward")
|
|
509
|
+
if pend is not None:
|
|
510
|
+
_audit("forward", target, "", "asked")
|
|
511
|
+
return pend
|
|
512
|
+
if cli is None:
|
|
513
|
+
_audit("forward", target, "granted", "error")
|
|
514
|
+
return _err("ssh_forward", why, t0)
|
|
515
|
+
transport = cli.get_transport()
|
|
516
|
+
if transport is None or not transport.is_active():
|
|
517
|
+
try:
|
|
518
|
+
cli.close()
|
|
519
|
+
except Exception: # noqa: BLE001
|
|
520
|
+
pass
|
|
521
|
+
return _err("ssh_forward", "SSH 传输层没起来(连接立刻断了)", t0)
|
|
522
|
+
|
|
523
|
+
import socket as _socket
|
|
524
|
+
listener = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
|
|
525
|
+
try:
|
|
526
|
+
listener.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
|
|
527
|
+
listener.bind(("127.0.0.1", lport))
|
|
528
|
+
listener.listen(16)
|
|
529
|
+
listener.settimeout(0.5)
|
|
530
|
+
except Exception as exc: # noqa: BLE001
|
|
531
|
+
try:
|
|
532
|
+
listener.close()
|
|
533
|
+
cli.close()
|
|
534
|
+
except Exception: # noqa: BLE001
|
|
535
|
+
pass
|
|
536
|
+
_audit("forward", target, "granted", "error")
|
|
537
|
+
return _err("ssh_forward", "本地端口用不了:%s(换一个 local_port)" % exc, t0)
|
|
538
|
+
|
|
539
|
+
actual = listener.getsockname()[1]
|
|
540
|
+
# 任务列表里显示的就是这一句 —— 先翻模板再填值(同审批正文那两条)。
|
|
541
|
+
label = trf("ssh 隧道 127.0.0.1:{local} -> {remote}:{rport}(经 {host})",
|
|
542
|
+
actual, rh, rport, target)
|
|
543
|
+
|
|
544
|
+
from core import jobs as _jobs
|
|
545
|
+
try:
|
|
546
|
+
from core.request_snapshot import current_session_id
|
|
547
|
+
sid = str(current_session_id() or "")
|
|
548
|
+
except Exception: # noqa: BLE001
|
|
549
|
+
sid = ""
|
|
550
|
+
|
|
551
|
+
def _run(job) -> str:
|
|
552
|
+
deadline = time.monotonic() + (_jobs.JOB_MAX_LIFETIME_MS / 1000.0)
|
|
553
|
+
job.out.write(("%s 已开始\n" % label).encode("utf-8"))
|
|
554
|
+
try:
|
|
555
|
+
while not job.cancel_event.is_set() and time.monotonic() < deadline:
|
|
556
|
+
try:
|
|
557
|
+
conn, peer = listener.accept()
|
|
558
|
+
except _socket.timeout:
|
|
559
|
+
continue
|
|
560
|
+
except OSError:
|
|
561
|
+
break
|
|
562
|
+
try:
|
|
563
|
+
chan = transport.open_channel(
|
|
564
|
+
"direct-tcpip", (rh, rport), peer, timeout=float(timeout_s))
|
|
565
|
+
except Exception as exc: # noqa: BLE001
|
|
566
|
+
job.out.write(("打开通道失败:%s: %s\n"
|
|
567
|
+
% (type(exc).__name__, exc)).encode("utf-8"))
|
|
568
|
+
conn.close()
|
|
569
|
+
continue
|
|
570
|
+
import threading as _threading
|
|
571
|
+
_threading.Thread(target=_bridge, args=(conn, chan),
|
|
572
|
+
daemon=True).start()
|
|
573
|
+
job.out.write(("连接:%s\n" % (peer,)).encode("utf-8"))
|
|
574
|
+
finally:
|
|
575
|
+
try:
|
|
576
|
+
listener.close()
|
|
577
|
+
except Exception: # noqa: BLE001
|
|
578
|
+
pass
|
|
579
|
+
try:
|
|
580
|
+
transport.close()
|
|
581
|
+
cli.close()
|
|
582
|
+
except Exception: # noqa: BLE001
|
|
583
|
+
pass
|
|
584
|
+
if job.cancel_event.is_set():
|
|
585
|
+
return "隧道已停止(取消)。"
|
|
586
|
+
return "隧道到寿限(30 分钟)自动停止;要续,重新调用。"
|
|
587
|
+
|
|
588
|
+
try:
|
|
589
|
+
job = _jobs.start_thread(_run, kind=_jobs.KIND_SKILL, command=label,
|
|
590
|
+
session_key=sid, storage_id=sid,
|
|
591
|
+
description=label, notify=False)
|
|
592
|
+
except Exception as exc: # noqa: BLE001
|
|
593
|
+
try:
|
|
594
|
+
listener.close()
|
|
595
|
+
cli.close()
|
|
596
|
+
except Exception: # noqa: BLE001
|
|
597
|
+
pass
|
|
598
|
+
return _err("ssh_forward", "起不了后台任务:%s: %s"
|
|
599
|
+
% (type(exc).__name__, exc), t0)
|
|
600
|
+
|
|
601
|
+
_audit("forward", target, "granted", "ok")
|
|
602
|
+
return _ok("ssh_forward", {
|
|
603
|
+
"host": target,
|
|
604
|
+
"local": "127.0.0.1:%d" % actual,
|
|
605
|
+
"remote": "%s:%d" % (rh, rport),
|
|
606
|
+
"task_id": job.id,
|
|
607
|
+
"note": ("隧道在后台跑(30 分钟寿限)。用 task 工具查/停它;"
|
|
608
|
+
"把 local 地址给需要连它的程序即可。"),
|
|
609
|
+
}, t0, truncated=False)
|