同一個電腦配置多個ssh key以及配置完成後git拉取或更新程式碼仍要輸入密碼問題的解決
阿新 • • 發佈:2019-01-03
1.配置多個ssh key
以兩個賬號為例:
[email protected]對應gitee的遠端倉庫
[email protected]對應github的遠端倉庫
1.1.在~/.ssh目錄下分別生成兩個賬號的ssh key
使用ssh-keygen -t rsa -C "[email protected]"不要一直回車,
在第一個提示出輸入key檔案的名字,剩下兩個提示直接回車,最後提示公匙和私匙儲存在你命名的key檔案中
[email protected]:~/.ssh$ ssh-keygen -t rsa -C "[email protected]"
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 [email protected]
The key's randomart image is:
+---[RSA 2048]----+
...
+----[SHA256]-----+
[email protected]:~/.ssh$ ls
id_rsa_gitee_user1 id_rsa_gitee_user1.pub known_hosts
使用同樣的步驟在.ssh資料夾中生成[email protected].com的key
[email protected]:~/.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中:
[email protected]:~/.ssh$ ssh-add id_rsa_gitee_user1
Identity added: id_rsa_gitee_user1 (id_rsa_gitee_user1)
[email protected]:~/.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.測試
如下則表示配置成功
[email protected]:~/.ssh$ ssh -T [email protected]
Welcome to Gitee.com, user1!
[email protected]:~/.ssh$ ssh -T [email protected]
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 = [email protected]:xx/xxxx.git
fetch = +refs/heads/*:refs/remotes/origin/*