GIT SSH 设置
Git SSH 设置指南
通过SSH协议使用Git可以免去每次操作都需要输入密码的麻烦,同时提高安全性。以下是设置Git SSH连接的完整步骤:
1. 检查现有SSH密钥
首先检查是否已有SSH密钥:
ls -al ~/.ssh
通常SSH密钥命名为:
id_rsa和id_rsa.pub(RSA算法)id_ed25519和id_ed25519.pub(Ed25519算法)
2. 生成新的SSH密钥(如果没有)
ssh-keygen -t ed25519 -C "your_email@example.com"
或者使用RSA算法(如果系统不支持Ed25519):
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
按提示操作,可以设置密码短语(可选但推荐)。
3. 将SSH密钥添加到ssh-agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519 # 或你生成的密钥文件名
4. 将公钥添加到Git服务器
复制公钥内容:
cat ~/.ssh/id_ed25519.pub
然后将其添加到:
- GitHub: Settings → SSH and GPG keys → New SSH key
- GitLab: Preferences → SSH Keys
- Bitbucket: Personal settings → SSH keys
5. 测试SSH连接
ssh -T git@github.com # 对于GitHub
ssh -T git@gitlab.com # 对于GitLab
你应该会看到一条欢迎消息。
6. 配置Git使用SSH
克隆仓库时使用SSH URL(格式为 git@github.com:user/repo.git),而不是HTTPS URL。
对于已有仓库,可以更改远程URL:
git remote set-url origin git@github.com:user/repo.git
7. 可选配置(~/.ssh/config)
对于多账户或特殊配置,可以创建/编辑SSH配置文件:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
常见问题解决
-
权限问题:确保密钥文件权限正确
chmod 600 ~/.ssh/id_ed25519 chmod 644 ~/.ssh/id_ed25519.pub -
连接被拒绝:检查防火墙设置或尝试使用
-v参数调试ssh -vT git@github.com -
不同平台:Windows用户可以使用Git Bash或WSL来执行这些命令
完成这些步骤后,你就可以通过SSH协议与Git仓库安全地交互而无需每次都输入密码了。

浙公网安备 33010602011771号