使用ssh key這種方式進(jìn)行clone ,pull github上面的項(xiàng)目,使用 git clone或者git pull origin master出現(xiàn)permission denied (publickey),原因是因?yàn)閟sh key過期失效或者沒有ssh key。 那么解決這種的問題的方法就是重新生成一個(gè)新的ssh key ,然后將這個(gè)ssh key添加到github賬戶上面,就可以了。
1. 檢查SSH key是否已經(jīng)存在
用這個(gè)命令
ls ~/.ssh/
進(jìn)行檢查 id_rsa.pub 是否存在,如果存在,就不用生成一個(gè)新的SSH key了,直接跳到下面的第3步。
2. 如果第1步中的SSH key不存在,生成一個(gè)新的SSH key
先:
cd /Users/your_user_name/.ssh
命令如下:
ssh-keygen -t rsa -b 2048 -C "your_email@example.com"
其中,your_email@example.com要修改成你的郵箱地址。
回車后輸出如下:
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/your_user_name/.ssh/id_rsa):
直接回車,會(huì)將key保存到默認(rèn)文件中。
接著會(huì)輸出:
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
這兩步是讓你輸入一個(gè)密碼,以及確認(rèn)密碼,這個(gè)密碼在你提交代碼到Github時(shí)會(huì)用到【注意:記住這個(gè)密碼,最簡(jiǎn)單的方式就是設(shè)置的和github賬戶登入密碼一樣,容易記住】
回車后就提示成功了:
Your identification has been saved in /Users/your_user_name/.ssh/id_rsa.
Your public key has been saved in /Users/your_user_name/.ssh/id_rsa.pub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db your_email@example.com
到這一步,你會(huì)發(fā)現(xiàn) /Users/your_user_name/.ssh/id_rsa.pub 文件已經(jīng)生成了。
3. 將ssh key添加到git
打開id_rsa.pub文件,復(fù)制里面的內(nèi)容,然后粘貼到git中相關(guān)的位置中。
例如對(duì)于gitlab 來說:

4. 把ssh 添加到keychain中
這個(gè)時(shí)候如果去git clone代碼,會(huì)讓你輸入密碼,如果一個(gè)還好說,如果關(guān)聯(lián)了很多的話,那就比較麻煩了,這個(gè)時(shí)候的解決方法就是添加到keychain中:
ssh-add -K /Users/youre_user_name/.ssh/id_rsa
4.1 (評(píng)論區(qū)留言提出)
如果出現(xiàn):
Could not open a connection to your authentication agent.
那么就使用如下命令解決:
ssh-agent bash
注:
.ssl 文件是隱藏的
可以用如下的方式顯示:
開啟顯示隱藏文件:
defaults write com.apple.finder AppleShowAllFiles -bool TRUE
關(guān)閉顯示隱藏文件:
defaults write com.apple.finder AppleShowAllFiles -bool FALSE
運(yùn)行完命令后,要重啟一下Finder。