Git提交时有Https和SSH两种验证方式,Https方式除了速度慢以外,在每次提交时还需要输入帐号和密码;而使用SSH可以生成一个公钥-私钥对,我们会把公钥添加到Git的服务器,把私钥放在本地。提交文件的时候Git服务器会用公钥和客户端提交私钥做验证,如果验证通过则提交成功。

对于Github添加公钥有以下几种情况:
1.单个Github用户推送单个Github用户;
2.单个Github用户推送多个Github用户;
3.多个Github用户推送多个Github用户;

对于单个Github用户推送单个Github用户

1 首先需要设置git全局用户信息

git config --global user.name "yourName"
git config --global user.email "yourEmail"

2 查看SSH版本,若没有输出,则需要安装SSH

ssh -V
sudo apt-get install openssh-client openssh-server   #SSH安装命令

3 生成新的SSH key

cd ~/.ssh
#若没有id_rsa和id_rsa.pub 则可以使用默认生成命令
ssh-keygen -t rsa -C "some explanations"
#若之前已存在,可以自定义生成
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_new

在~/.ssh目录下有id_rsa/id_rsa_new(私钥)和 id_rsa.pub/id_rsa_new.pub(公钥)两个文件,其中.pub文件里存放的即是公钥key。

4 添加私钥

ssh-add ~/.ssh/id_rsa

执行ssh-add时出现Could not open a connection to your authentication agent则先执行如下命令即可:

ssh-agent bash

5 添加公钥

登录到GitHub,选择settings ,选择Add SSH key,把.pub的内容复制到里面即可。

6 测试

ssh -T git@github.com
Hi xxx You've successfully authenticated, but GitHub does not provide shell access.

如果有以上提示,说明公钥添加成功。

单个Github用户推送多个Github用户

这种情况多用于同一个用户推送不同项目的仓库(如个人项目和工作项目):

1 生成多个SSH key

ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_p
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_w

2 添加私钥

ssh-add ~/.ssh/id_rsa_p
ssh-add ~/.ssh/id_rsa_w

3 修改配置文件

vim config
#personal
Host personal 
HostName github.com 
User uesrname@example.com
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_p 
#work 
Host work 
HostName github.com
User username@example.com
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_w

4 添加不同公钥到对应GitHub账户

5 测试

ssh -T git@personal  #git@Host
 Hi xxx You've successfully authenticated, but GitHub does not provide shell access

如果有以上提示,说明连接成功。

对于多个Github用户推送多个Github用户

这种情况多用于不同用户推送不同Github用户的仓库(个人账户到个人项目仓库,工作账户推送工作项目仓库),和配置单个Git用户的方式不同,这里我们需要为每个项目分别配置,所以要命令行进入仓库文件夹再设置。

1 生成多个SSH key

ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_p2p
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_w2w

2 添加私钥

ssh-add ~/.ssh/id_rsa_p2p
ssh-add ~/.ssh/id_rsa_w2w

3 修改配置文件

cd ~/.ssh
vim config
#personal to personal
Host p2p 
HostName github.com 
User personalAccount@example.com  
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_p2p 

#work to work
Host w2w 
HostName github.com
User workAccount@example.com
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_w2w

4 添加不同公钥到对应GitHub账户

5 添加局部用户信息

cd personalRepository
git config --local user.name "yourName"
git config --local user.email "personalAccount@example.com"
cd workRepository
git config --local user.name "yourName"
git config --local user.email "workAccount@example.com"

其中全局用户信息存在~/.gitconfig中,局部用户信息存在对应仓库目录.git/config中。

原作者:有一个错别字