Linux SSH 配置:专用密钥访问 GitHub 私有仓库

git; workspace
257 字

0. 目录与权限

chmod 700 ~/.ssh

1. 生成一把专用密钥(推荐 ed25519)

ssh-keygen -t ed25519 -C "github" -f ~/.ssh/id_ed25519_github

chmod 600 ~/.ssh/id_ed25519_github
chmod 644 ~/.ssh/id_ed25519_github.pub

2. 启动 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:全账号可用

  1. 登录 GitHub
  2. 右上角头像 -> Settings
  3. 左侧:SSH and GPG keys
  4. 点击:New SSH key
  5. Title:随便写(如 "Standard-PC")
  6. Key type:Authentication Key
  7. Key:粘贴 ~/.ssh/id_ed25519_github.pub 的内容
  8. Add SSH key

B. 仓库级(Repo-level)SSH key:只给某个私有仓库用(Deploy key)

  1. 登录 GitHub,进入目标私有仓库页面
  2. 仓库右侧/顶部:Settings(仓库设置)
  3. 左侧:Deploy keys
  4. 点击:Add deploy key
  5. Title:随便写(如 "CI key" / "Server key")
  6. Key:粘贴 ~/.ssh/id_ed25519_github.pub 的内容
  7. 权限:
    • 只拉代码:不要勾选 “Allow write access”
    • 需要推送:勾选 “Allow write access”
  8. Add key

5. 验证 SSH

ssh -T git@github.com

6. 克隆私有仓库(SSH URL)

git clone git@github.com

/REPO.git

7. 已有仓库:把远程从 HTTPS 改成 SSH

cd /path/to/repo git remote set-url origin git@github.com

/REPO.git git fetch origin