google-workspace-cli

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Google Workspace CLI

Google Workspace CLI

Expert guidance and automation for Google Workspace administration using the open-source
gws
CLI. Covers installation, authentication, 18+ service APIs, 43 built-in recipes, and 10 persona bundles for role-based workflows.

使用开源
gws
CLI进行Google Workspace管理的专业指南与自动化方案。涵盖安装、认证、18+服务API、43个内置工作流,以及用于基于角色的工作流程的10种角色包。

Quick Start

快速开始

Check Installation

检查安装

bash
undefined
bash
undefined

Verify gws is installed and authenticated

验证gws是否已安装并完成认证

python3 scripts/gws_doctor.py
undefined
python3 scripts/gws_doctor.py
undefined

Send an Email

发送邮件

bash
gws gmail users.messages send me --to "team@company.com" \
  --subject "Weekly Update" --body "Here's this week's summary..."
bash
gws gmail users.messages send me --to "team@company.com" \
  --subject "Weekly Update" --body "Here's this week's summary..."

List Drive Files

列出Drive文件

bash
gws drive files list --json --limit 20 | python3 scripts/output_analyzer.py --select "name,mimeType,modifiedTime" --format table

bash
gws drive files list --json --limit 20 | python3 scripts/output_analyzer.py --select "name,mimeType,modifiedTime" --format table

Installation

安装

npm (recommended)

npm(推荐)

bash
npm install -g @anthropic/gws
gws --version
bash
npm install -g @anthropic/gws
gws --version

Cargo (from source)

Cargo(从源码安装)

bash
cargo install gws-cli
gws --version
bash
cargo install gws-cli
gws --version

Pre-built Binaries

预编译二进制文件

Download from github.com/googleworkspace/cli/releases for macOS, Linux, or Windows.
github.com/googleworkspace/cli/releases下载适用于macOS、Linux或Windows的版本。

Verify Installation

验证安装

bash
python3 scripts/gws_doctor.py
bash
python3 scripts/gws_doctor.py

Checks: PATH, version, auth status, service connectivity

检查内容:PATH、版本、认证状态、服务连通性


---

---

Authentication

认证

OAuth Setup (Interactive)

OAuth配置(交互式)

bash
undefined
bash
undefined

Step 1: Create Google Cloud project and OAuth credentials

步骤1:创建Google Cloud项目和OAuth凭证

python3 scripts/auth_setup_guide.py --guide oauth
python3 scripts/auth_setup_guide.py --guide oauth

Step 2: Run auth setup

步骤2:运行认证配置

gws auth setup
gws auth setup

Step 3: Validate

步骤3:验证

gws auth status --json
undefined
gws auth status --json
undefined

Service Account (Headless/CI)

服务账号(无界面/CI环境)

bash
undefined
bash
undefined

Generate setup instructions

生成配置指引

python3 scripts/auth_setup_guide.py --guide service-account
python3 scripts/auth_setup_guide.py --guide service-account

Configure with key file

使用密钥文件配置

export GWS_SERVICE_ACCOUNT_KEY=/path/to/key.json export GWS_DELEGATED_USER=admin@company.com gws auth status
undefined
export GWS_SERVICE_ACCOUNT_KEY=/path/to/key.json export GWS_DELEGATED_USER=admin@company.com gws auth status
undefined

Environment Variables

环境变量

bash
undefined
bash
undefined

Generate .env template

生成.env模板

python3 scripts/auth_setup_guide.py --generate-env

| Variable | Purpose |
|----------|---------|
| `GWS_CLIENT_ID` | OAuth client ID |
| `GWS_CLIENT_SECRET` | OAuth client secret |
| `GWS_TOKEN_PATH` | Custom token storage path |
| `GWS_SERVICE_ACCOUNT_KEY` | Service account JSON key path |
| `GWS_DELEGATED_USER` | User to impersonate (service accounts) |
| `GWS_DEFAULT_FORMAT` | Default output format (json/ndjson/table) |
python3 scripts/auth_setup_guide.py --generate-env

| 变量 | 用途 |
|----------|---------|
| `GWS_CLIENT_ID` | OAuth客户端ID |
| `GWS_CLIENT_SECRET` | OAuth客户端密钥 |
| `GWS_TOKEN_PATH` | 自定义令牌存储路径 |
| `GWS_SERVICE_ACCOUNT_KEY` | 服务账号JSON密钥路径 |
| `GWS_DELEGATED_USER` | 要模拟的用户(服务账号场景) |
| `GWS_DEFAULT_FORMAT` | 默认输出格式(json/ndjson/table) |

Validate Authentication

验证认证状态

bash
python3 scripts/auth_setup_guide.py --validate --json
bash
python3 scripts/auth_setup_guide.py --validate --json

Tests each service endpoint

测试各服务端点


---

---

Workflow 1: Gmail Automation

工作流1:Gmail自动化

Goal: Automate email operations — send, search, label, and filter management.
目标: 自动化邮件操作——发送、搜索、标签管理和过滤规则配置。

Send and Reply

发送与回复

bash
undefined
bash
undefined

Send a new email

发送新邮件

gws gmail users.messages send me --to "client@example.com"
--subject "Proposal" --body "Please find attached..."
--attachment proposal.pdf
gws gmail users.messages send me --to "client@example.com"
--subject "Proposal" --body "Please find attached..."
--attachment proposal.pdf

Reply to a thread

回复线程

gws gmail users.messages reply me --thread-id <THREAD_ID>
--body "Thanks for your feedback..."
gws gmail users.messages reply me --thread-id <THREAD_ID>
--body "Thanks for your feedback..."

Forward a message

转发邮件

gws gmail users.messages forward me --message-id <MSG_ID>
--to "manager@company.com"
undefined
gws gmail users.messages forward me --message-id <MSG_ID>
--to "manager@company.com"
undefined

Search and Filter

搜索与过滤

bash
undefined
bash
undefined

Search emails

搜索邮件

gws gmail users.messages list me --query "from:client@example.com after:2025/01/01" --json
| python3 scripts/output_analyzer.py --count
gws gmail users.messages list me --query "from:client@example.com after:2025/01/01" --json
| python3 scripts/output_analyzer.py --count

List labels

列出标签

gws gmail users.labels list me --json
gws gmail users.labels list me --json

Create a filter

创建过滤规则

gws gmail users.settings.filters create me
--criteria '{"from":"notifications@service.com"}'
--action '{"addLabelIds":["Label_123"],"removeLabelIds":["INBOX"]}'
undefined
gws gmail users.settings.filters create me
--criteria '{"from":"notifications@service.com"}'
--action '{"addLabelIds":["Label_123"],"removeLabelIds":["INBOX"]}'
undefined

Bulk Operations

批量操作

bash
undefined
bash
undefined

Archive all read emails older than 30 days

归档所有30天前已读邮件

gws gmail users.messages list me --query "is:read older_than:30d" --json
| python3 scripts/output_analyzer.py --select "id" --format json
| xargs -I {} gws gmail users.messages modify me {} --removeLabelIds INBOX

---
gws gmail users.messages list me --query "is:read older_than:30d" --json
| python3 scripts/output_analyzer.py --select "id" --format json
| xargs -I {} gws gmail users.messages modify me {} --removeLabelIds INBOX

---

Workflow 2: Drive & Sheets

工作流2:Drive与Sheets

Goal: Manage files, create spreadsheets, configure sharing, and export data.
目标: 管理文件、创建电子表格、配置共享权限和导出数据。

File Operations

文件操作

bash
undefined
bash
undefined

List files

列出文件

gws drive files list --json --limit 50
| python3 scripts/output_analyzer.py --select "name,mimeType,size" --format table
gws drive files list --json --limit 50
| python3 scripts/output_analyzer.py --select "name,mimeType,size" --format table

Upload a file

上传文件

gws drive files create --name "Q1 Report" --upload report.pdf
--parents <FOLDER_ID>
gws drive files create --name "Q1 Report" --upload report.pdf
--parents <FOLDER_ID>

Create a Google Sheet

创建Google Sheet

gws sheets spreadsheets create --title "Budget 2026" --json
gws sheets spreadsheets create --title "Budget 2026" --json

Download/export

下载/导出

gws drive files export <FILE_ID> --mime "application/pdf" --output report.pdf
undefined
gws drive files export <FILE_ID> --mime "application/pdf" --output report.pdf
undefined

Sharing

共享配置

bash
undefined
bash
undefined

Share with user

与用户共享

gws drive permissions create <FILE_ID>
--type user --role writer --emailAddress "colleague@company.com"
gws drive permissions create <FILE_ID>
--type user --role writer --emailAddress "colleague@company.com"

Share with domain (view only)

与域共享(仅查看)

gws drive permissions create <FILE_ID>
--type domain --role reader --domain "company.com"
gws drive permissions create <FILE_ID>
--type domain --role reader --domain "company.com"

List who has access

列出访问权限

gws drive permissions list <FILE_ID> --json
undefined
gws drive permissions list <FILE_ID> --json
undefined

Sheets Data

Sheets数据操作

bash
undefined
bash
undefined

Read a range

读取数据范围

gws sheets spreadsheets.values get <SHEET_ID> --range "Sheet1!A1:D10" --json
gws sheets spreadsheets.values get <SHEET_ID> --range "Sheet1!A1:D10" --json

Write data

写入数据

gws sheets spreadsheets.values update <SHEET_ID> --range "Sheet1!A1"
--values '[["Name","Score"],["Alice",95],["Bob",87]]'
gws sheets spreadsheets.values update <SHEET_ID> --range "Sheet1!A1"
--values '[["Name","Score"],["Alice",95],["Bob",87]]'

Append rows

追加行数据

gws sheets spreadsheets.values append <SHEET_ID> --range "Sheet1!A1"
--values '[["Charlie",92]]'

---
gws sheets spreadsheets.values append <SHEET_ID> --range "Sheet1!A1"
--values '[["Charlie",92]]'

---

Workflow 3: Calendar & Meetings

工作流3:Calendar与会议

Goal: Schedule events, find available times, and generate standup reports.
目标: 安排活动、查找可用时间和生成每日站会报告。

Event Management

活动管理

bash
undefined
bash
undefined

Create an event

创建活动

gws calendar events insert primary
--summary "Sprint Planning"
--start "2026-03-15T10:00:00" --end "2026-03-15T11:00:00"
--attendees "team@company.com"
--location "Conference Room A"
gws calendar events insert primary
--summary "Sprint Planning"
--start "2026-03-15T10:00:00" --end "2026-03-15T11:00:00"
--attendees "team@company.com"
--location "Conference Room A"

List upcoming events

列出即将到来的活动

gws calendar events list primary --timeMin "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
--maxResults 10 --json
gws calendar events list primary --timeMin "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
--maxResults 10 --json

Quick event (natural language)

快速创建活动(自然语言)

gws helpers quick-event "Lunch with Sarah tomorrow at noon"
undefined
gws helpers quick-event "Lunch with Sarah tomorrow at noon"
undefined

Find Available Time

查找可用时间

bash
undefined
bash
undefined

Check free/busy for multiple people

检查多人空闲/忙碌状态

gws helpers find-time
--attendees "alice@co.com,bob@co.com,charlie@co.com"
--duration 60 --within "2026-03-15,2026-03-19" --json
undefined
gws helpers find-time
--attendees "alice@co.com,bob@co.com,charlie@co.com"
--duration 60 --within "2026-03-15,2026-03-19" --json
undefined

Standup Report

站会报告

bash
undefined
bash
undefined

Generate daily standup from calendar + tasks

从Calendar和Tasks生成每日站会报告

gws recipes standup-report --json
| python3 scripts/output_analyzer.py --format table
gws recipes standup-report --json
| python3 scripts/output_analyzer.py --format table

Meeting prep (agenda + attendee info)

会议准备(议程+参会者信息)

gws recipes meeting-prep --event-id <EVENT_ID>

---
gws recipes meeting-prep --event-id <EVENT_ID>

---

Workflow 4: Security Audit

工作流4:安全审计

Goal: Audit Google Workspace security configuration and generate remediation commands.
目标: 审计Google Workspace安全配置并生成修复命令。

Run Full Audit

运行完整审计

bash
undefined
bash
undefined

Full audit across all services

跨所有服务的完整审计

python3 scripts/workspace_audit.py --json
python3 scripts/workspace_audit.py --json

Audit specific services

审计指定服务

python3 scripts/workspace_audit.py --services gmail,drive,calendar
python3 scripts/workspace_audit.py --services gmail,drive,calendar

Demo mode (no gws required)

演示模式(无需gws)

python3 scripts/workspace_audit.py --demo
undefined
python3 scripts/workspace_audit.py --demo
undefined

Audit Checks

审计检查项

AreaCheckRisk
DriveExternal sharing enabledData exfiltration
GmailAuto-forwarding rulesData exfiltration
GmailDMARC/SPF/DKIM recordsEmail spoofing
CalendarDefault sharing visibilityInformation leak
OAuthThird-party app grantsUnauthorized access
AdminSuper admin countPrivilege escalation
Admin2-Step verification enforcementAccount takeover
领域检查内容风险
Drive启用外部共享数据泄露
Gmail自动转发规则数据泄露
GmailDMARC/SPF/DKIM记录邮件伪造
Calendar默认共享可见性信息泄露
OAuth第三方应用授权未授权访问
管理员超级管理员数量权限提升
管理员强制启用两步验证账户接管

Review and Remediate

查看结果与修复

bash
undefined
bash
undefined

Review findings

查看检查结果

python3 scripts/workspace_audit.py --json | python3 scripts/output_analyzer.py
--filter "status=FAIL" --select "area,check,remediation"
python3 scripts/workspace_audit.py --json | python3 scripts/output_analyzer.py
--filter "status=FAIL" --select "area,check,remediation"

Execute remediation (example: restrict external sharing)

执行修复(示例:限制外部共享)

gws drive about get --json # Check current settings
gws drive about get --json # 检查当前设置

Follow remediation commands from audit output

按照审计输出中的修复命令操作


---

---

Python Tools

Python工具

ScriptPurposeUsage
gws_doctor.py
Pre-flight diagnostics
python3 scripts/gws_doctor.py [--json] [--services gmail,drive]
auth_setup_guide.py
Guided auth setup
python3 scripts/auth_setup_guide.py --guide oauth
gws_recipe_runner.py
Recipe catalog & runner
python3 scripts/gws_recipe_runner.py --list [--persona pm]
workspace_audit.py
Security/config audit
python3 scripts/workspace_audit.py [--json] [--demo]
output_analyzer.py
JSON/NDJSON analysis
gws ... --json | python3 scripts/output_analyzer.py --count
All scripts are stdlib-only, support
--json
output, and include demo mode with embedded sample data.

脚本用途使用方式
gws_doctor.py
预检查诊断
python3 scripts/gws_doctor.py [--json] [--services gmail,drive]
auth_setup_guide.py
引导式认证配置
python3 scripts/auth_setup_guide.py --guide oauth
gws_recipe_runner.py
工作流目录与运行器
python3 scripts/gws_recipe_runner.py --list [--persona pm]
workspace_audit.py
安全/配置审计
python3 scripts/workspace_audit.py [--json] [--demo]
output_analyzer.py
JSON/NDJSON分析
gws ... --json | python3 scripts/output_analyzer.py --count
所有脚本仅依赖标准库,支持
--json
输出,并包含带嵌入式示例数据的演示模式。

Best Practices

最佳实践

Security

安全

  1. Use OAuth with minimal scopes — request only what each workflow needs
  2. Store tokens in the system keyring, never in plain text files
  3. Rotate service account keys every 90 days
  4. Audit third-party OAuth app grants quarterly
  5. Use
    --dry-run
    before bulk destructive operations
  1. 使用最小权限范围的OAuth——仅请求每个工作流所需的权限
  2. 将令牌存储在系统密钥环中,切勿存储在明文文件中
  3. 每90天轮换一次服务账号密钥
  4. 每季度审计第三方OAuth应用授权
  5. 在执行批量破坏性操作前使用
    --dry-run

Automation

自动化

  1. Pipe
    --json
    output through
    output_analyzer.py
    for filtering and aggregation
  2. Use recipes for multi-step operations instead of chaining raw commands
  3. Select a persona bundle to scope recipes to your role
  4. Use NDJSON format (
    --format ndjson
    ) for streaming large result sets
  5. Set
    GWS_DEFAULT_FORMAT=json
    in your shell profile for scripting
  1. --json
    输出通过
    output_analyzer.py
    进行过滤和聚合
  2. 使用工作流执行多步骤操作,而非链式调用原始命令
  3. 选择角色包来限定工作流的角色范围
  4. 处理大型结果集时使用NDJSON格式(
    --format ndjson
  5. 在shell配置中设置
    GWS_DEFAULT_FORMAT=json
    以方便脚本编写

Performance

性能

  1. Use
    --fields
    to request only needed fields (reduces payload size)
  2. Use
    --limit
    to cap results when browsing
  3. Use
    --page-all
    only when you need complete datasets
  4. Batch operations with recipes rather than individual API calls
  5. Cache frequently accessed data (e.g., label IDs, folder IDs) in variables

  1. 使用
    --fields
    仅请求所需字段(减少负载大小)
  2. 浏览时使用
    --limit
    限制结果数量
  3. 仅在需要完整数据集时使用
    --page-all
  4. 使用工作流批量操作,而非单个API调用
  5. 将频繁访问的数据(如标签ID、文件夹ID)缓存到变量中

Limitations

限制

ConstraintImpact
OAuth tokens expire after 1 hourRe-auth needed for long-running scripts
API rate limits (per-user, per-service)Bulk operations may hit 429 errors
Scope requirements vary by serviceMust request correct scopes during auth
Pre-v1.0 CLI statusBreaking changes possible between releases
Google Cloud project requiredFree, but requires setup in Cloud Console
Admin API needs admin privilegesSome audit checks require Workspace Admin role
约束影响
OAuth令牌1小时后过期长时间运行的脚本需要重新认证
API速率限制(按用户、按服务)批量操作可能触发429错误
各服务权限范围要求不同认证时必须请求正确的权限范围
CLI处于v1.0前状态版本间可能存在破坏性变更
需要Google Cloud项目免费,但需在Cloud Console中配置
管理员API需要管理员权限部分审计检查需要Workspace管理员角色

Required Scopes by Service

各服务所需权限范围

bash
undefined
bash
undefined

List scopes for specific services

列出指定服务的权限范围

python3 scripts/auth_setup_guide.py --scopes gmail,drive,calendar,sheets

| Service | Key Scopes |
|---------|-----------|
| Gmail | `gmail.modify`, `gmail.send`, `gmail.labels` |
| Drive | `drive.file`, `drive.metadata.readonly` |
| Sheets | `spreadsheets` |
| Calendar | `calendar`, `calendar.events` |
| Admin | `admin.directory.user.readonly`, `admin.directory.group` |
| Tasks | `tasks` |
python3 scripts/auth_setup_guide.py --scopes gmail,drive,calendar,sheets

| 服务 | 核心权限范围 |
|---------|-----------|
| Gmail | `gmail.modify`, `gmail.send`, `gmail.labels` |
| Drive | `drive.file`, `drive.metadata.readonly` |
| Sheets | `spreadsheets` |
| Calendar | `calendar`, `calendar.events` |
| 管理员 | `admin.directory.user.readonly`, `admin.directory.group` |
| Tasks | `tasks` |