多个github帐号的SSH key切换

来源:互联网 发布:如何优化前端页面 编辑:程序博客网 时间:2024/05/24 02:46

假设你有两个github账号:


一、生成并添加第一个ssh key

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. $ ssh-keygen -t rsa -C "youremail@xxx.com"  
在Git Bash中执行命令一路回车,会在~/.ssh/目录下生成id_rsa和id_rsa.pub两个文件

用文本编辑器打开id_rsa.pub里的内容,在Github中添加SSH Keys

不明白的请参考GitHub创建SSH Keys


二、生成并添加第二个ssh key

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. $ ssh-keygen -t rsa -C "youremail@xxx.com"  


这次不要一路回车了,给这个文件起一个名字 不然默认的话就覆盖了之前生成的第一个



假如起名叫my,目录结构如下:


如果生成的第二个ssh key不在.ssh/下,可移动到此目录


三、在.ssh/下创建config文件 内容如下:(注意这里的文件是没有文件类型的扩展名的)

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Host github.com  
  2.     HostName github.com  
  3.     PreferredAuthentications publickey  
  4.     IdentityFile ~/.ssh/id_rsa  
  5.   
  6. Host my.github.com  
  7.     HostName github.com  
  8.     PreferredAuthentications publickey  
  9.     IdentityFile ~/.ssh/my  
Host名字随意,接下来会用到。


四、测试配置是否正确





如果出现Hi xxx!You've successfully authenticated 就说明连接成功了


现在就以下种情况给出不同的做法:

1、本地已经创建或已经clone到本地:

如下两种解决方法:

打开.Git/config文件

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #更改[remote "origin"]项中的url中的  
  2. #my.github.com 对应上面配置的host  
  3. [remote "origin"]  
  4.     url = git@my.github.com:itmyline/blog.git  
或者在Git Bash中提交的时候修改remote 
[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. $ git remote rm origin  
  2. $ git remote add origin git@my.github.com:itmyline/blog.git  

2、clone仓库时对应配置host对应的账户
[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #my.github.com对应一个账号  
  2. git clone git@my.github.com:username/repo.git
0 0
原创粉丝点击