Linux SSH 配置:专用密钥访问 GitHub 私有仓库
0. 目录与权限
chmod 700 ~/.ssh1. 生成一把专用密钥(推荐 ed25519)
ssh-keygen -t ed25519 -C "github" -f ~/.ssh/id_ed25519_github
chmod 600 ~/.ssh/id_ed25519_github
chmod 644 ~/.ssh/id_ed25519_github.pub2. 启动 ssh-agent 并加载密钥(当前会话)
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519_github
3. 写 SSH 配置(固定用这把 key 访问 GitHub)
cat >> ~/.ssh/config <<'EOF' Host github.com HostName github.com User git IdentityFile ~/.ssh/id_ed25519_github IdentitiesOnly yes EOF
chmod 600 ~/.ssh/config
4. 获取公钥并添加到 GitHub
cat ~/.ssh/id_ed25519_github.pub
A. 账号级(Account-level)SSH key:全账号可用
- 登录 GitHub
- 右上角头像 -> Settings
- 左侧:SSH and GPG keys
- 点击:New SSH key
- Title:随便写(如 "Standard-PC")
- Key type:Authentication Key
- Key:粘贴
~/.ssh/id_ed25519_github.pub的内容 - Add SSH key
B. 仓库级(Repo-level)SSH key:只给某个私有仓库用(Deploy key)
- 登录 GitHub,进入目标私有仓库页面
- 仓库右侧/顶部:Settings(仓库设置)
- 左侧:Deploy keys
- 点击:Add deploy key
- Title:随便写(如 "CI key" / "Server key")
- Key:粘贴
~/.ssh/id_ed25519_github.pub的内容 - 权限:
- 只拉代码:不要勾选 “Allow write access”
- 需要推送:勾选 “Allow write access”
- Add key
5. 验证 SSH
ssh -T git@github.com6. 克隆私有仓库(SSH URL)
git clone git@github.com
/REPO.git7. 已有仓库:把远程从 HTTPS 改成 SSH
cd /path/to/repo git remote set-url origin git@github.com
/REPO.git git fetch origin