compshare-cli 0.5.0__tar.gz → 0.5.1__tar.gz

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.
Files changed (71) hide show
  1. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/CHANGELOG.md +13 -0
  2. {compshare_cli-0.5.0/src/compshare_cli.egg-info → compshare_cli-0.5.1}/PKG-INFO +14 -1
  3. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/README.md +13 -0
  4. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/connector/compshare/connector-meta.json +1 -1
  5. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/connector/compshare/mcp.json +1 -1
  6. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/connector/compshare/skills/compshare/SKILL.md +1 -1
  7. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/__init__.py +1 -1
  8. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/instance.py +41 -34
  9. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/i18n.py +4 -2
  10. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/ssh.py +101 -31
  11. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/ssh_cache.py +9 -5
  12. {compshare_cli-0.5.0 → compshare_cli-0.5.1/src/compshare_cli.egg-info}/PKG-INFO +14 -1
  13. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli.egg-info/SOURCES.txt +1 -0
  14. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_cli.py +194 -14
  15. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_ssh.py +162 -2
  16. compshare_cli-0.5.1/tests/test_ssh_cache.py +118 -0
  17. compshare_cli-0.5.1/tests/test_ssh_integration.py +217 -0
  18. compshare_cli-0.5.0/tests/test_ssh_cache.py +0 -47
  19. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/LICENSE +0 -0
  20. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/MANIFEST.in +0 -0
  21. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/RELEASING.md +0 -0
  22. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/connector/compshare/icon.svg +0 -0
  23. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/connector/compshare/token-schema.json +0 -0
  24. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/pyproject.toml +0 -0
  25. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/setup.cfg +0 -0
  26. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/skills/compshare-cli/SKILL.md +0 -0
  27. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/skills/compshare-cli/agents/openai.yaml +0 -0
  28. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/__main__.py +0 -0
  29. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/actions.py +0 -0
  30. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/api.py +0 -0
  31. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/cli.py +0 -0
  32. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/__init__.py +0 -0
  33. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/bandwidth.py +0 -0
  34. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/common.py +0 -0
  35. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/doctor.py +0 -0
  36. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/feedback.py +0 -0
  37. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/image.py +0 -0
  38. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/minimax.py +0 -0
  39. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/storage.py +0 -0
  40. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/commands/team.py +0 -0
  41. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/config.py +0 -0
  42. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/errors.py +0 -0
  43. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/insights.py +0 -0
  44. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/instance_templates.py +0 -0
  45. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/location.py +0 -0
  46. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/mcp_server.py +0 -0
  47. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/output.py +0 -0
  48. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/parsing.py +0 -0
  49. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/remote_jobs.py +0 -0
  50. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/runtime.py +0 -0
  51. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli/sdk.py +0 -0
  52. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli.egg-info/dependency_links.txt +0 -0
  53. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli.egg-info/entry_points.txt +0 -0
  54. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli.egg-info/requires.txt +0 -0
  55. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/src/compshare_cli.egg-info/top_level.txt +0 -0
  56. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_actions.py +0 -0
  57. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_api.py +0 -0
  58. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_bandwidth.py +0 -0
  59. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_config.py +0 -0
  60. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_feedback.py +0 -0
  61. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_instance_templates.py +0 -0
  62. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_location.py +0 -0
  63. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_mcp_server.py +0 -0
  64. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_minimax.py +0 -0
  65. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_minimax_media.py +0 -0
  66. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_output.py +0 -0
  67. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_parsing.py +0 -0
  68. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_release_version.py +0 -0
  69. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_remote_jobs.py +0 -0
  70. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_sdk.py +0 -0
  71. {compshare_cli-0.5.0 → compshare_cli-0.5.1}/tests/test_workbuddy_connector.py +0 -0
@@ -2,6 +2,19 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.5.1
6
+
7
+ - 修复 SSH 远程命令参数中的空格、空参数、引号和 Shell 特殊字符丢失的问题,
8
+ 并使 `--print` 输出的命令与实际执行一致;Shell 脚本使用 `-- sh -lc '脚本'`。
9
+ - 文件传输共用 SSH 连接缓存,支持 `--refresh`、`--no-cache`、`--cache-ttl` 和
10
+ `--connect-timeout`;交互式 SSH 也应用连接超时,连接或认证失败后清除失效缓存。
11
+ - 修复 SCP 的 IPv6、SSH URI 和 `-l` 用户名覆盖处理,区分文件传输错误、远程命令错误
12
+ 与连接或认证错误,避免把远程程序的 `Permission denied` 误判为认证失败。
13
+ - 非交互密钥认证不再请求密码,密码自动填写兼容 `BatchMode` 配置;缺失 SSH 程序或
14
+ askpass 助手时返回可读错误,JSON 输出能处理非 UTF-8 远程输出。
15
+ - 忽略损坏、结构无效或时间戳异常的 SSH 缓存,保持凭证文件权限且不修改已有父目录权限。
16
+ - 新增真实 OpenSSH 回归测试,覆盖参数、脚本、双向文件传输、主机密钥校验与远程任务。
17
+
5
18
  ## 0.5.0
6
19
 
7
20
  - 对齐 MiniMax H3 视频 API:支持 480P、4K、最长 30 秒、Skill、静音、水印和模型筛选,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: compshare-cli
3
- Version: 0.5.0
3
+ Version: 0.5.1
4
4
  Summary: Command-line client for CompShare GPU compute and MiniMax H3
5
5
  Author: CompShare
6
6
  License-Expression: Apache-2.0
@@ -82,6 +82,13 @@ compshare instance list --all
82
82
 
83
83
  # 连接实例
84
84
  compshare instance ssh INSTANCE_ID
85
+ compshare --json instance ssh INSTANCE_ID -- nvidia-smi
86
+ compshare --json instance ssh INSTANCE_ID -- sh -lc 'cd /workspace && pwd'
87
+
88
+ # 上传、下载文件或目录
89
+ compshare --json instance cp INSTANCE_ID ./model.bin :/workspace/model.bin
90
+ compshare --json instance cp INSTANCE_ID ./dataset :/workspace/dataset
91
+ compshare --json instance cp INSTANCE_ID :/workspace/results ./results
85
92
 
86
93
  # MiniMax H3:先预演,再创建
87
94
  compshare --json minimax create '一只猫在海边奔跑' --dry-run
@@ -105,6 +112,12 @@ compshare -h
105
112
  compshare instance -h
106
113
  ```
107
114
 
115
+ SSH 远程命令放在 `--` 后面,参数中的空格、引号和 `$` 会按原样传递;需要管道、重定向
116
+ 或 `&&` 时使用 `sh -lc '脚本'`。SSH 和文件传输共用一小时有效的连接缓存,重置密码或
117
+ 重装后可用 `--refresh` 强制刷新,`--no-cache` 禁用缓存。`--connect-timeout` 设置连接
118
+ 建立的最长时间(默认 30 秒),`ssh --timeout` 设置等待实例运行的时间;长任务使用
119
+ `instance job`。
120
+
108
121
  ## 命令概览
109
122
 
110
123
  ```text
@@ -55,6 +55,13 @@ compshare instance list --all
55
55
 
56
56
  # 连接实例
57
57
  compshare instance ssh INSTANCE_ID
58
+ compshare --json instance ssh INSTANCE_ID -- nvidia-smi
59
+ compshare --json instance ssh INSTANCE_ID -- sh -lc 'cd /workspace && pwd'
60
+
61
+ # 上传、下载文件或目录
62
+ compshare --json instance cp INSTANCE_ID ./model.bin :/workspace/model.bin
63
+ compshare --json instance cp INSTANCE_ID ./dataset :/workspace/dataset
64
+ compshare --json instance cp INSTANCE_ID :/workspace/results ./results
58
65
 
59
66
  # MiniMax H3:先预演,再创建
60
67
  compshare --json minimax create '一只猫在海边奔跑' --dry-run
@@ -78,6 +85,12 @@ compshare -h
78
85
  compshare instance -h
79
86
  ```
80
87
 
88
+ SSH 远程命令放在 `--` 后面,参数中的空格、引号和 `$` 会按原样传递;需要管道、重定向
89
+ 或 `&&` 时使用 `sh -lc '脚本'`。SSH 和文件传输共用一小时有效的连接缓存,重置密码或
90
+ 重装后可用 `--refresh` 强制刷新,`--no-cache` 禁用缓存。`--connect-timeout` 设置连接
91
+ 建立的最长时间(默认 30 秒),`ssh --timeout` 设置等待实例运行的时间;长任务使用
92
+ `instance job`。
93
+
81
94
  ## 命令概览
82
95
 
83
96
  ```text
@@ -8,7 +8,7 @@
8
8
  "source": "compshare",
9
9
  "type": "mcp",
10
10
  "auth_mode": "token",
11
- "version": "0.5.0",
11
+ "version": "0.5.1",
12
12
  "minWorkbuddyVersion": "5.0.0",
13
13
  "examples_zh": [
14
14
  "查询上海可用的 RTX 4090 GPU 规格、库存和价格",
@@ -7,7 +7,7 @@
7
7
  "--python",
8
8
  "3.11",
9
9
  "--from",
10
- "compshare-cli[mcp]==0.5.0",
10
+ "compshare-cli[mcp]==0.5.1",
11
11
  "compshare-mcp"
12
12
  ],
13
13
  "env": {
@@ -3,7 +3,7 @@ name: compshare
3
3
  description: Manage CompShare GPU cloud resources and MiniMax H3 media tasks through the controlled CompShare MCP bridge.
4
4
  description_zh: 通过受控 CompShare MCP 桥接查询和管理优云智算 GPU 云资源及 MiniMax H3 视频、图片和语音任务。
5
5
  description_en: Manage CompShare GPU cloud resources and MiniMax H3 media tasks through the controlled CompShare MCP bridge.
6
- version: "0.5.0"
6
+ version: "0.5.1"
7
7
  author: "CompShare"
8
8
  ---
9
9
 
@@ -1,3 +1,3 @@
1
1
  """CompShare command-line client."""
2
2
 
3
- __version__ = "0.5.0"
3
+ __version__ = "0.5.1"
@@ -2,7 +2,6 @@ from __future__ import annotations
2
2
 
3
3
  import os
4
4
  import shlex
5
- import subprocess
6
5
  import sys
7
6
  import time
8
7
  from datetime import datetime
@@ -64,8 +63,10 @@ from compshare_cli.ssh import (
64
63
  execute_captured,
65
64
  execute_captured_with_password,
66
65
  execute_with_password,
66
+ run_command,
67
67
  scp_download_command,
68
68
  scp_upload_command,
69
+ ssh_login_command,
69
70
  )
70
71
  from compshare_cli.ssh_cache import DEFAULT_TTL, SSHCredentialCache
71
72
 
@@ -495,8 +496,7 @@ def _remote_job_connection(
495
496
  raise UsageError(tr("Instance {instance} has no SSH login command.", instance=instance))
496
497
  raw_password = host.get("Password")
497
498
  password = decode_password(str(raw_password)) if raw_password is not None else None
498
- argv = [*shlex.split(str(login_command))]
499
- argv[1:1] = ["-o", f"ConnectTimeout={connect_timeout}"]
499
+ argv = ssh_login_command(login_command, connect_timeout=connect_timeout)
500
500
  argv.append(shell_command(script))
501
501
  return argv, password, credential_source
502
502
 
@@ -540,9 +540,9 @@ def _remote_job_records(
540
540
 
541
541
 
542
542
  def _remote_job_stream(state: Runtime, instance: str, script: str) -> int:
543
- argv, password, credential_source = _remote_job_connection(state, instance, script)
544
- exit_code = execute_with_password(argv, password) if password else subprocess.call(argv)
545
- if exit_code == 255 and credential_source == "cache":
543
+ argv, password, _ = _remote_job_connection(state, instance, script)
544
+ exit_code = execute_with_password(argv, password) if password else run_command(argv)
545
+ if exit_code == 255:
546
546
  SSHCredentialCache().delete(_ssh_cache_profile(state), instance)
547
547
  return exit_code
548
548
 
@@ -2891,16 +2891,14 @@ def ssh(
2891
2891
  password = decode_password(str(raw_password)) if raw_password is not None else None
2892
2892
  if not command:
2893
2893
  raise UsageError(tr("Instance {instance} has no SSH login command.", instance=instance))
2894
- argv = [*shlex.split(command), *(remote_command or [])]
2894
+ argv = ssh_login_command(command, connect_timeout=connect_timeout)
2895
2895
  if remote_command:
2896
- argv[1:1] = ["-o", f"ConnectTimeout={connect_timeout}"]
2896
+ argv.append(joined_command(remote_command))
2897
2897
  if print_only or (state.json_output and not remote_command):
2898
2898
  Renderer(state.json_output, state.show_sensitive).data(
2899
2899
  {
2900
2900
  "instance": instance,
2901
- "command": command
2902
- if not remote_command
2903
- else f"{command} {shlex.join(remote_command)}",
2901
+ "command": shlex.join(argv),
2904
2902
  "password": password,
2905
2903
  "credential_source": credential_source,
2906
2904
  }
@@ -2920,7 +2918,7 @@ def ssh(
2920
2918
  "code": execution.error_code,
2921
2919
  "message": message,
2922
2920
  }
2923
- if credential_source == "cache" and execution.phase in {
2921
+ if use_cache and execution.phase in {
2924
2922
  "authentication",
2925
2923
  "connection",
2926
2924
  "ssh",
@@ -2956,21 +2954,13 @@ def ssh(
2956
2954
  err=True,
2957
2955
  )
2958
2956
  else:
2959
- if exit_code == 255 and credential_source == "cache":
2957
+ if exit_code == 255 and use_cache:
2960
2958
  SSHCredentialCache().delete(_ssh_cache_profile(state), instance)
2961
2959
  raise typer.Exit(exit_code)
2962
2960
  if password and not state.show_sensitive:
2963
2961
  typer.echo(tr("Password hidden; rerun with --show-sensitive to display it."))
2964
- elif not password:
2965
- typer.echo(
2966
- tr(
2967
- "The API did not return a password. Run `compshare instance password {instance}` "
2968
- "to set one.",
2969
- instance=instance,
2970
- )
2971
- )
2972
- exit_code = subprocess.call(argv)
2973
- if exit_code == 255 and credential_source == "cache":
2962
+ exit_code = run_command(argv)
2963
+ if exit_code == 255 and use_cache:
2974
2964
  SSHCredentialCache().delete(_ssh_cache_profile(state), instance)
2975
2965
  raise typer.Exit(exit_code)
2976
2966
 
@@ -2994,6 +2984,22 @@ def cp(
2994
2984
  "--auto-password/--no-auto-password",
2995
2985
  help="Automatically enter the password returned by the API.",
2996
2986
  ),
2987
+ connect_timeout: int = typer.Option(
2988
+ 30, "--connect-timeout", min=1, help="Maximum SSH connection time in seconds."
2989
+ ),
2990
+ use_cache: bool = typer.Option(
2991
+ True,
2992
+ "--cache/--no-cache",
2993
+ help="Cache SSH connection data to avoid repeated instance queries.",
2994
+ ),
2995
+ cache_ttl: int = typer.Option(
2996
+ DEFAULT_TTL, "--cache-ttl", min=1, help="SSH connection cache lifetime in seconds."
2997
+ ),
2998
+ refresh: bool = typer.Option(
2999
+ False,
3000
+ "--refresh",
3001
+ help="Refresh SSH connection data from the API before connecting.",
3002
+ ),
2997
3003
  ) -> None:
2998
3004
  source_is_remote = source_path.startswith(":")
2999
3005
  destination_is_remote = destination_path.startswith(":")
@@ -3019,14 +3025,16 @@ def cp(
3019
3025
  raise UsageError(tr("Remote path cannot be empty."))
3020
3026
 
3021
3027
  state = runtime(ctx)
3022
- _, _, host = locate_instance(state, instance)
3028
+ _, _, host, _ = _locate_ssh_instance(
3029
+ state, instance, use_cache=use_cache, refresh=refresh, cache_ttl=cache_ttl
3030
+ )
3023
3031
  login_command = host.get("SshLoginCommand")
3024
3032
  raw_password = host.get("Password")
3025
3033
  password = decode_password(str(raw_password)) if raw_password is not None else None
3026
3034
  if not login_command:
3027
3035
  raise UsageError(tr("Instance {instance} has no SSH login command.", instance=instance))
3028
3036
  try:
3029
- ssh_argv = shlex.split(str(login_command))
3037
+ ssh_argv = ssh_login_command(login_command, connect_timeout=connect_timeout)
3030
3038
  if direction == "download":
3031
3039
  argv = scp_download_command(ssh_argv, remote_path, str(local), recursive=True)
3032
3040
  else:
@@ -3061,6 +3069,8 @@ def cp(
3061
3069
  "code": execution.error_code,
3062
3070
  "message": message,
3063
3071
  }
3072
+ if use_cache and execution.phase in {"authentication", "connection", "ssh"}:
3073
+ SSHCredentialCache().delete(_ssh_cache_profile(state), instance)
3064
3074
  Renderer(True, state.show_sensitive).data(
3065
3075
  {
3066
3076
  "instance": instance,
@@ -3084,15 +3094,12 @@ def cp(
3084
3094
  err=True,
3085
3095
  )
3086
3096
  else:
3097
+ if exit_code == 255 and use_cache:
3098
+ SSHCredentialCache().delete(_ssh_cache_profile(state), instance)
3087
3099
  raise typer.Exit(exit_code)
3088
3100
  if password and not state.show_sensitive:
3089
3101
  typer.echo(tr("Password hidden; rerun with --show-sensitive to display it."))
3090
- elif not password:
3091
- typer.echo(
3092
- tr(
3093
- "The API did not return a password. Run `compshare instance password {instance}` "
3094
- "to set one.",
3095
- instance=instance,
3096
- )
3097
- )
3098
- raise typer.Exit(subprocess.call(argv))
3102
+ exit_code = run_command(argv)
3103
+ if exit_code == 255 and use_cache:
3104
+ SSHCredentialCache().delete(_ssh_cache_profile(state), instance)
3105
+ raise typer.Exit(exit_code)
@@ -831,9 +831,11 @@ ZH_TRANSLATIONS: Dict[str, str] = {
831
831
  "Incomplete credentials": "凭证不完整",
832
832
  "Not configured": "未配置",
833
833
  "Instance {instance} has no SSH login command.": "实例 {instance} 没有可用的 SSH 登录命令。",
834
- "The API did not return a password. Run `compshare instance password {instance}` to set one.": (
835
- "API 未返回密码。请运行 `compshare instance password {instance}` 设置密码。"
834
+ "The instance SSH login command is invalid.": "实例的 SSH 登录命令无效。",
835
+ "SSH password automation requires compshare-ssh-askpass; reinstall compshare-cli.": (
836
+ "自动填写 SSH 密码需要 compshare-ssh-askpass;请重新安装 compshare-cli。"
836
837
  ),
838
+ "Unable to run {executable}: {detail}": "无法运行 {executable}:{detail}",
837
839
  "Password hidden; rerun with --show-sensitive to display it.": (
838
840
  "密码已隐藏;如需显示,请使用 --show-sensitive 重新运行。"
839
841
  ),
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import os
4
4
  import re
5
+ import shlex
5
6
  import shutil
6
7
  import signal
7
8
  import subprocess
@@ -9,6 +10,10 @@ import sys
9
10
  import tempfile
10
11
  from dataclasses import dataclass
11
12
  from typing import Any, List, Optional
13
+ from urllib.parse import urlsplit
14
+
15
+ from compshare_cli.errors import CLIError, UsageError
16
+ from compshare_cli.i18n import tr
12
17
 
13
18
  _ASKPASS_PASSWORD_FILE_ENV = "COMPSHARE_INTERNAL_SSH_PASSWORD_FILE"
14
19
  _SSH_OPTIONS_WITH_VALUE = {
@@ -37,7 +42,7 @@ _SSH_OPTIONS_WITH_VALUE = {
37
42
  _SCP_SHARED_OPTIONS = {"-c", "-F", "-i", "-J", "-o"}
38
43
 
39
44
 
40
- class PasswordAutomationUnavailable(RuntimeError):
45
+ class PasswordAutomationUnavailable(CLIError):
41
46
  """Raised when the current terminal cannot safely automate an SSH password."""
42
47
 
43
48
 
@@ -61,7 +66,7 @@ def _is_windows() -> bool:
61
66
 
62
67
 
63
68
  def _password_authentication(argv: List[str], *, command_mode: bool = False) -> List[str]:
64
- executable = os.path.basename(argv[0]).casefold()
69
+ executable = os.path.basename(argv[0]).casefold() if argv else ""
65
70
  if executable not in {"ssh", "ssh.exe"}:
66
71
  raise PasswordAutomationUnavailable
67
72
  options = [
@@ -74,6 +79,8 @@ def _password_authentication(argv: List[str], *, command_mode: bool = False) ->
74
79
  "NumberOfPasswordPrompts=1",
75
80
  "-o",
76
81
  "StrictHostKeyChecking=accept-new",
82
+ "-o",
83
+ "BatchMode=no",
77
84
  ]
78
85
  if command_mode:
79
86
  options.extend(["-n", "-T"])
@@ -81,7 +88,7 @@ def _password_authentication(argv: List[str], *, command_mode: bool = False) ->
81
88
 
82
89
 
83
90
  def _scp_password_authentication(argv: List[str]) -> List[str]:
84
- executable = os.path.basename(argv[0]).casefold()
91
+ executable = os.path.basename(argv[0]).casefold() if argv else ""
85
92
  if executable not in {"scp", "scp.exe"}:
86
93
  raise PasswordAutomationUnavailable
87
94
  return [
@@ -94,6 +101,8 @@ def _scp_password_authentication(argv: List[str]) -> List[str]:
94
101
  "NumberOfPasswordPrompts=1",
95
102
  "-o",
96
103
  "StrictHostKeyChecking=accept-new",
104
+ "-o",
105
+ "BatchMode=no",
97
106
  *argv[1:],
98
107
  ]
99
108
 
@@ -137,13 +146,39 @@ def _scp_connection(ssh_argv: List[str]) -> tuple[List[str], str]:
137
146
  raise ValueError("SSH login command contains a remote command")
138
147
  index += 1
139
148
 
140
- if destination is None:
149
+ if not destination:
141
150
  raise ValueError("SSH login command has no destination")
142
- if login and "@" not in destination:
143
- destination = f"{login}@{destination}"
151
+ if destination.startswith("ssh://"):
152
+ parsed = urlsplit(destination)
153
+ if not parsed.hostname or parsed.path or parsed.query or parsed.fragment:
154
+ raise ValueError("invalid SSH destination URI")
155
+ destination = parsed.hostname
156
+ login = login or parsed.username
157
+ if parsed.port is not None and "-P" not in scp_options:
158
+ scp_options.extend(("-P", str(parsed.port)))
159
+ username, separator, hostname = destination.rpartition("@")
160
+ if not separator:
161
+ hostname = destination
162
+ if ":" in hostname and not hostname.startswith("["):
163
+ hostname = f"[{hostname}]"
164
+ username = login or username
165
+ destination = f"{username}@{hostname}" if username else hostname
144
166
  return scp_options, destination
145
167
 
146
168
 
169
+ def ssh_login_command(command: str, *, connect_timeout: int = 30) -> List[str]:
170
+ """Validate an API login command and bound connection setup for every caller."""
171
+ try:
172
+ if not isinstance(command, str):
173
+ raise ValueError("SSH login command must be a string")
174
+ argv = shlex.split(command)
175
+ _scp_connection(argv)
176
+ except (TypeError, ValueError) as exc:
177
+ raise UsageError(tr("The instance SSH login command is invalid.")) from exc
178
+ argv[1:1] = ["-o", f"ConnectTimeout={connect_timeout}"]
179
+ return argv
180
+
181
+
147
182
  def scp_upload_command(
148
183
  ssh_argv: List[str],
149
184
  local_path: str,
@@ -180,7 +215,9 @@ def _askpass_executable() -> str:
180
215
  located = shutil.which(name)
181
216
  if located:
182
217
  return located
183
- raise PasswordAutomationUnavailable
218
+ raise PasswordAutomationUnavailable(
219
+ tr("SSH password automation requires compshare-ssh-askpass; reinstall compshare-cli.")
220
+ )
184
221
 
185
222
 
186
223
  def askpass() -> None:
@@ -217,25 +254,33 @@ def execute_captured_with_password(argv: List[str], password: str) -> RemoteExec
217
254
 
218
255
  def execute_captured(argv: List[str]) -> RemoteExecutionResult:
219
256
  """Run and capture a non-interactive SSH command using normal OpenSSH auth."""
220
- executable = os.path.basename(argv[0]).casefold()
257
+ executable = os.path.basename(argv[0]).casefold() if argv else ""
221
258
  if executable not in {"ssh", "ssh.exe"}:
222
259
  raise PasswordAutomationUnavailable
223
260
  command = [
224
261
  argv[0],
225
262
  "-o",
263
+ "BatchMode=yes",
264
+ "-o",
226
265
  "StrictHostKeyChecking=accept-new",
227
266
  "-n",
228
267
  "-T",
229
268
  *argv[1:],
230
269
  ]
231
- completed = subprocess.run(command, capture_output=True, text=True, check=False)
270
+ completed = run_command(command, capture=True)
232
271
  return remote_execution_result(completed.returncode, completed.stdout, completed.stderr)
233
272
 
234
273
 
235
- def remote_execution_result(exit_code: int, stdout: str, stderr: str) -> RemoteExecutionResult:
274
+ def remote_execution_result(
275
+ exit_code: int, stdout: str, stderr: str, *, transfer: bool = False
276
+ ) -> RemoteExecutionResult:
236
277
  """Classify common OpenSSH failures while preserving the original diagnostics."""
237
278
  if exit_code == 0:
238
279
  return RemoteExecutionResult(exit_code, stdout, stderr, "completed")
280
+ if exit_code != 255 and not transfer:
281
+ return RemoteExecutionResult(
282
+ exit_code, stdout, stderr, "remote_command", "remote_exit_nonzero"
283
+ )
239
284
 
240
285
  diagnostic = stderr.casefold()
241
286
  patterns = (
@@ -247,7 +292,7 @@ def remote_execution_result(exit_code: int, stdout: str, stderr: str) -> RemoteE
247
292
  ("network is unreachable", "connection", "network_unreachable"),
248
293
  ("connection refused", "connection", "connection_refused"),
249
294
  ("host key verification failed", "connection", "host_key_verification_failed"),
250
- ("permission denied", "authentication", "authentication_failed"),
295
+ ("permission denied (", "authentication", "authentication_failed"),
251
296
  ("authentication failed", "authentication", "authentication_failed"),
252
297
  ("too many authentication failures", "authentication", "authentication_failed"),
253
298
  )
@@ -256,7 +301,7 @@ def remote_execution_result(exit_code: int, stdout: str, stderr: str) -> RemoteE
256
301
  return RemoteExecutionResult(exit_code, stdout, stderr, phase, error_code)
257
302
  if exit_code == 255:
258
303
  return RemoteExecutionResult(exit_code, stdout, stderr, "ssh", "ssh_failed")
259
- return RemoteExecutionResult(exit_code, stdout, stderr, "remote_command", "remote_exit_nonzero")
304
+ return RemoteExecutionResult(exit_code, stdout, stderr, "file_transfer", "transfer_failed")
260
305
 
261
306
 
262
307
  def copy_with_password(argv: List[str], password: str) -> int:
@@ -270,12 +315,14 @@ def copy_captured_with_password(argv: List[str], password: str) -> RemoteExecuti
270
315
  command = _scp_password_authentication(argv)
271
316
  completed = _run_with_askpass(command, password, capture=True)
272
317
  assert isinstance(completed, subprocess.CompletedProcess)
273
- return remote_execution_result(completed.returncode, completed.stdout, completed.stderr)
318
+ return remote_execution_result(
319
+ completed.returncode, completed.stdout, completed.stderr, transfer=True
320
+ )
274
321
 
275
322
 
276
323
  def copy_captured(argv: List[str]) -> RemoteExecutionResult:
277
324
  """Run and capture an SCP transfer using non-interactive OpenSSH authentication."""
278
- executable = os.path.basename(argv[0]).casefold()
325
+ executable = os.path.basename(argv[0]).casefold() if argv else ""
279
326
  if executable not in {"scp", "scp.exe"}:
280
327
  raise PasswordAutomationUnavailable
281
328
  command = [
@@ -286,8 +333,34 @@ def copy_captured(argv: List[str]) -> RemoteExecutionResult:
286
333
  "StrictHostKeyChecking=accept-new",
287
334
  *argv[1:],
288
335
  ]
289
- completed = subprocess.run(command, capture_output=True, text=True, check=False)
290
- return remote_execution_result(completed.returncode, completed.stdout, completed.stderr)
336
+ completed = run_command(command, capture=True)
337
+ return remote_execution_result(
338
+ completed.returncode, completed.stdout, completed.stderr, transfer=True
339
+ )
340
+
341
+
342
+ def run_command(
343
+ command: List[str], *, capture: bool = False, environment: Optional[dict] = None
344
+ ) -> Any:
345
+ """Keep process failures user-facing and captured output safe for JSON."""
346
+ try:
347
+ if capture:
348
+ return subprocess.run(
349
+ command,
350
+ env=environment,
351
+ capture_output=True,
352
+ text=True,
353
+ encoding="utf-8",
354
+ errors="replace",
355
+ check=False,
356
+ )
357
+ if environment is None:
358
+ return subprocess.call(command)
359
+ return subprocess.call(command, env=environment)
360
+ except OSError as exc:
361
+ raise CLIError(
362
+ tr("Unable to run {executable}: {detail}", executable=command[0], detail=exc)
363
+ ) from exc
291
364
 
292
365
 
293
366
  def _run_with_askpass(
@@ -310,15 +383,7 @@ def _run_with_askpass(
310
383
  }
311
384
  )
312
385
  environment.setdefault("DISPLAY", "compshare-ssh")
313
- if capture:
314
- return subprocess.run(
315
- command,
316
- env=environment,
317
- capture_output=True,
318
- text=True,
319
- check=False,
320
- )
321
- return subprocess.call(command, env=environment)
386
+ return run_command(command, capture=capture, environment=environment)
322
387
 
323
388
 
324
389
  def connect_with_password(argv: List[str], password: str) -> int:
@@ -335,12 +400,17 @@ def connect_with_password(argv: List[str], password: str) -> int:
335
400
 
336
401
  command = _password_authentication(argv)
337
402
  size = shutil.get_terminal_size(fallback=(80, 24))
338
- child = pexpect.spawn(
339
- command[0],
340
- command[1:],
341
- encoding=None,
342
- dimensions=(size.lines, size.columns),
343
- )
403
+ try:
404
+ child = pexpect.spawn(
405
+ command[0],
406
+ command[1:],
407
+ encoding=None,
408
+ dimensions=(size.lines, size.columns),
409
+ )
410
+ except (OSError, pexpect.ExceptionPexpect) as exc:
411
+ raise CLIError(
412
+ tr("Unable to run {executable}: {detail}", executable=command[0], detail=exc)
413
+ ) from exc
344
414
  prompt = re.compile(rb"password\s*:\s*$", re.IGNORECASE)
345
415
  password_bytes = password.encode("utf-8")
346
416
  tail = b""
@@ -126,14 +126,19 @@ class SSHCredentialCache:
126
126
  cached_at = raw.get("cached_at")
127
127
  host = raw.get("host")
128
128
  current = time.time() if now is None else now
129
- if not isinstance(cached_at, (int, float)) or current - cached_at > ttl:
129
+ if not isinstance(cached_at, (int, float)) or not 0 <= current - cached_at <= ttl:
130
130
  return None
131
131
  if not isinstance(host, dict):
132
132
  return None
133
- if not host.get("SshLoginCommand"):
133
+ if any(
134
+ not isinstance(host.get(field), str) or not host[field].strip()
135
+ for field in ("Region", "Zone", "SshLoginCommand")
136
+ ):
134
137
  return None
135
138
  result = dict(host)
136
139
  password = result.get("Password")
140
+ if password is not None and not isinstance(password, str):
141
+ return None
137
142
  if isinstance(password, str):
138
143
  clear = _unprotect_password(password)
139
144
  if clear is None:
@@ -178,7 +183,7 @@ class SSHCredentialCache:
178
183
  return {"version": CACHE_VERSION, "entries": {}}
179
184
  try:
180
185
  data = json.loads(self.path.read_text(encoding="utf-8"))
181
- except (OSError, json.JSONDecodeError):
186
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
182
187
  return {"version": CACHE_VERSION, "entries": {}}
183
188
  if (
184
189
  not isinstance(data, dict)
@@ -191,8 +196,7 @@ class SSHCredentialCache:
191
196
  def _write(self, data: Dict[str, Any]) -> None:
192
197
  temporary: Optional[Path] = None
193
198
  try:
194
- self.path.parent.mkdir(parents=True, exist_ok=True)
195
- os.chmod(self.path.parent, stat.S_IRWXU)
199
+ self.path.parent.mkdir(mode=stat.S_IRWXU, parents=True, exist_ok=True)
196
200
  with tempfile.NamedTemporaryFile(
197
201
  mode="w",
198
202
  encoding="utf-8",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: compshare-cli
3
- Version: 0.5.0
3
+ Version: 0.5.1
4
4
  Summary: Command-line client for CompShare GPU compute and MiniMax H3
5
5
  Author: CompShare
6
6
  License-Expression: Apache-2.0
@@ -82,6 +82,13 @@ compshare instance list --all
82
82
 
83
83
  # 连接实例
84
84
  compshare instance ssh INSTANCE_ID
85
+ compshare --json instance ssh INSTANCE_ID -- nvidia-smi
86
+ compshare --json instance ssh INSTANCE_ID -- sh -lc 'cd /workspace && pwd'
87
+
88
+ # 上传、下载文件或目录
89
+ compshare --json instance cp INSTANCE_ID ./model.bin :/workspace/model.bin
90
+ compshare --json instance cp INSTANCE_ID ./dataset :/workspace/dataset
91
+ compshare --json instance cp INSTANCE_ID :/workspace/results ./results
85
92
 
86
93
  # MiniMax H3:先预演,再创建
87
94
  compshare --json minimax create '一只猫在海边奔跑' --dry-run
@@ -105,6 +112,12 @@ compshare -h
105
112
  compshare instance -h
106
113
  ```
107
114
 
115
+ SSH 远程命令放在 `--` 后面,参数中的空格、引号和 `$` 会按原样传递;需要管道、重定向
116
+ 或 `&&` 时使用 `sh -lc '脚本'`。SSH 和文件传输共用一小时有效的连接缓存,重置密码或
117
+ 重装后可用 `--refresh` 强制刷新,`--no-cache` 禁用缓存。`--connect-timeout` 设置连接
118
+ 建立的最长时间(默认 30 秒),`ssh --timeout` 设置等待实例运行的时间;长任务使用
119
+ `instance job`。
120
+
108
121
  ## 命令概览
109
122
 
110
123
  ```text
@@ -64,4 +64,5 @@ tests/test_remote_jobs.py
64
64
  tests/test_sdk.py
65
65
  tests/test_ssh.py
66
66
  tests/test_ssh_cache.py
67
+ tests/test_ssh_integration.py
67
68
  tests/test_workbuddy_connector.py