SSH的密钥管理主要包括两个方面:生成公钥/私钥对以及公钥(私钥自己保密)的分发。多个github仓库和多个github帐号需要生成多个密钥对。

假设有用户user_one 下的仓库one,地址为git@github:user_one/one.git
用户user_two 下的仓库two,地址为git@github:user_two/two.git

1.全局配置

git config --global user.name "your_name" 
git config --global user.email  "your_email"

2.生成密钥对
执行命令 ssh-keygen -t rsa -C email 创建github对应的sshkey,命名为id_rsa_one

ssh-keygen -t rsa -C "your_email"

将上述代码再执行一遍,创建第二个sshkey,命名为id_rsa_two
创建好之后将id_rsa_one.pub和id_rsa_two.pub分别上传到对应服务器上。

3.克隆项目到本地

git clone git@github:user_one/one.git
git clone git@github:user_two/two.git

4.代码提交
切换到one的仓库,在执行push之前,执行以下命令:

ssh-agent bash
ssh-add ~/.ssh/id_rsa_one

然后执行push就可以成功提交了,切换到仓库two也是同理。

以上方法有个问题就是,每次重启电脑之后,需要重新执行以上两行代码才能正常提交。这里我们需要加个config配置。

解决方案
1.在~/.ssh目录下创建config文件,进行相应配置:

#第一个git项目账号 
Host github
HostName github.com 
User user_one
IdentityFile ~/.ssh/id_rsa_one

#第二个git项目账号 
Host github
HostName github.com
User user_two
IdentityFile ~/.ssh/id_rsa_two

2.检出服务端项目代码,这里需要注意,使用.ssh目录下的host代替真实的hostname,这样才能让git识别出来
git remote add user_one git@user_one:one/project.git

3.push的时候,push到对应的Host即可
one项目中: git push user_one master

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐