SonarSource/sonarqube-cli
GitHub: SonarSource/sonarqube-cli
SonarSource 官方的命令行工具,将 SonarQube 的静态代码质量与安全分析能力直接带入终端,并集成 AI 编码助手的密钥防护钩子。
Stars: 210 | Forks: 8
# SonarQube CLI
[](https://github.com/SonarSource/sonarqube-cli/actions/workflows/build.yml)
[](https://sonarcloud.io/summary/new_code?id=SonarSource_sonarqube-cli)
**在终端中——在代码质量和安全问题进入生产环境之前发现它们。**
SonarQube CLI 将企业级静态分析集成到您的开发工作流中:
- **🔒 密钥检测** — 扫描代码中的硬编码凭证,并防止密钥被发送给 LLM 提供商
- **⚡ 快速反馈循环** — 无需等待 CI/CD 即可对本地更改进行服务端问题检测
- **🤖 AI 辅助修复** — 针对安全漏洞生成修复建议(SonarQube Cloud)
- **🔗 Agent 集成** — 为 Claude Code、GitHub Copilot 和其他 AI 编码工具提供无缝钩子
- **📊 可脚本化** — 通过 JSON 输出以编程方式查询和管理 SonarQube 问题
**独立使用或与以下工具集成:** Git hooks、Claude Code、GitHub Copilot、CI/CD pipelines、自定义自动化
## 文档
- **📘 官方文档:** [docs.sonarsource.com/sonarqube-cli](https://docs.sonarsource.com/sonarqube-cli)
- **🌐 项目网站:** [sonarsource.com/sonarqube/cli](https://sonarsource.com/sonarqube/cli)
- **📖 命令参考:** [sonarsource.com/sonarqube/cli/commands.html](https://sonarsource.com/sonarqube/cli/commands.html)
## 目录
- [文档](#documentation)
- [使用此 CLI 的三种方式](#three-ways-to-use-this-cli)
- [前置条件](#prerequisites)
- [快速开始](#quick-start)
- [第 1 步:安装](#step-1-install)
- [第 2 步:认证](#step-2-authenticate)
- [第 3 步:尝试基本命令](#step-3-try-basic-commands)
- [第 4 步:分析本地更改](#step-4-analyze-local-changes-sonarqube-cloud-only)
- [集成](#integrations)
- [Claude Code 集成](#claude-code-integration)
- [Git Hooks](#git-hooks)
- [GitHub Copilot 集成](#github-copilot-integration)
- [示例输出](#example-outputs)
- [故障排除](#troubleshooting)
- [状态管理](#state-management)
- [卸载](#uninstalling)
- [数据收集](#data-collection)
- [贡献](#contributing)
- [许可证](#license)
## 使用此 CLI 的三种方式
SonarQube CLI 专为三种不同的使用场景而设计:
1. **🤖 Agentic 使用** — 内置对 AI 编码 agent(Claude Code、GitHub Copilot)的支持,提供 pre-tool hooks 以防止密钥被发送给 LLM 提供商
sonar integrate claude -g
# 现在 Claude Code 将在处理您的代码之前自动扫描密钥
2. **🖥️ 交互式 CLI** — 直接在终端中运行命令以扫描代码、检查问题并手动管理 SonarQube 项目
sonar list issues --project my-app
sonar analyze --file file.ext
3. **⚙️ 脚本与自动化** — 集成到脚本中用于报告、仪表板或自动化质量门
# 生成跨所有项目的问题报告:
sonar list projects | jq -r '.projects[].key' | while read project; do
echo "Project: $project"
sonar list issues --project "$project" | jq -r '.issues[].severity' | sort | uniq -c
done
## 前置条件
在安装之前,您需要:
- **SonarQube 访问权限**(选择其一):
- [SonarQube Cloud](https://sonarcloud.io) — 对于开源项目免费,对于私有仓库收费
- SonarQube Server — 自托管实例(v9.9+)
- **操作系统**:Linux (x86-64, ARM64)、macOS (ARM64) 或 Windows (x86-64)
**可选:**
- Git 2.x+,用于 git hook 集成
- Claude Code 或 GitHub Copilot CLI,用于 AI 助手集成
**首次使用 SonarQube?** [创建免费的 SonarQube Cloud 账户](https://sonarcloud.io/sessions/new) — 开源项目无需信用卡。
## 快速开始
### 第 1 步:安装
**Linux/macOS:**
```
curl -o- https://raw.githubusercontent.com/SonarSource/sonarqube-cli/refs/heads/master/user-scripts/install.sh | bash
```
**Windows(在 PowerShell 中):**
```
irm https://raw.githubusercontent.com/SonarSource/sonarqube-cli/refs/heads/master/user-scripts/install.ps1 | iex
```
**验证安装:**
```
sonar --version
# 示例输出:1.0.0
```
**注意:** 您可能需要重启终端才能使 `sonar` 命令可用。
### 第 2 步:认证
连接到 SonarQube Cloud EU(默认):
```
sonar auth login
# 打开浏览器以登录 SonarQube 并生成用户 token
# 完成后返回终端
```
对于 SonarQube Cloud US:
```
sonar auth login --server https://sonarqube.us
```
对于自托管的 SonarQube Server:
```
sonar auth login --server https://sonarqube.mycompany.com
```
**验证认证:**
```
sonar auth status
# 正在验证 token......
# [✓ 已连接]
# Server https://sonarcloud.io
# Org my-org
# Source OS Keychain
```
**对于自动化、CI/CD 和 AI agent**,请通过环境变量传递 token。CLI 会在执行命令时读取它们,因此不会向磁盘或操作系统 keychain 写入任何内容。
首先生成一个 token:SonarQube → My Account → Security → Generate Token。
然后在调用 `sonar` 之前定义以下环境变量(在 CI 中使用您的运行器的 secret 存储,或使用您偏好的本地机制 —— direnv、未跟踪的 `.env` 文件、密码管理器 CLI 等):
- SonarQube Cloud:`SONARQUBE_CLI_TOKEN` + `SONARQUBE_CLI_ORG`
- 自托管 SonarQube Server:`SONARQUBE_CLI_TOKEN` + `SONARQUBE_CLI_SERVER`
导出这些变量后,任何命令无需进一步配置即可运行:
```
sonar list projects
```
必须同时设置这两个变量 —— 如果仅存在 `SONARQUBE_CLI_TOKEN`,CLI 会在 stderr 打印警告并回退到 keychain 凭证,这通常不符合自动化的需求。
切勿提交 token 或将其作为 CLI 参数传递。
### 第 3 步:尝试基本命令
**列出您的项目:**
```
sonar list projects
# {"projects":[{"key":"my-org_my-app","name":"my-app"},
# {"key":"my-org_demo","name":"demo-project"}],
# "paging":{"pageIndex":1,"pageSize":500,"total":2,"hasNextPage":false}}
```
默认输出为 JSON。可以通过管道传递给 `jq` 进行临时过滤,例如 `sonar list projects | jq -r '.projects[].key'`。
**扫描文件中的密钥:**
```
cat > test.js <<'EOF'
const STRIPE_KEY = "sk_live_";
EOF
sonar analyze secrets test.js
# Sonar Secrets CLI - BETA (2.43.0.11106)
# 正在尝试向 SonarQube Server 或 Cloud 进行身份验证,以启用完整功能
# 身份验证成功
# 正在运行分析...
# 发现 1 个 secret
# Stripe API Key
# 文件:test.js
# 位置:[1:21-1:53]
# Secret:sk_*****************************
# ❌ 发现 secrets (227ms)
# 💡 移除报告的 secret,然后重新运行扫描。
```
当发现密钥时,命令将以退出代码 `51` 退出。
**检查项目中的问题:**
```
sonar list issues --project my-org_my-app --format table --page-size 3
# SEVERITY | RULE | MESSAGE | FILE
# ---------------------------------------------------------------------------------------------------------------
# CRITICAL | typescript:S3776 | 重构此函数以降低其 Cognitive Complexity | src/preview.tsx:17
# CRITICAL | typescript:S2004 | 重构此代码,使嵌套函数不超过 4... | src/Preview.tsx:235
# CRITICAL | typescript:S3776 | 重构此函数以降低其 Cognitive Complexity | src/Description.tsx:43
```
支持的格式:`json`(默认)、`table`、`toon`、`csv`。
### 第 4 步:分析本地更改(仅限 SonarQube Cloud)
```
cd your-project-directory
sonar analyze --file file.ext
# 分析未提交的更改以查找新 issues
# 仅显示您在更改中引入的 issues
```
**常用选项:**
```
sonar analyze --file src/myfile.ts # Analyze a specific file
sonar analyze --base main # Analyze changes vs main branch
sonar analyze --branch feature-xyz # Set branch context
```
## 集成
### Claude Code 集成
**全局设置**(hooks 应用于所有 Claude Code 会话):
```
sonar auth login
sonar integrate claude -g
```
**特定项目设置**(hooks 仅应用于此项目):
```
cd your-project
sonar auth login
sonar integrate claude --project my-org_my-project
```
这将安装:
- **用于密钥扫描的 Pre-tool-use hook** — 防止硬编码的凭证被发送给 LLM 提供商
- **SonarQube Agentic Analysis 集成** — 在您的工作流中进行服务端代码质量分析
- **Model Context Protocol (MCP) 服务器** — 直接从 Claude Code 访问 SonarQube 数据
### Git Hooks
**Pre-commit hook**(在每次 commit 前扫描暂存文件):
```
sonar integrate git --hook pre-commit
```
**Pre-push hook**(在每次 push 前扫描已 commit 的文件):
```
sonar integrate git --hook pre-push
```
**全局 git hooks**(应用于所有代码仓库):
```
sonar integrate git --hook pre-commit --global
```
**用于 CI/CD 或自动化**(非交互模式):
```
sonar integrate git --hook pre-commit --non-interactive
# 跳过所有提示,遇到错误时快速失败
```
### GitHub Copilot 集成
**全局设置:**
```
sonar auth login
sonar integrate copilot -g
```
**特定项目设置:**
```
cd your-project
sonar auth login
sonar integrate copilot --project my-org_my-project
```
这将安装:
- **用于密钥扫描的 Pre-tool-use hook** — 防止硬编码的凭证被发送给 LLM 提供商
- **SonarQube Agentic Analysis 集成** — 在您的工作流中进行服务端代码质量分析
- **Model Context Protocol (MCP) 服务器** — 直接从 Copilot 访问 SonarQube 数据
## 示例输出
### 扫描密钥
```
$ sonar analyze secrets src/config.ts
sonar-secrets 2.43.0.11106 is already installed (latest)
Sonar Secrets CLI - BETA (2.43.0.11106)
Trying to authenticate to SonarQube Server or Cloud, in order to enable complete functionality
Authentication successful
Running analysis...
Found 1 secret
Stripe API Key
File: src/config.ts
Location: [5:20-5:52]
Secret: sk_*****************************
❌ Secrets found (227ms)
💡 Remove the reported secret, then rerun the scan.
```
退出代码:未发现密钥时为 `0`,发现至少一个密钥时为 `51`。
### 列出问题
`sonar list issues` 默认发出 JSON;传递 `--format table` 以获取如下人类可读的视图。
```
$ sonar list issues --project my-org_my-app --severities CRITICAL,BLOCKER --page-size 3 --format table
SEVERITY | RULE | MESSAGE | FILE
-------------------------------------------------------------------------------------------------------------------------
CRITICAL | typescript:S3776 | Refactor this function to reduce its Cognitive Complexity from 26 to the 15 allowed. | code/addons/a11y/src/preview.tsx:17
CRITICAL | typescript:S2004 | Refactor this code to not nest functions more than 4 levels deep. | code/addons/docs/src/blocks/components/Preview.tsx:235
CRITICAL | typescript:S3776 | Refactor this function to reduce its Cognitive Complexity from 23 to the 15 allowed. | code/addons/vitest/src/components/Description.tsx:43
```
### 分析本地更改
```
$ sonar analyze
SonarQube Agentic Analysis: no files in the change set to analyze.
```
当存在针对配置了 SonarQube Cloud Agentic Analysis 的项目的暂存更改时,分析器会报告该更改集引入的新问题,其格式与可通过 `--format` 选择的 `text`/`json` 格式相同。
### 针对 LLM 优化的输出格式
对于 AI 编码助手,请使用 `--format toon` — 一种 token 高效且带有 YAML 风格的相同 JSON payload 编码:
```
$ sonar list issues --project my-org_my-app --severities BLOCKER --page-size 1 --format toon
total: 88
p: 1
ps: 1
paging:
pageIndex: 1
pageSize: 1
total: 88
issues[1]:
- key: AZ0avojpNWh-T1cKsujg
rule: "typescript:S3516"
severity: BLOCKER
component: "my-org_my-app:src/ConfigFile.ts"
project: my-org_my-app
line: 377
message: "Refactor this function to not always return the same value."
type: CODE_SMELL
```
此格式专为 LLM 解析而设计,可与 Claude Code、GitHub Copilot 或自定义 AI 工作流结合使用。
## 故障排除
### "未找到 Project key"
**症状:** `Error: Project 'my-project' not found`
**原因:** 使用了项目显示名称而不是项目 key。
**解决方案:** 使用 `sonar list projects` 的 JSON 输出中的确切项目 key:
```
# 找到正确的 key:
sonar list projects -q my-project
# {"projects":[{"key":"my-org_my-project","name":"my-project"}],
# "paging":{"pageIndex":1,"pageSize":500,"total":1,"hasNextPage":false}}
# 或者,仅获取 keys:
sonar list projects -q my-project | jq -r '.projects[].key'
# 在后续命令中使用 key 值(而不是 name):
sonar list issues --project my-org_my-project
```
### "No issues found" 但 SonarQube Web UI 中存在问题
**原因:** 项目尚未被扫描,或者您检查的分支有误。
**解决方案:**
1. 验证您的项目在 SonarQube 中是否至少完成过一次扫描
2. 检查您是否认证到了正确的组织:
sonar auth status
3. 对于特定分支的问题,请指定分支:
sonar list issues --project my-org_my-app --branch feature-xyz
### "Authentication failed" 或 token 错误
**症状:** `Error: Invalid token` 或浏览器认证失败
**解决方案:** 使用基于 token 的认证:
1. 转到 SonarQube → My Account → Security → Generate Token
2. 复制生成的 token
3. 使用以下环境变量(在从新终端运行命令之前全局设置它们):
SONARQUBE_CLI_TOKEN=YOUR_TOKEN
SONARQUBE_CLI_SERVER=https://sonarcloud.io # 或您的 SonarQube Server URL
SONARQUBE_CLI_ORG=your-org-key # 仅限 SonarQube Cloud
对于 SonarQube Cloud,确保您使用了正确的区域:
- EU:`https://sonarcloud.io`
- US:`https://sonarqube.us`
### `sonar analyze` 提示 "Not a git repository"
**原因:** `sonar analyze` 需要 git 来检测更改。
**解决方案:**
- 在 git 仓库内部运行:
cd your-project
sonar analyze
- 或者改为分析特定文件:
sonar analyze --file src/myfile.ts
### 安装后 Git hook 未运行
**症状:** 安装了 pre-commit hook 但在 `git commit` 时未执行
**解决方案:**
1. 检查 hook 文件是否存在且具有可执行权限:
ls -la .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
2. 手动测试 hook:
.git/hooks/pre-commit
3. 对于全局 hooks,验证 git 配置:
git config --global core.hooksPath
# 应该显示:~/.sonar/git-hooks(或类似内容)
### 安装后提示 "Command not found: sonar"
**症状:** 运行安装程序后,终端无法识别 `sonar`
**解决方案:**
1. **重启终端**(需要重新加载 PATH)
2. 如果仍然无效,请手动添加到 PATH:
**Linux/macOS** — 添加到 `~/.bashrc` 或 `~/.zshrc`:
export PATH="$HOME/.local/share/sonarqube-cli/bin:$PATH"
然后重新加载:`source ~/.bashrc`(或 `~/.zshrc`)
**Windows** — 安装程序应该已经自动更新了 PATH。请尝试:
- 打开一个新的 PowerShell 窗口
- 如果问题仍然存在,请重启计算机
3. 验证可执行文件是否存在:
# Linux/macOS:
ls -la ~/.local/share/sonarqube-cli/bin/sonar
# Windows (PowerShell):
ls $env:LOCALAPPDATA\sonarqube-cli\bin\sonar.exe
### 密钥扫描出现误报
**症状:** `sonar analyze secrets` 标记了测试数据或示例代码
**解决方案:**
为避免遗漏真实凭证,密钥扫描被特意设计得非常敏感。对于测试文件:
1. **使用明显虚假的值:**
// ✅ 不会被标记:
const API_KEY = "test_fake_key_for_unit_tests";
const TOKEN = "-token-12345";
// ❌ 可能会被标记:
const API_KEY = "sk_live_abc123xyz789";
2. **将测试密钥存储在被忽略的文件中:**
- `.env.test` 文件通常默认被排除在外
- 将看起来真实的测试数据保留在 `src/` 之外的 fixture 文件中
3. **对于合理的例外情况:** 考虑添加注释说明该值安全的原因,或者甚至在测试中也使用环境变量。
### 仍然遇到问题?
- **搜索现有 issue:** [GitHub Issues](https://github.com/SonarSource/sonarqube-cli/issues)
- [新建 Issue](https://github.com/SonarSource/sonarqube-cli/issues/new/choose)
请在报告中包含:
- `sonar --version` 的输出
- 完整的错误信息(已隐去敏感信息)
- 您运行的命令
- 操作系统及版本
- 对于认证问题:Server URL(SonarQube Cloud 还是 Server)
## 状态管理
有关更多信息,请参见[状态管理](./docs/state-management.md)。
## 卸载
### Linux/Mac OS
1. 删除 `~/.local/share/sonarqube-cli/` 文件夹。
2. 从您的 `~/.bashrc` 或 `~/.zshrc` 文件中移除 `export PATH="$HOME/.local/share/sonarqube-cli/bin:$PATH"`。
### Windows
1. 删除 `%localappdata%\sonarqube-cli\` 文件夹。
2. 从 `PATH` 用户级环境变量中移除此文件夹。
## 数据收集
SonarQube CLI 会收集匿名的使用数据和错误报告,以帮助改进产品。
**遥测:** 匿名的命令使用统计信息将发送给 SonarSource。
**错误报告:** 未处理的异常将报告给 [Sentry](https://sentry.io),以帮助我们识别和修复崩溃。
两者默认均已启用,并共享同一个停用开关。要禁用所有数据收集:
```
sonar config telemetry --disabled
```
您还可以设置 `DO_NOT_TRACK=1` 环境变量,在不更改已保存配置的情况下为当前会话禁用遥测。
不会传输任何个人身份识别信息。
## 贡献
我们不接受此项目的外部 pull request。这与您的更改质量无关——将所有更改集中在一处,能让我们妥善跟踪、规划、排定优先级并测试进入 CLI 的所有内容。
这并不意味着我们不想听取您的意见——我们非常乐意。如果您遇到了 bug 或有好的想法,请[提出 GitHub Issue](https://github.com/SonarSource/sonarqube-cli/issues/new/choose),剩下的事交给我们处理。
源代码是公开的,因此欢迎您 fork、阅读和进行试验。如果您想从源代码构建 CLI,请参见 [CONTRIBUTING.md](./CONTRIBUTING.md)。
## 许可证
版权所有 SonarSource Sàrl。
SonarQube CLI 基于 [GNU Lesser General Public License, Version 3.0,](http://www.gnu.org/licenses/lgpl.txt) 发布。
标签:AI辅助, Homebrew安装, SonarQube, StruQ, 云安全监控, 代码安全, 文档结构分析, 机密检测, 漏洞枚举, 自动化攻击, 静态分析