关于git项目中多ssh-key管理

2,587 阅读1分钟

前言

git项目进行pull,push等操作时,都需要本地ssh-key权限。但当多个仓库或多个账号进行开发时,则需要对多个key进行管理。 环境: windows10, Git Bash。

生成ssh-key

1、生成一个新的自定义名称(demo)的公钥:

$ ssh-keygen -t rsa -C "YOUR_EMAIL@YOUREMAIL.COM" -f ~/.ssh/demo

执行命令后,一路回车;
执行完成后,会在 ~/.ssh/目录下生成一个 demo 和 demo.pub(主要内容在此文件中) 文件;
然后可同样步骤再生成另一个公钥(anohterDemo)。

2、添加相应的 demo.pub,anotherDemo.pub 到你的git项目上。

公钥添加代理

1、查看系统ssh-key代理,为公钥添加代理,执行如下命令

$ ssh-add -l

以上命令若输出 "Could not open a connection to your authentication agent" 则还没有创建代理。可以先执行以下命令创建代理

$ eval `ssh-agent -s`

如输出 "The agent has no identities" 则表示没有代理。如果系统有代理,可以执行下面的命令清除代理:

$ ssh-add -D

2、然后依次将不同的ssh添加代理,执行命令如下:

 $ ssh-add ~/.ssh/demo
 $ ssh-add ~/.ssh/anotherDemo

配置公钥对应服务器

1、配置 ~/.ssh/config 文件 如果没有就在~/.ssh目录创建config文件,该文件用于配置对应的服务器。

#demo resrepositories 
Host github-demo
HostName github.com
User git
IdentityFile C:/Users/用户名/.ssh/demo

#anotherDemo resrepositories 
Host github-anotherDemo
HostName github.com
User git
IdentityFile C:/Users/用户名/.ssh/anotherDemo

配置完成后,在连接github仓库时,远程库的地址要对应地做一些修改,比如现在添加帐号下的demo仓库,则需要这样添加:

git remote add test git@github-demo:username/demo.git
#并非原来的git@github.com:username/demo.git

2、测试 ssh

$ ssh -T git@github.com

你会得到如下提示,表示这个ssh公钥已经获得了权限

Hi @username/demo! You've successfully authenticated, but GitHub does not provide shell access.

Ps: 同理可得多账号操作方式