Linux Git SSH 配置全过程指南
1. 检查并安装必要的软件
# 检查是否已安装Git和SSH
git --version
ssh -V
# 如果未安装,执行以下命令安装
sudo apt update
sudo apt install git openssh-client -y
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. 将公钥添加到Git托管平台
复制公钥内容
cat ~/.ssh/id_ed25519.pub
# 或
# cat ~/.ssh/id_rsa.pub
添加到Git平台
- GitHub: Settings → SSH and GPG keys → New SSH key
- GitLab: Preferences → SSH Keys
- Bitbucket: Personal settings → SSH keys
4. 测试SSH连接
# GitHub测试
ssh -T git@github.com
5. 配置Git全局设置
git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"
6. 使用SSH克隆仓库
git clone git@github.com:username/repository.git
到这里就可以了
7. 可选:配置多个SSH密钥
如果需要为不同平台使用不同密钥:
- 创建config文件
nano ~/.ssh/config
- 添加配置示例
# GitHub账户
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
IdentitiesOnly yes
# 公司GitLab账户
Host gitlab.company.com
HostName gitlab.company.com
User git
IdentityFile ~/.ssh/id_rsa_work
IdentitiesOnly yes
8. 验证配置
# 检查Git配置
git config --list
# 检查SSH配置
ssh -vT git@github.com # 详细输出连接过程
9. 常见问题解决
权限问题
chmod 700 ~/.ssh
chmod 600 ~/.ssh/*
连接被拒绝
- 检查防火墙设置
- 确认SSH服务在服务器上运行
- 验证网络连接
完成以上步骤后,您应该能够通过SSH协议安全地与Git仓库进行交互。