Ubuntu 22.04 用 SSH 方式 拉 GitHub 代码
GitHub 官方的 SSH 配置流程就是:检查 key、生成新 key、加入 ssh-agent、把公钥加到 GitHub、测试连接、再把仓库 remote 改成 SSH。 
一、先检查服务器上有没有 SSH key
ls -al ~/.ssh
如果看到类似这些文件,说明以前配过:
• id_ed25519
• id_ed25519.pub
GitHub 官方也建议先检查现有 SSH key。 
⸻
二、生成新的 SSH key
GitHub 目前推荐使用 ed25519。 
在 Ubuntu 22.04 上执行:
ssh-keygen -t ed25519 -C "你的GitHub邮箱"
比如:
ssh-keygen -t ed25519 -C "you@example.com"
执行后会看到:
Enter file in which to save the key (/root/.ssh/id_ed25519):
直接回车即可。
接着会问你是否设置 passphrase:
Enter passphrase (empty for no passphrase):
如果这台 ECS 是你自己长期用的部署机,想省事可以直接回车不设。
如果更注重安全,可以设一个密码短语。
⸻
三、启动 ssh-agent 并加载私钥
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
GitHub 官方文档也是这么做的。 
如果报错 Could not open a connection to your authentication agent,就重新执行一遍:
eval "$(ssh-agent -s)"
⸻
四、复制公钥内容
把公钥打印出来:
cat ~/.ssh/id_ed25519.pub
会得到一整行,类似:
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI...... your_email@example.com
把这一整行完整复制。
⸻
五、把公钥加到 GitHub
GitHub 页面操作:
• 右上角头像
• Settings
• SSH and GPG keys
• New SSH key
然后:
• Title:随便写,比如 aliyun-ecs
• Key type:Authentication Key
• Key:粘贴刚才复制的公钥
保存即可。GitHub 官方要求把公钥加到账号后,才能用 SSH 做 Git 认证。 
⸻
六、测试 SSH 是否连通
执行:
ssh -T git@github.com
第一次会提示:
The authenticity of host 'github.com (...)' can't be established.
Are you sure you want to continue connecting (yes/no/[fingerprint])?
输入:
yes
如果成功,通常会看到类似:
Hi sunyuhuakeyboard! You've successfully authenticated, but GitHub does not provide shell access.
这就是 GitHub 官方文档里的成功提示。 
⸻
七、用 SSH 地址 clone 仓库
你的仓库 SSH 地址已经在 API 返回里有了:
git@github.com:sunyuhuakeyboard/shanzao-project.git
直接执行:
git clone git@github.com:sunyuhuakeyboard/shanzao-project.git
这样就不会再让你输入 GitHub 用户名和 token 了。
⸻
八、如果仓库已经 clone 下来了,只是想以后用 SSH pull
进入项目目录后,把 remote 从 HTTPS 改成 SSH:
cd ~/work/shanzao-project
git remote -v
git remote set-url origin git@github.com:sunyuhuakeyboard/shanzao-project.git
git remote -v
GitHub 官方文档里也明确可以用 git remote set-url 把远程从 HTTPS 切到 SSH。 
然后以后直接:
git pull
⸻
九、你这个场景最推荐的完整命令
你可以直接一条条执行:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
ssh-keygen -t ed25519 -C "你的GitHub邮箱"
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
cat ~/.ssh/id_ed25519.pub
把公钥加到 GitHub 后,再执行:
ssh -T git@github.com
git clone git@github.com:sunyuhuakeyboard/shanzao-project.git
如果是已经拉过的项目,就改 remote:
cd ~/work/shanzao-project
git remote set-url origin git@github.com:sunyuhuakeyboard/shanzao-project.git
git pull
⸻
十、如果 22 端口被拦了
有些服务器网络环境会拦 SSH 的 22 端口。GitHub 官方提供了 SSH over HTTPS port 443 的方式。 
这种情况下可以新建 ~/.ssh/config:
cat > ~/.ssh/config <<'EOF'
Host github.com
HostName ssh.github.com
Port 443
User git
IdentityFile ~/.ssh/id_ed25519
EOF
chmod 600 ~/.ssh/config
然后再测:
ssh -T git@github.com
⸻
十一、你现在最适合怎么做
你前面 HTTPS + token 已经折腾过一轮了,所以现在最稳的是:
1. 生成 id_ed25519
2. 加到 GitHub
3. 测试 ssh -T git@github.com
4. 把 remote 改成 SSH
5. 直接 git pull
如果你愿意,我可以下一条直接按你的服务器环境,给你整理成一份 Ubuntu 22.04 从 0 到 1 配 GitHub SSH 的可直接复制执行版脚本。
更多推荐

所有评论(0)