git配置多个SSH key
1. 生成新的ssh key
执行下方命令,在选择文件地址及文件名时,不要使用默认值,填写自定义的密钥路径名称,比如:github_work、github_personal等
ssh-keygen -t rsa -C "<邮箱>"
Generating public/private rsa key pair.
Enter file in which to save the key (~/.ssh/id_rsa):<为了区分多个key,需要填写自定义的名称>
2. 配置~/.ssh/config
如果没有则新建
# work
Host codeup_work
HostName codeup.aliyun.com
IdentityFile ~/.ssh/codeup_work
PreferredAuthentications publickey
IdentityAgent none
IdentitiesOnly yes
User xiaoming
# personal
# 通配符表示可用于多个server
Host *
IdentityFile ~/.ssh/id_rsa
PreferredAuthentications publickey
IdentityAgent none
IdentitiesOnly yes
User xiaohong
配置说明:
- Host:别名
- PreferredAuthentications:指定SSH客户端尝试认证方法的优先顺序
- publickey:使用SSH密钥对认证
- keyboard-interactive:交互式键盘认证(通常是密码提示)
- password:密码认证
- gssapi-with-mic:基于GSSAPI的认证(如Kerberos)
- IdentityAgent:指定用于存储和管理SSH密钥的代理程序,none为禁用代理
- IdentitiesOnly:控制SSH是否只使用在配置文件中通过IdentityFile明确指定的密钥。
- no:默认值,SSH会尝试所有可用的密钥,包括SSH代理中的密钥。
- yes:当有多个SSH密钥,并且想确保SSH只使用为特定主机明确指定的密钥时非常有用。这可以防止SSH尝试使用不相关的密钥,从而避免因尝试太多密钥而被服务器拒绝连接。
- User:指定连接到远程主机时使用的用户名。如果不想每次都在命令行中指定用户名(如ssh username@hostname),可以在配置文件中设置默认用户名。对于git,用户名通常是git。
3. 使用
在仓库服务器中设置相应的ssh key,即可使用。
当克隆仓库时:
# work仓库
git clone git@codeup_work:username/repo.git
# 其他仓库正常使用
git clone git@xx:xx/repo.git
对于现有仓库,需要更改remote:
# work
git remote set-url origin git@codeup_work:username/repo.git
#其他仓库不用修改