Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

git - How to manage multiple ssh keys in the ~/.ssh directory

I'm sure we all get this error from time to time:

$ git push origin master
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The typical remedy is to simply create a public/private key pair and share it with your git host (in my case bitbucket, with their instructions)

The thing is though, I have many accounts that require that I have a public/private key pair (for example i need to save a key to connect to AWS.. etc).. so what I do is that i create these keys and save them in separate directories ie

~/.ssh $ find .
./awskeys
./awskeys/id_rsa
./awskeys/id_rsa.pub
./bitbucket
./bitbucket/id_rsa
./bitbucket/id_rsa.pub

but then this error pops up every now and then.. to solve it I have to move the relevant keys back to the root ~/.ssh. this doesn't seem right to me. How can I reliably do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can have them anywhere you want, but their permission and the permission of the parent folders need to be strict:

  • no writable access for the parent folder (for others and all)
  • 644 for a public key
  • 600 for a private key.

You then:

  • declare those different keys in ~/.ssh/config (example here)
  • change the remote url in order to use the appropriate entry of the ~/.ssh/config file which described the right ssh key to use.

That means an entry like:

Host mygithub
    User           git
    IdentityFile   ~/.ssh/mypath/mykey # wherever your "new" key lives
    IdentitiesOnly yes

Allows you to replace an url like git@github.com:username/repo with:

git remote set-url origin mygithub:username/repo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...