一、交互式登录服务器
登陆命令
gh auth login
按照交互式提示操作(可以打开浏览器)
运行命令后,系统会询问你几个问题,通常建议如下选择:
- What account do you want to log into? 选择
GitHub.com。 - What is your preferred protocol for Git operations? 选择
HTTPS或SSH(如果你已经配置了 SSH 密钥,选 SSH;否则 HTTPS 最简单)。 - Authenticate Git with your GitHub credentials? 输入
Y。 - How would you like to authenticate GitHub CLI? 选择
Login with a web browser(最推荐)。
检查登录状态
gh auth status
二、非交互式登录(适合自动化脚本)
1. 如果你在无法进行交互的脚本环境(如 CI/CD)中,可以使用 Personal Access Token (PAT):
- 登录 GitHub,点击右上角头像 -> Settings。
- 在左侧栏最下方找到 Developer settings。
- 选择 Personal access tokens -> Tokens (classic)。(注:目前建议使用 classic 版本,兼容性最广)。
- 点击 Generate new token -> Generate new token (classic)。
- Note: 给 Token 起个名字(例如
Ubuntu-Server-CLI)。 - Expiration: 设置有效期(建议 30 或 90 天;如果是永久脚本,可根据安全策略选择
No expiration)。
2. 勾选权限 (Scopes) 建议
根据你在服务器上的常见操作,建议勾选以下权限:
| 权限范围 (Scopes) | 建议勾选 | 用途 |
| repo | ✅ | 读写私有仓库、提交代码、管理 Issue |
| workflow | ✅ | 如果你需要运行或触发 GitHub Actions |
| write:packages | ⬜ | 如果你需要上传 Docker 镜像到 GitHub |
| admin:org | ✅ | 成员管理、团队管理、设置修改、安全审计(高风险) |
| admin:public_key | ✅ | 强烈建议:允许 gh 自动为你上传 SSH 密钥 |
| gist | ⬜ | 除非你需要管理代码片段 |
| user | ✅ | 读取个人资料信息(登录必备) |
三、查询REPO和下载
列出你的所有仓库
gh repo list
如何克隆“所有”或“特定”仓库
gh repo clone <从列表中看到的名称>
四、GitHub 代理设置指南
以下是针对不同场景的配置方法:
为 HTTPS 协议设置代理(最常用)
如果你通过 https://github.com/... 克隆仓库,可以通过 Git 的全局配置来设置。
全局配置(推荐):
# 设置 HTTP 代理
git config --global http.proxy http://127.0.0.1:8080
# 设置 HTTPS 代理
git config --global https.proxy http://127.0.0.1:8080
取消配置:
git config --global --unset http.proxy
git config --global --unset https.proxy
针对 gh 专用配置:
# 设置HTTP代理
gh config set http_proxy http://127.0.0.1:8080
# 也可以设置SOCK5代理(和HTTP代理二选一)
gh config set http_proxy socks5://127.0.0.1:1080
# 取消
gh config unset http_proxy
