背景
例如:你在一家公司上班,并有公司发给你的一个git账号。同时,作为自己的兴趣爱好,你自己有一个github的账号。此时,你想要在同一台电脑上同时配置两个账号,以便于都能访问到git代码库。
方法
1、首先配置不同的SSH KEY,使用ssh-Keygen命令生成不同的SSH KEY
配置公司git账号
#切换到.ssh目录
cd ~/.ssh
#使用自己的企业邮箱产生SSH KEY
ssh-keygen -t rsa -C "mywork@email.com"
#企业的可以使用id_rsa,也可以自己起名,例如:id_rsa_work
Enter file in which to save the key (/root/.ssh/id_rsa): id_rsa
#将ssh key添加到SSH agent中,该命令如果报错:Could not open a connection to your authentication agent.无法连接到ssh agent,可执行ssh-agent bash命令后再执行ssh-add命令。
ssh-add ~/.ssh/id_rsa
同理,配置自己的github账号
#切换到.ssh目录
cd ~/.ssh
#使用自己github的注册邮箱产生SSH KEY
ssh-keygen -t rsa -C "mygithub@email.com"
#github的SSH KEY
Enter file in which to save the key (/root/.ssh/id_rsa): id_rsa_github
#将ssh key添加到SSH agent中 ,该命令如果报错:Could not open a connection to your authentication agent.无法连接到ssh agent,可执行ssh-agent bash命令后再执行ssh-add命令。
ssh-add ~/.ssh/id_rsa_github
生成对应的key后,记得把各自的SSH KEY配置到git中
2、在.ssh目录下配置config文件
#切换到.ssh目录
cd ~/.ssh
#创建并编辑config文件
vim config
# 粘贴到config文件中
#公司的git地址
Host gitlib
Hostname git.7x-networks.com #公司的git地址
IdentityFile ~/.ssh/id_rsa #访问公司git的SSH KEY
User longfei.su
Port *** #公司的git端口
Host github.com
Hostname github.com #github的地址
IdentityFile ~/.ssh/id_rsa_github #访问github的SSH KEY
User sulongfei001
3、测试配置是否成功
#github的地址
ssh -T git@github.com
#出现如下内容,表示成功链接github,***为你的github账户的用户名
Hi ***! You've successfully authenticated, but GitHub does not provide shell access.
#公司的git地址
ssh -T git@git.***.com
#出现如下内容,表示成功链接github,***为公司git账户的用户名
Hi ***! You've successfully authenticated, but GitHub does not provide shell access.
4、本地如果没有项目,git上创建项目仓库并拉取
git clone git@***:***/git-test.git
cd git-test
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
5、本地已有项目,git上创建仓库并拉取
git init
git remote add origin git@***:***/git-test.git
git add .
git commit
git push -u origin master