背景
很多时候, 利用Git不仅仅只连接一个远程仓库, 所以需要对Git的连接进行配置, 它需要以下条件:
生成每个链接配对的私钥/公钥, 并且密钥文件命名不能重复
推送到远程仓库的时候需要区分账户, 以便推送到相应的仓库
配置
-
进入Git相关联的
~/.ssh
文件夹, 创建指定名称的密钥:1
ssh-keygen -t rsa -f ~/.ssh/id_rsa_x -C "[email protected]"
-
在
~/.ssh/
文件夹下创建config
配置文件, 并进行编辑:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# 第一个Git相关仓库
Host <server_name>
Hostname <connection_address>
Port <connection_port>
IdentityFile ~/.ssh/id_rsa
# 第二个Git相关仓库
Host github.com
Hostname github.com
User git
IdentityFile ~/.ssh/id_rsa_x0
# 第三个Git相关仓库
Host second.github.com
Hostname github.com
User git
IdentityFile ~/.ssh/id_rsa_x1- 对于Git仓库的连接是通过ssh的方式, 利用
[email protected]:githubUserName/repName.git
的地址来识别使用本地的哪个私钥, 地址中的User就是@前面的git, 而Host是@后面的github.com, 至于冒号后面的则是你的github的用户名以及仓库名. - 如果对于github, 你有多个不同账户的密钥连接, 则需要对Host单独进行配置, 并且在DNS服务商那里进行CNAME解析, 比如上面的第三个Git相关仓库的Host.
- 在这里, 第一个Git相关仓库其实是连接的VPS中的网络服务Hexo, 所以需要端口, 而第二个和第三个则是连接的Github的远程仓库, 保持这默认端口就可以了.
- 对于Git仓库的连接是通过ssh的方式, 利用
-
查看SSH公钥的值, 将其添加到Github账户中, 并清空本地的SSH缓存, 且添加新的SSH密钥到SSH agent中:
1
2
3
4
5
6# 清空缓存
ssh-add -D
# 添加新的SSH密钥
ssh-add id_rsa
# 确认新密钥是否添加成功
ssh-add -l -
测试ssh连接:
1
ssh -vT [email protected]
-
取消全局用户, 设置项目独立的用户:
1
2
3
4
5
6# 取消全局用户
git config --global --unset user.name
git config --global --unset user.email
# 进入项目文件夹, 单独设置用户
git config user.name "<username>"
git config user.email "<useremail>" -
进入项目目录, 重建Origin(Git默认的远程库名称):
1
2
3
4
5git remote rm origin
# 添加远程仓库地址
git remote add origin [email protected]:githubUserName/repName.git
# 查看远程
git remote -v -
将本地库的项目内容推送到远程库中:
1
2
3# 将本地项目的当前分支master推送到远程
# -u: 在第一次推送中把本地的master分支与远程的master分支关联起来, 在以后的推送/拉取时就可以简化命令
git push -u origin master