Bash CLI 工具:轻松切换 Codex 配置文件
管理多个 Codex 账户(工作、个人、备用)时,默认的 ~/.codex/auth.json 文件往往成为大瓶颈。手动复制认证文件容易混淆:分不清哪个配置文件在使用、剩余额度多少,还可能覆盖重要数据。一个简单的 bash 脚本 codex-auth 就能解决这些问题,它提供保存、切换配置文件和通过 API 监控用量的命令。
脚本将配置文件独立存储,缓存使用数据,支持代理,并通过指纹检测重复账户。
auth.json 文件位置及跨平台注意事项
主要认证文件:
- Linux/macOS:
~/.codex/auth.json - Windows:
%USERPROFILE%\.codex\auth.json
文件包含 access_token、id_token 和 account_id。结构可能变动,因此解析使用 jq 并有备用方案。
手动 cp 的问题:
- 无法标识当前活跃配置文件
- 数据丢失风险
- 缺少额度及重置时间信息
脚本命令
脚本提供简洁的 CLI 接口:
codex-auth— 列出配置文件及使用情况codex-auth usage— 当前 auth.json 的额度codex-auth save <name>— 保存当前配置文件codex-auth use <name>— 切换配置文件(或简写codex-auth <name>)codex-auth list-fast— 本地列表,不调用 APIcodex-auth backup— 备份当前配置文件
代理支持:
codex-auth proxy set <url>codex-auth proxy showcodex-auth proxy unset
缓存:
codex-auth cache-time [seconds](默认 15s,0 禁用缓存)
使用示例
- 用工作账户登录:
codex-auth save work - 用个人账户登录:
codex-auth save personal - 切换:
codex-auth work或codex-auth personal - 输出示例:
📊 5h: 100% ⏱5h 7️⃣ 15% ⏱4d 9h work <[email protected]>
📊 5h: 100% ⏱5h 7️⃣ 84% ⏱3d 18h *personal <[email protected]>
通过 API 监控使用情况
向 https://chatgpt.com/backend-api/wham/usage 发送查询,使用 Authorization: Bearer $token 和 account_id 头信息:
curl -s \
-H "Authorization: Bearer $token" \
-H "Accept: application/json" \
-H "User-Agent: CodexCLI" \
"https://chatgpt.com/backend-api/wham/usage" | jq
解析结果显示:
- 账户邮箱
- 套餐类型
- 剩余额度(5 小时、周额度)
- 重置时间
- 代码审查限额
加速缓存机制
缓存存储在 ~/.codex-auth-profiles/.usage-cache,以 token + account_id + proxy 为键。可配置 TTL 避免不必要 API 调用。无缓存(TTL=0)每次获取最新数据。
代理支持
适用于企业网络或防火墙:
codex-auth proxy set http://127.0.0.1:8888
curl 使用 --proxy 处理所有请求。存储在 ~/.codex-auth-profiles/proxy。
重复检测
配置文件指纹:
account_idid_token中的sub- 邮箱
- 整个文件的 SHA256
防止不同名称下的重复,并检查与当前 auth.json 的匹配。
跨平台适配
- base64: Linux
base64 -d,macOSbase64 -D - stat: Linux
stat -c %Y,macOSstat -f %m - SHA256: Linux
sha256sum,macOSshasum -a 256
使用 mktemp + mv 实现原子写入。
配置文件存储在 ~/.codex-auth-profiles:JSON 文件包括配置文件、当前选择、设置和缓存。
局限性
- 依赖 auth.json 结构
- 后端 API 可能变动
- 仅限 Bash,不适合复杂逻辑
依赖:bash、jq、curl、awk、sort、base64、stat。
主要优势
- 无风险切换配置文件,避免覆盖 auth.json
- 视觉化额度监控及重置时间
- TTL 缓存加速,代理支持网络环境
- 指纹防重复
- 原子写入,完全跨平台
— Editorial Team
暂无评论。