<!-- title: Claude Code安装配置与权限体系全指南 -->

# Claude Code 安装配置与权限体系全指南

> **学习目标**：掌握 Claude Code 在 macOS / Linux / Windows 三大平台的完整安装流程，理解 `settings.json` 四层配置作用域，精通权限规则语法与六种权限模式，学会用 Hooks 扩展安全边界，最终为团队构建一套可复现、可管控的 Claude Code 开发环境。
>
> **适用人群**：刚接触 Claude Code 的开发者、需要在团队中推行 AI 编码工具的技术负责人、关注安全合规的 DevOps 工程师。

---

## 一、前置条件

| 项目 | 最低要求 |
|------|---------|
| **操作系统** | macOS 13.0+、Ubuntu 20.04+、Debian 10+、Alpine 3.19+、Windows 10 1809+ |
| **硬件** | 4 GB+ RAM，x64 或 ARM64 处理器 |
| **网络** | 需要互联网连接（支持 HTTP 代理） |
| **Shell** | Bash / Zsh / PowerShell / CMD |
| **地区** | Anthropic 支持的国家或地区 |
| **可选依赖** | Git（强烈推荐）、Node.js 18+（仅 npm 安装方式需要） |

---

## 二、安装：四种方式对比

### 2.1 方式对比总览

```mermaid
flowchart TD
    A[选择安装方式] --> B{你的平台?}
    B -->|macOS / Linux / WSL| C[Native Install 推荐]
    B -->|macOS| D[Homebrew]
    B -->|Windows 原生| E[WinGet / PowerShell]
    B -->|需要版本锁定| F[npm 安装]

    C --> C1["curl -fsSL https://claude.ai/install.sh | bash"]
    D --> D1["brew install --cask claude-code"]
    E --> E1["winget install Anthropic.ClaudeCode"]
    F --> F1["npm install -g @anthropic-ai/claude-code"]

    C1 --> G[✅ 自动后台更新]
    D1 --> H[⚠️ 需手动 brew upgrade]
    E1 --> H
    F1 --> I[⚠️ 需手动 npm update]

    style C fill:#d4edda,stroke:#28a745
    style G fill:#d4edda,stroke:#28a745
```

### 2.2 Native Install（推荐）

**macOS / Linux / WSL**：

```bash
curl -fsSL https://claude.ai/install.sh | bash
```

**Windows PowerShell**：

```powershell
irm https://claude.ai/install.ps1 | iex
```

**Windows CMD**：

```cmd
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
```

> **自动更新**：Native 安装会在后台自动更新，保持最新版本。这是 Anthropic 官方推荐的方式。

### 2.3 Homebrew（macOS）

```bash
# 稳定版（约滞后一周，跳过有重大回归的版本）
brew install --cask claude-code

# 最新版（发布即更新）
brew install --cask claude-code@latest
```

```bash
# 手动更新
brew upgrade claude-code
```

### 2.4 WinGet（Windows 原生）

```powershell
winget install Anthropic.ClaudeCode
```

```powershell
# 手动更新
winget upgrade Anthropic.ClaudeCode
```

> **Windows 原生 vs WSL**：如果项目在 Windows 文件系统上用原生安装；项目在 Linux 文件系统上用 WSL。原生 Windows 不支持沙箱功能，WSL 支持完整功能集。

### 2.5 npm 安装（需要版本控制时）

```bash
npm install -g @anthropic-ai/claude-code
```

```bash
# 安装特定版本
npm install -g @anthropic-ai/claude-code@1.0.25

# 锁定最低版本（package.json）
"@anthropic-ai/claude-code": ">=1.0.25"
```

### 2.6 Linux 包管理器

```bash
# Debian / Ubuntu
curl -fsSL https://claude.ai/install.sh | bash   # 自动检测 apt

# Fedora / RHEL
curl -fsSL https://claude.ai/install.sh | bash   # 自动检测 dnf

# Alpine
curl -fsSL https://claude.ai/install.sh | bash   # 自动检测 apk
```

### 2.7 验证安装

```bash
claude --version
```

预期输出：

```
Claude Code v1.0.xx
```

---

## 三、认证：五种身份验证方式

```mermaid
flowchart LR
    A[认证方式选择] --> B[Anthropic Account<br/>默认 · 最简单]
    A --> C[API Key<br/>适合企业用户]
    A --> D[Amazon Bedrock<br/>AWS 用户]
    A --> E[Google Vertex AI<br/>GCP 用户]
    A --> F[Azure Foundry<br/>微软云用户]

    B --> B1[浏览器登录]
    C --> C1["export ANTHROPIC_API_KEY=sk-..."]
    D --> D1[配置 AWS credentials]
    E --> E1[配置 gcloud auth]
    F --> F1[配置 Azure credentials]
```

### 3.1 Anthropic 账户登录（默认）

```bash
claude
# 首次启动自动引导浏览器登录
```

### 3.2 API Key 认证

```bash
export ANTHROPIC_API_KEY="sk-ant-api03-..."
claude
```

持久化到 Shell 配置：

```bash
# ~/.bashrc 或 ~/.zshrc
echo 'export ANTHROPIC_API_KEY="sk-ant-api03-..."' >> ~/.zshrc
source ~/.zshrc
```

### 3.3 Amazon Bedrock

```bash
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1
export AWS_ACCESS_KEY_ID=AKIA...
export AWS_SECRET_ACCESS_KEY=...
claude
```

### 3.4 Google Vertex AI

```bash
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=us-east5
export ANTHROPIC_VERTEX_PROJECT_ID=my-project-id
gcloud auth application-default login
claude
```

### 3.5 常见认证问题

| 问题 | 原因 | 解决方案 |
|------|------|---------|
| `Authentication failed` | API Key 过期或无效 | 检查 Key 前缀是否为 `sk-ant-` |
| `Rate limit exceeded` | 账户配额耗尽 | 升级计划或等待重置 |
| `Country not supported` | 地区不在支持列表 | 使用代理或 API Key 方式 |
| `npm install 权限错误` | 全局目录不可写 | 使用 Native Install 或修复 npm prefix |

---

## 四、配置体系：四层作用域

Claude Code 的配置系统类似 CSS 层叠规则——**更具体的设置总是覆盖更一般的**。

```mermaid
flowchart BT
    A["User 作用域<br/>~/.claude/settings.json<br/>个人全局偏好"] --> B["Project 作用域<br/>.claude/settings.json<br/>团队共享配置"]
    B --> C["Local 作用域<br/>.claude/settings.local.json<br/>个人项目覆盖"]
    C --> D["Managed 作用域<br/>最高优先级 · 不可覆盖<br/>企业 IT 部署"]
    D --> E["命令行参数<br/>临时会话覆盖"]

    style D fill:#f8d7da,stroke:#dc3545
    style E fill:#fff3cd,stroke:#ffc107
```

### 4.1 四层作用域详解

| 作用域 | 文件位置 | 影响范围 | 是否共享 |
|--------|---------|---------|---------|
| **Managed** | 服务器/MDM/注册表 | 所有用户 | IT 部署，不可覆盖 |
| **User** | `~/.claude/settings.json` | 你的所有项目 | 不共享 |
| **Project** | `.claude/settings.json` | 项目所有协作者 | 提交到 Git |
| **Local** | `.claude/settings.local.json` | 仅你在此项目 | Git 自动忽略 |

### 4.2 优先级规则

```
命令行参数 > Managed > Local > Project > User
```

**示例**：如果 User 设置 `spinnerTipsEnabled: true`，Project 设置 `spinnerTipsEnabled: false`，最终生效的是 **false**（Project 覆盖 User）。

### 4.3 实战：创建你的第一套配置

**步骤 1：创建全局用户配置**

```json
// ~/.claude/settings.json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(git log:*)",
      "Bash(git diff:*)",
      "Bash(git status:*)",
      "Bash(npm test:*)",
      "Bash(npm run lint:*)"
    ],
    "deny": [
      "Bash(rm -rf /*)",
      "Bash(rm -rf ~/*)"
    ]
  },
  "spinnerTipsEnabled": true,
  "preferredNotifChannel": "iterm2"
}
```

**步骤 2：创建项目级团队配置**

```json
// .claude/settings.json（提交到 Git）
{
  "permissions": {
    "allow": [
      "Bash(npm run build:*)",
      "Bash(npm run test:*)",
      "Bash(docker compose:*)",
      "Edit",
      "Write"
    ],
    "deny": [
      "Bash(rm -rf:*)"
    ]
  },
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $CLAUDE_FILE_PATH"
          }
        ]
      }
    ]
  }
}
```

**步骤 3：创建个人本地覆盖**

```json
// .claude/settings.local.json（不提交 Git）
{
  "permissions": {
    "allow": [
      "Bash(kubectl:*)",
      "Bash(aws:*)"
    ]
  },
  "model": "claude-sonnet-4-6"
}
```

---

## 五、权限体系：从入门到精通

### 5.1 权限模式（六种）

Claude Code 提供六种权限模式，通过 `defaultMode` 或 CLI 标志控制：

| 模式 | 说明 | 适用场景 |
|------|------|---------|
| `default` | 标准模式：首次使用工具时逐个确认 | 新手入门、安全优先 |
| `acceptEdits` | 自动接受文件编辑和常见文件系统命令（mkdir, touch, mv, cp） | 日常开发 |
| `plan` | Plan Mode：只读探索，不修改源文件 | 代码审查、架构调研 |
| `auto` | 自动批准工具调用，后台验证动作是否与请求一致 | 自主编码（研究预览） |
| `dontAsk` | 自动拒绝未预批准的工具调用 | CI/CD 流水线 |
| `bypassPermissions` | 跳过所有权限提示（根目录/主目录删除仍需确认） | 容器/VM 隔离环境 |

**设置方式**：

```json
// settings.json
{
  "defaultMode": "acceptEdits"
}
```

```bash
# CLI 临时覆盖
claude --mode auto
claude --dangerously-skip-permissions  # 等同于 bypassPermissions
```

### 5.2 权限规则语法

权限规则格式：`Tool` 或 `Tool(specifier)`

**规则求值顺序**：`deny → ask → allow`，**最先匹配的规则生效**，所以 deny 永远优先。

```mermaid
flowchart LR
    A[工具调用请求] --> B{匹配 deny?}
    B -->|是| C[❌ 拒绝/隐藏]
    B -->|否| D{匹配 ask?}
    D -->|是| E[🔔 弹出确认]
    D -->|否| F{匹配 allow?}
    F -->|是| G[✅ 自动批准]
    F -->|否| E

    style C fill:#f8d7da,stroke:#dc3545
    style G fill:#d4edda,stroke:#28a745
    style E fill:#fff3cd,stroke:#ffc107
```

#### 5.2.1 匹配所有用法

```json
{
  "permissions": {
    "allow": ["Bash"],
    "deny": ["WebFetch"]
  }
}
```

- `Bash` → 允许所有 Bash 命令
- `WebFetch` → 完全禁止网页抓取（工具从上下文中移除）

#### 5.2.2 精细匹配：specifier 语法

```json
{
  "permissions": {
    "allow": [
      "Bash(npm run build)",
      "Bash(npm test)",
      "Bash(git commit*)",
      "Read(./src/**)",
      "WebFetch(domain:docs.python.org)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Read(./.env)",
      "Edit(./.env)"
    ]
  }
}
```

| 规则 | 效果 |
|------|------|
| `Bash(npm run build)` | 精确匹配该命令 |
| `Bash(git commit*)` | 通配符匹配所有 git commit 变体 |
| `Read(./src/**)` | 允许读取 src 下所有文件 |
| `WebFetch(domain:docs.python.org)` | 仅允许抓取指定域名 |
| `Read(./.env)` | 禁止读取 .env 文件 |

#### 5.2.3 Bash 规则特殊行为

**复合命令**：`&&`、`||`、`;`、`|` 连接的命令，每部分独立匹配。

```json
{
  "permissions": {
    "allow": ["Bash(npm run build)"],
    "deny": ["Bash(rm *)"]
  }
}
```

`npm run build && rm -rf dist` → 被拒绝（`rm` 部分匹配 deny 规则）。

**进程包装器**：`npx`、`bunx` 等会检查实际执行的子命令。

```json
{
  "permissions": {
    "allow": ["Bash(npx jest)"]
  }
}
```

`npx jest` → 允许。`npx rm -rf /` → 拒绝。

**只读命令**：以下命令无需权限确认：
- `cat`, `head`, `tail`, `ls`, `find`, `grep`, `rg`, `wc`, `sort`, `uniq`
- `git log`, `git diff`, `git status`, `git branch --list`
- `echo`, `pwd`, `which`, `env`

#### 5.2.4 其他工具的权限规则

| 工具 | specifier 示例 | 说明 |
|------|---------------|------|
| `Read` | `Read(./src/**)` | 文件读取 |
| `Edit` | `Edit(./src/**/*.ts)` | 文件编辑 |
| `Write` | `Write(./dist/**)` | 文件写入 |
| `WebFetch` | `WebFetch(domain:api.example.com)` | 网页抓取 |
| `Agent` | `Agent` | 子代理 |
| `MCP(server:tool)` | `MCP(github:create_issue)` | MCP 工具 |

### 5.3 实战场景：构建安全权限配置

#### 场景 1：前端项目安全配置

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(npm *)",
      "Bash(node *)",
      "Bash(npx *)",
      "Bash(git *)",
      "Edit",
      "Write"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Read(./.env.production)",
      "Edit(./.env.production)"
    ]
  }
}
```

#### 场景 2：只读代码审查模式

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(git log*)",
      "Bash(git diff*)",
      "Bash(git show*)"
    ],
    "deny": [
      "Edit",
      "Write",
      "Bash"
    ]
  },
  "defaultMode": "plan"
}
```

#### 场景 3：CI/CD 流水线配置

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Edit",
      "Write",
      "Bash(npm *)",
      "Bash(git *)"
    ]
  },
  "defaultMode": "dontAsk"
}
```

---

## 六、Hooks：事件驱动的安全扩展

Hooks 允许你在 Claude Code 执行工具操作前后运行自定义脚本，实现权限系统无法覆盖的精细控制。

### 6.1 Hooks 生命周期

```mermaid
sequenceDiagram
    participant U as 用户
    participant C as Claude Code
    participant H as Hook 脚本
    participant T as 工具

    U->>C: 发起请求
    C->>C: 准备调用工具
    C->>H: PreToolUse Hook
    H-->>C: approve / deny / 修改参数
    alt Hook 批准
        C->>T: 执行工具
        T-->>C: 返回结果
        C->>H: PostToolUse Hook
        H-->>C: 处理完成
    else Hook 拒绝
        C-->>U: 报告被拒绝
    end
    C->>H: Notification Hook（异步通知）
    C->>H: Stop Hook（会话结束时）
```

### 6.2 Hook 类型

| Hook 类型 | 触发时机 | 用途 |
|-----------|---------|------|
| `PreToolUse` | 工具调用前 | 拦截、修改、记录 |
| `PostToolUse` | 工具调用后 | 格式化、验证、通知 |
| `Notification` | 通知事件时 | 桌面通知、Webhook |
| `Stop` | 会话结束时 | 清理、汇总 |

### 6.3 Hook 环境变量

Hook 脚本执行时自动获得以下环境变量：

| 变量 | 说明 |
|------|------|
| `$CLAUDE_TOOL_NAME` | 被调用的工具名称 |
| `$CLAUDE_FILE_PATH` | 操作的文件路径（Read/Edit/Write） |
| `$CLAUDE_SESSION_ID` | 当前会话 ID |
| `$CLAUDE_COMMAND` | Bash 命令内容 |

### 6.4 实战 Hook 配置

#### Hook 1：自动代码格式化

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $CLAUDE_FILE_PATH 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

#### Hook 2：敏感文件保护

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "case \"$CLAUDE_FILE_PATH\" in *.env*|*secret*|*credential*) exit 2;; *) exit 0;; esac"
          }
        ]
      }
    ]
  }
}
```

> **exit 2** = 拒绝操作，**exit 0** = 批准，**exit 1** = 错误。

#### Hook 3：操作审计日志

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"[$(date -Iseconds)] BASH: $CLAUDE_COMMAND\" >> ~/.claude/audit.log"
          }
        ]
      }
    ]
  }
}
```

---

## 七、.claude 目录结构全解析

```mermaid
flowchart TD
    ROOT[".claude/ 目录"] --> A["settings.json<br/>团队共享配置（提交 Git）"]
    ROOT --> B["settings.local.json<br/>个人本地配置（Git 忽略）"]
    ROOT --> C["CLAUDE.md<br/>项目级指令文件"]
    ROOT --> D["commands/<br/>自定义斜杠命令"]
    ROOT --> E["agents/<br/>自定义子代理"]
    ROOT --> F["skills/<br/>自动触发技能"]
    ROOT --> G["hooks/<br/>Hook 脚本文件"]
    ROOT --> H["workflows/<br/>工作流脚本"]
    ROOT --> I["memory/<br/>持久化记忆文件"]
    ROOT --> J["worktrees/<br/>Git 工作树"]

    style ROOT fill:#e7f3ff,stroke:#0066cc
    style A fill:#d4edda,stroke:#28a745
    style B fill:#fff3cd,stroke:#ffc107
```

### 7.1 初始化项目

```bash
# 方法 1：CLI 初始化
cd my-project
claude init

# 方法 2：手动创建
mkdir -p .claude/commands .claude/agents
touch .claude/settings.json
touch .claude/settings.local.json
echo ".claude/settings.local.json" >> .gitignore
```

### 7.2 完整 .claude/settings.json 示例

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(npm *)",
      "Bash(node *)",
      "Bash(npx *)",
      "Bash(git *)",
      "Bash(docker *)",
      "Edit",
      "Write"
    ],
    "deny": [
      "Bash(rm -rf /*)",
      "Bash(sudo *)",
      "Bash(curl * | bash)"
    ]
  },
  "defaultMode": "acceptEdits",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "case \"$CLAUDE_FILE_PATH\" in *.env*|*.key|*secret*) exit 2;; *) exit 0;; esac"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
          }
        ]
      }
    ]
  },
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}
```

---

## 八、企业部署：Managed Settings

对于需要集中管控的组织，Claude Code 支持 Managed Settings——**最高优先级，不可被用户或项目配置覆盖**。

### 8.1 部署方式

| 平台 | 部署机制 |
|------|---------|
| **macOS** | `com.anthropic.claudecode` managed preferences domain，通过 Jamf/Kandji 等 MDM 推送配置描述文件 |
| **Windows** | `HKLM\SOFTWARE\Policies\ClaudeCode` 注册表键，`Settings` 值包含 JSON（通过 GPO 部署） |
| **Linux** | `/etc/claude-code/managed-settings.json` 文件 |
| **服务器** | Anthropic Admin Console 远程推送 |

### 8.2 典型企业策略

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(npm test*)",
      "Bash(npm run lint*)",
      "Edit",
      "Write"
    ],
    "deny": [
      "Bash(sudo *)",
      "Bash(rm -rf *)",
      "Bash(curl * | bash)",
      "Bash(chmod 777*)",
      "WebFetch"
    ],
    "disableBypassPermissionsMode": "disable",
    "disableAutoMode": "disable"
  },
  "allowedModels": ["claude-sonnet-4-6"],
  "blockSensitiveFiles": true
}
```

> `disableBypassPermissionsMode: "disable"` 确保任何用户都无法使用 `--dangerously-skip-permissions` 绕过权限。

---

## 九、完整实战：从安装到安全配置

### 9.1 场景描述

假设你是一个 5 人前端团队的 Tech Lead，需要为团队搭建 Claude Code 环境。项目使用 React + TypeScript + npm。

### 9.2 步骤 1：安装

每个团队成员执行：

```bash
# macOS
curl -fsSL https://claude.ai/install.sh | bash

# 验证
claude --version
```

### 9.3 步骤 2：认证

```bash
claude
# 浏览器打开 → 登录 Anthropic 账户 → 完成认证
```

### 9.4 步骤 3：初始化项目配置

```bash
cd my-react-project
claude init
```

### 9.5 步骤 4：创建团队共享 settings.json

```json
// .claude/settings.json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(npm *)",
      "Bash(node *)",
      "Bash(npx *)",
      "Bash(git *)",
      "Edit",
      "Write"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Read(./.env.local)",
      "Edit(./.env.production)"
    ]
  },
  "defaultMode": "acceptEdits",
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

### 9.6 步骤 5：提交配置到 Git

```bash
git add .claude/settings.json
git commit -m "feat: add shared Claude Code configuration"
git push
```

### 9.7 步骤 6：每个成员拉取并验证

```bash
git pull
claude
# 尝试: "帮我修复 src/App.tsx 中的 TypeScript 错误"
# 预期: 自动格式化 + 无需手动确认编辑权限
```

### 9.8 验证清单

```mermaid
flowchart TD
    A[验证安装] --> B["claude --version ✅"]
    B --> C[验证认证]
    C --> D["启动 claude 无报错 ✅"]
    D --> E[验证权限]
    E --> F["尝试编辑文件 → 自动批准 ✅"]
    F --> G[验证 Hooks]
    G --> H["编辑文件后自动 prettier ✅"]
    H --> I[验证安全]
    I --> J["尝试 rm -rf → 被拒绝 ✅"]
    J --> K[🎉 配置完成]

    style K fill:#d4edda,stroke:#28a745
```

---

## 十、常见问题排查

### 10.1 安装问题

| 症状 | 排查命令 | 解决方案 |
|------|---------|---------|
| `command not found: claude` | `which claude` | 重新安装或检查 PATH |
| `npm EACCES` | `npm config get prefix` | 使用 Native Install 或修复 npm 全局目录权限 |
| `install.sh 校验失败` | `sha256sum $(which claude)` | 重新下载安装脚本 |
| WSL 启动报错 | `echo $WSL_DISTRO_NAME` | 确保 WSL 2 + Ubuntu 20.04+ |

### 10.2 权限问题

| 症状 | 原因 | 解决方案 |
|------|------|---------|
| 每次都弹确认 | 未配置 `allow` 规则 | 添加到 `permissions.allow` |
| 配置了但还弹确认 | 规则语法错误 | 检查 specifier 是否精确匹配 |
| deny 规则不生效 | allow 在 deny 之前 | deny 始终优先——检查是否有拼写错误 |
| Hook 脚本不执行 | 脚本无执行权限 | `chmod +x your-hook.sh` |

### 10.3 配置不生效排查

```bash
# 查看当前所有生效的权限
claude /permissions

# 检查 settings.json 语法
cat .claude/settings.json | python3 -m json.tool

# 查看配置层级
echo "User:  ~/.claude/settings.json"
echo "Proj:  .claude/settings.json"
echo "Local: .claude/settings.local.json"
```

---

## 十一、CLI 常用命令速查

```bash
# 启动交互式会话
claude

# 指定模式启动
claude --mode plan          # 只读计划模式
claude --mode auto          # 自主模式
claude --mode acceptEdits   # 自动接受编辑

# 非交互模式（管道/脚本）
claude -p "解释这个函数的作用" < src/utils.ts
echo "修复 lint 错误" | claude -p

# 会话管理
claude --resume              # 恢复上次会话
claude --continue            # 继续上次对话

# 更新
claude update                # 手动检查更新

# 配置
claude config                # 打开配置 UI
claude /permissions          # 管理权限规则

# 版本信息
claude --version
claude --changelog
```

---

## 十二、安全最佳实践清单

1. **永远不要**将 `bypassPermissions` 模式用于日常开发
2. **始终**将 `.claude/settings.local.json` 加入 `.gitignore`
3. **始终**用 deny 规则阻止 `rm -rf`、`sudo`、`curl | bash` 等危险命令
4. **始终**保护 `.env`、`*.key`、`*secret*` 等敏感文件
5. **推荐**使用 PreToolUse Hook 实现额外的安全审计
6. **推荐**使用 PostToolUse Hook 自动运行 linter/formatter
7. **团队项目**务必在 `.claude/settings.json` 中定义统一的权限基准
8. **企业场景**使用 Managed Settings 确保不可覆盖的安全策略

---

## 参考来源

1. [Configure permissions - Claude Code Docs](https://code.claude.com/docs/en/permissions) — 官方权限配置文档，涵盖六种模式与规则语法
2. [Advanced setup - Claude Code Docs](https://code.claude.com/docs/en/setup) — 官方安装指南，包含多平台安装与认证方式
3. [Claude Code Settings & Configuration Guide (2026) | Product Builder](https://www.productbuilder.net/learn/claude-code-settings) — 四层作用域详解与 55+ 配置项说明
4. [Complete Guide to Claude Code Permissions | ClaudeCodeLab](https://claudecode-lab.com/en/blog/claude-code-permissions-guide/) — 权限规则、Hooks 实现模式与 managed settings 全景
5. [The Complete .claude Directory Guide for Claude Code](https://computingforgeeks.com/claude-code-dot-claude-directory-guide/) — .claude 目录结构、CLAUDE.md、commands/agents/skills 组织方式

> [!tip] 51学通信知识星球
> **星主：爱卫生**（微信：gprshome201101）——公众号「51学通信」创办者，19 年通信行业运维与讲师经验，著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书（各大电商平台有售）。
> **星球定位**：深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域，主打运维岗位与信令分析。
> **当前规模**：5200 篇主题 / 990 个回答，198 元/年。
> **加入福利**：加入星球后请加爱卫生微信，拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题，另有群内分享。
> **AI 加持**：51学通信知识星球已作为 skill 接入 WorkBuddy，使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例，做总结、找文档和 PPT 等场景全覆盖。

![51学通信知识星球海报-扫码加入](https://wiki.500nian.com/images/zhixingqiu_qrcode.png)
