Google Cloud Shell Python 客户端实战:环境启动、SSH 密钥管理与 gcloud 预授权
Google Cloud Shell Python 客户端实战:环境启动、SSH 密钥管理与 gcloud 预授权
本篇指南以 Context Hub 仓库中维护的 Google Cloud Shell Python 客户端文档 为核心,系统讲解 google-cloud-shell 1.14.0 的安装、认证、客户端初始化,以及查询/启动环境、增删 SSH 公钥、向运行中的环境推送 OAuth 凭据(预授权 gcloud)等完整工作流。读完你可以直接用 Python 代码管理 Cloud Shell 环境,并把获取的 SSH/WSS 连接信息接入自己的远程开发流程;同时会了解这些文档在 Context Hub 中如何被编码 Agent 通过 chub 命令检索与使用。
文档定位与获取方式
本文依据的源文档位于仓库的 content/google/docs/shell/python/DOC.md。该文件带有 YAML frontmatter,声明了其元数据:
name: shell—— 条目名,对应检索 ID 中的google/shell;metadata.languages: "python"—— 这是 Python 语言变体;metadata.versions: "1.14.0"—— 覆盖的 PyPI 包版本;metadata.revision: 1、updated-on: "2026-03-13"—— 内容修订号与最后更新日期;metadata.source: maintainer—— 内容信任级别;metadata.tags——google,cloud-shell,gcp,ssh,shell,remote-development。
按仓库的 内容规范 说明,versions 字段始终指包/SDK 版本(PyPI 上的版本号),这正是 Agent 从 requirements.txt 或 package.json 中可探测到的版本。作为多语言文档的 Python 变体,它放在 shell/python/ 子目录中(对应 目录结构约定 的 multi-language docs 布局)。
在 Context Hub 中,编码 Agent 获取本文档的典型方式是使用 CLI 参考 中描述的 chub 命令:
chub get google/shell --lang py
若需要保持内容新鲜度,可使用 get-api-docs 技能 中记录的流程:先 chub search "cloud shell" --json 找到匹配 ID,再 chub get <id> --lang py 拉取,用完后通过 chub annotate 记录补充经验、通过 chub feedback 反馈文档质量。
核心能力与边界:它是什么
google-cloud-shell 是 Cloud Shell API 的 Python 官方客户端,提供以下能力:
- 查看某个用户的 Cloud Shell 环境状态与元数据;
- 启动(唤醒)Cloud Shell 环境;
- 向环境中添加或移除 SSH 公钥;
- 向运行中的环境推送 OAuth 访问凭据,使环境内的
gcloud无需再次登录即可使用。
一个重要的边界:该包不会替你执行 shell 命令。API 只返回环境元数据(如 web_host、ssh_username、ssh_host、ssh_port),你仍需用自己的 SSH 客户端或 Web 客户端去连接环境。换言之,这个 API 面是刻意保持小巧的:get、start、authorize、add key、remove key 五类操作,不要期待存在一个 "run command" RPC(该限制也明确写入源文档的 "Important Pitfalls" 一节)。
安装与版本锁定
官方推荐锁定项目期望的版本号:
python -m pip install "google-cloud-shell==1.14.0"
使用其他包管理器时的等价写法:
uv add "google-cloud-shell==1.14.0"
poetry add "google-cloud-shell==1.14.0"
Python 版本兼容性方面:源文档指出 Google 当前的库文档与 PyPI 元数据标明支持 Python 3.7+,包括 Python 3.14(Python 3.14 支持自上游 1.13.0 的 changelog 加入,详见下文"版本敏感信息")。
认证与初始化
Application Default Credentials(ADC)
Cloud Shell 使用 ADC(应用默认凭据)。本地开发时先用 gcloud 登录:
gcloud auth application-default login
可选的补充环境变量:
export GOOGLE_APPLICATION_CREDENTIALS="/absolute/path/to/credentials.json"
export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google
GOOGLE_APPLICATION_CREDENTIALS让 ADC 显式加载某个凭据文件;- Google 官方建议尽量避免长期存在的服务账号密钥(服务账号密钥被视为安全风险,不推荐,详见下文陷阱部分);
GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google用于启用默认的 Google 客户端库日志处理器。
资源命名:用户级而非项目级
Cloud Shell 环境名是按用户隔离的,不是按项目隔离的,因此客户端方法上不要期望有 project= 参数。默认环境名通常是:
users/me/environments/default
初始化客户端
最小初始化(使用默认 ADC):
from google.cloud import shell_v1
client = shell_v1.CloudShellServiceClient()
environment_name = client.environment_path("me", "default")
如果需要显式指定凭据(例如显式携带 cloud-platform scope):
import google.auth
from google.cloud import shell_v1
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
client = shell_v1.CloudShellServiceClient(credentials=credentials)
environment_name = client.environment_path("me", "default")
environment_path("me", "default") 是生成式客户端提供的路径构造方法,它把 users/me/environments/default 这个规范资源名拼装出来,供后续所有请求复用。
常用工作流
查询当前环境:get_environment
获取环境元数据是最基础的只读操作:
from google.cloud import shell_v1
client = shell_v1.CloudShellServiceClient()
environment_name = client.environment_path("me", "default")
environment = client.get_environment(request={"name": environment_name})
print(environment.name)
print(environment.state)
print(environment.web_host)
print(environment.ssh_username)
print(environment.ssh_host)
print(environment.ssh_port)
返回的 Environment 对象包含运行中环境的 SSH 与 WSS 连接目标(ssh_host、ssh_port、web_host、ssh_username),以及当前已注册的公钥信息。state 字段可用于判断环境是否处于可连接状态。
启动环境并预授权 gcloud:start_environment
start_environment 是一个长时间运行操作(long-running operation),必须等待 .result() 返回后再读取连接字段,否则拿到的是尚未就绪的结果:
from pathlib import Path
import google.auth
from google.auth.transport.requests import Request
from google.cloud import shell_v1
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
credentials.refresh(Request())
client = shell_v1.CloudShellServiceClient(credentials=credentials)
environment_name = client.environment_path("me", "default")
public_key = Path.home().joinpath(".ssh/id_rsa.pub").read_text().strip()
operation = client.start_environment(
request={
"name": environment_name,
"access_token": credentials.token,
"public_keys": [public_key],
}
)
response = operation.result(timeout=300)
environment = response.environment
print(environment.web_host)
print(environment.ssh_username)
print(environment.ssh_host)
print(environment.ssh_port)
要点:
public_keys传入本机公钥内容(示例从~/.ssh/id_rsa.pub读取),环境启动后该公钥即被注册,用于后续 SSH 认证;access_token是可选参数,但若传入有效 token,环境会被预认证,用户进入 Cloud Shell 后可直接运行gcloud命令而无需再次登录;- 调用前先用
credentials.refresh(Request())确保 token 新鲜有效; operation.result(timeout=300)表示最多等待 300 秒,超时则抛出异常。
启动后通过 SSH 连接
start_environment 完成后,用与本机注册公钥匹配的私钥连接:
ssh -p "${SSH_PORT}" "${SSH_USER}@${SSH_HOST}"
在 Python 侧,连接值取自 get_environment() 或 start_environment() 返回的 Environment:
ssh_user = environment.ssh_username
ssh_host = environment.ssh_host
ssh_port = environment.ssh_port
注意:SSH 只有在本机私钥与环境中已注册的某个公钥匹配时才有效,否则连接会被拒绝。
事后追加公钥:add_public_key
当环境已存在、需要允许另一对 SSH 密钥时,使用 add_public_key:
from pathlib import Path
from google.cloud import shell_v1
client = shell_v1.CloudShellServiceClient()
environment_name = client.environment_path("me", "default")
public_key = Path.home().joinpath(".ssh/id_rsa.pub").read_text().strip()
operation = client.add_public_key(
request={
"environment": environment_name,
"key": public_key,
}
)
response = operation.result(timeout=60)
print(response.key)
同样地,该方法返回长时间运行操作,需 operation.result() 等待完成;response.key 回显被添加的密钥内容。请求文档中列出的受支持密钥格式为 ssh-dss、ssh-rsa 以及 ecdsa-sha2-* 系列变体。
移除公钥:remove_public_key
对称地,移除某把公钥:
from pathlib import Path
from google.cloud import shell_v1
client = shell_v1.CloudShellServiceClient()
environment_name = client.environment_path("me", "default")
public_key = Path.home().joinpath(".ssh/id_rsa.pub").read_text().strip()
operation = client.remove_public_key(
request={
"environment": environment_name,
"key": public_key,
}
)
operation.result(timeout=60)
请求体结构与 add_public_key 一致,也是长时间运行操作,等待 result() 返回后即完成移除。
不重启环境刷新授权:authorize_environment
如果环境已在运行,想推送新的 OAuth token 而不重新启动环境,使用 authorize_environment:
from datetime import datetime, timedelta, timezone
import google.auth
from google.auth.transport.requests import Request
from google.cloud import shell_v1
from google.protobuf import timestamp_pb2
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
credentials.refresh(Request())
expire_time = timestamp_pb2.Timestamp()
expire_time.FromDatetime(
datetime.now(timezone.utc) + timedelta(minutes=55)
)
client = shell_v1.CloudShellServiceClient(credentials=credentials)
environment_name = client.environment_path("me", "default")
operation = client.authorize_environment(
request={
"name": environment_name,
"access_token": credentials.token,
"expire_time": expire_time,
}
)
operation.result(timeout=60)
要点:
expire_time通过 protobuf 的timestamp_pb2.Timestamp构造,示例设置为当前时间之后 55 分钟,用于控制推送进环境的凭据有效期;- REST 参考文档还列出
id_token作为可选的附加字段,如果你的工作流还需要把 ID token 送进环境,可以一并传入。
关键陷阱(Pitfalls)
综合源文档的 "Important Pitfalls" 一节,实践中必须注意:
- 资源名是用户级的:如
users/me/environments/default,客户端方法上不要期待project=参数。 - 四个写操作都是长时间运行操作:
start_environment、add_public_key、remove_public_key、authorize_environment都返回 operation,必须等待.result()完成后再假设变更已生效。 - SSH 认证依赖密钥配对:只有本机私钥与环境中已注册的某个公钥匹配时,SSH 连接才有效。
- API 面很小:get、start、authorize、add key、remove key 就是全部;用返回的 SSH/WSS 坐标自行连接,不要期待客户端里有 "run command" RPC。
- 优先使用用户 ADC:Google ADC 文档明确说明服务账号密钥存在安全风险、不推荐;本地开发优先用户 ADC 或其他非密钥型 ADC 流程。
版本敏感信息与升级注意
源文档的 "Version-Sensitive Notes" 一节给出了若干需要核对的事实:
- PyPI 当前发布
google-cloud-shell 1.14.0(发布于 2026 年 1 月 15 日); - Google 参考文档与 changelog 页面仍把最新参考内容标记为
1.13.0:上文的公开 API 面可视为当前形态,但如果你依赖1.13.0之后引入的行为,请仔细核对 changelog 层面的细节; 1.13.0的 changelog:加入 Python 3.14 支持,并弃用credentials_file参数——优先使用 ADC 或显式传入credentials=对象;1.12.0的 changelog:加入可读取元数据的 REST 拦截器;1.7.0的 changelog:启用"rest"transport。如果你需要显式使用 HTTP/JSON transport,可在创建客户端时传transport="rest":
client = shell_v1.CloudShellServiceClient(transport="rest")
由于源文档本身标注 source: maintainer 且已记录版本演进,升级依赖时建议以 PyPI 实际发布的版本与官方 changelog 为准,而不是依赖训练记忆中的 API 形态——这正是 Context Hub 文档体系想解决的问题:Agent 在写代码前先 chub get 拿到带版本号、带修订日期的准确文档,而不是凭记忆猜测。
把本文档接入 Agent 工作流
在 Context Hub 中,本文档的价值在于被编码 Agent 在编写调用 Cloud Shell API 的代码前直接读取。结合 get-api-docs 技能 与 CLI 参考,完整流程是:
# 1. 确保 chub 存在
chub --help
# 2. 检索相关文档
chub search "cloud shell" --json
# 3. 拉取 Python 变体
chub get google/shell --lang py
# 4. 完成后补充本地经验(可选)
chub annotate google/shell "access_token 需要先 refresh(Request()) 再传入"
若文档附带额外的参考文件(references/ 子目录中的内容),可用 chub get google/shell --full 或 --file <path> 增量获取,避免浪费 token;文档的修订号与更新日期(revision、updated-on)会随 frontmatter 一起提供给 Agent,用于判断内容新鲜度(见 内容规范 的版本更新约定)。发现的文档缺口可以通过 chub feedback 反馈给维护者,形成"文档随使用持续改进"的闭环。