频道栏目
首页 > 资讯 > 其他综合 > 正文

使用不同的SSH密钥执行git命令

17-04-14        来源:[db:作者]  
收藏   我要投稿

使用不同的SSH密钥执行git命令:一般来说,通过Git命令对远程仓库进行操作的时候,都需要经过身份验证,常用的身份验证方式有两种。

HTTPS SSH

为了省去每进行一次Git操作就要输入用户名和密码的麻烦(HTTPS协议),相信大部分人都是使用SSH协议进行身份验证。SSH协议的使用也很简单,在本地生成一个公钥私钥对,再把公钥上传到SSH服务器(这里以github.com为例),每次对远程服务器进行操作的时候,本地生成一些随机的字符串并用私钥进行加密以后传送到远程服务器,远程服务器使用公钥进行解密,若解密成功则身份验证通过。

但是现在遇到了一个问题,如果同时要对两个不同用户的github仓库进行Git命令操作,那么如何为每一次操作指定不同用户的私钥文件呢?

对于SSH命令指定不同的私钥文件非常简单:

 ?  ssh -i ~/.ssh/id_rsa -T git@github.com
Hi 9394974! You've successfully authenticated, but GitHub does not provide shell access.

只要通过-i参数指定私钥所在的地址即可。

Git命令可没有提供-i参数来指定私钥文件地址,但是git命令既然是基于SSH协议进行操作的,那么只要能更改SSH的配置文件即可,SSH协议可以从三个地方来读取配置(可以通过man ssh_config命令查看):

 ssh(1) obtains configuration data from the following sources in the following order:

      1.   command-line options
      2.   user's configuration file (~/.ssh/config)
      3.   system-wide configuration file (/etc/ssh/ssh_config)

 For each parameter, the first obtained value will be used.  The configuration files contain sections separated by ``Host'' specifications, and that section
 is only applied for hosts that match one of the patterns given in the specification.  The matched host name is usually the one given on the command line (see
 the CanonicalizeHostname option for exceptions.)

可以看到,SSH协议读取配置文件时是按照顺序读取,一旦拿到需要的参数就不再继续读取。那么,在配置另一个用户的配置文件时,可以选择新建~/.ssh/config文件。

# ~/.ssh/config
Host another_repo
HostName github.com
User git
IdentityFile ~/.ssh/another_repo_rsa

在新建了一个Host以后,假设another_repo的git协议url为git@github.com:another_user/another_repo.git,则在clone项目时需要改为:

git clone another_repo:another_user/another_repo.git
即格式为{Host}:{User}/{project.git}。

在clone项目下来以后,还需要修改git项目的remote,把原来的origin删除:

git remote rm origin
git remote add origin another_repo:another_user/another_repo.git

此时访问远程仓库就没有任何问题了。

最后值得注意的是,在对another_repo进行push的时候,身份标记还是以第一个用户的身份标记,如果需要修改为第二个用户的身份标记,需要修改git项目的config:

git config --local user.name "another_user"
git config --local user.email "another_user@email.com"
相关TAG标签
上一篇:改造Quartz的Bean由SpringIOC容器管理(SpringBoot项目实战)
下一篇:Python3实例:使用cx_Freeze打包成exe文件
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站