1.配置多个ssh key
以两个账号为例:
user1@email.com对应gitee的远程仓库
user2@email.com对应github的远程仓库
1.1.在~/.ssh目录下分别生成两个账号的ssh key
使用ssh-keygen -t rsa -C "user1@email.com"不要一直回车,
在第一个提示出输入key文件的名字,剩下两个提示直接回车,最后提示公匙和私匙保存在你命名的key文件中
ming@ming-TM1604:~/.ssh$ ssh-keygen -t rsa -C "user1@email.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ming/.ssh/id_rsa): id_rsa_gitee_user1
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa_gitee_user1.
Your public key has been saved in id_rsa_gitee_user1.pub.
The key fingerprint is:
SHA256:aaaaaaaaaaaaaaaaaaaaaaaaa user1@email.com
The key's randomart image is:
+---[RSA 2048]----+
...
+----[SHA256]-----+
ming@ming-TM1604:~/.ssh$ ls
id_rsa_gitee_user1 id_rsa_gitee_user1.pub known_hosts
使用同样的步骤在.ssh文件夹中生成user2@email.com的key
ming@ming-TM1604:~/.ssh$ ls
id_rsa_gitee_user1 id_rsa_gitee_user1.pub id_rsa_github_user2 id_rsa_github_user2.pub known_hosts
1.2.将密匙添加到ssh agent中
默认只读取id_rsa,为了让ssh识别新的私钥,需将其添加到ssh agent中:
ming@ming-TM1604:~/.ssh$ ssh-add id_rsa_gitee_user1
Identity added: id_rsa_gitee_user1 (id_rsa_gitee_user1)
ming@ming-TM1604:~/.ssh$ ssh-add id_rsa_github_user2
Identity added: id_rsa_github_user2 (id_rsa_github_user2)
1.3.创建配置文件
在.ssh文件中创建文件名为config,无后缀
在config中分别配置两个ssh key的信息
#github配置
Host github-user2
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github_user2
User ming
#gitee配置
Host gitee-user1
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_gitee_user1
User ming
1.4.测试
如下则表示配置成功
ming@ming-TM1604:~/.ssh$ ssh -T git@gitee.com
Welcome to Gitee.com, user1!
ming@ming-TM1604:~/.ssh$ ssh -T git@github.com
Warning: Permanently added the RSA host key for IP address '52.74.223.119' to the list of known hosts.
Hi RidingACodeToStray! You've successfully authenticated, but GitHub does not provide shell access.
注:取消全局用户和邮箱配置
git config --global --unset user.name
git config --global --unset user.email
在不同仓库配置用户和邮箱
git config user.name "yourname"
git config user.email "youremail"
2.关于配置ssh key拉取或更新代码仍要输入邮箱密码的问题
可能由于之前拉取代码使用的url是https方式,该方式会要求用户认证,ssh地址的时候才会采用ssh认证
进入仓库的.git文件夹,打开里面的config文件编辑,将
[remote "origin"]
url = https://gitee.com/xx/xxxx.git
fetch = +refs/heads/*:refs/remotes/origin/*
改为
[remote "origin"]
url = git@gitee.com:xx/xxxx.git
fetch = +refs/heads/*:refs/remotes/origin/*