需求
一台电脑同时使用多个Git账号,互相不干扰。
思路
- 生成多个
ssh key
- 针对不同的项目使用不同的
ssh key
解决方案
下面以两个Git(
gitee.com
)账号(account_1@qq.com
和account_2@qq.com
)进行演示约定:
以
$
开始的代码表示用户输入的内容
${}
表示引用变量,请以实际值为准
1. 创建并进入~/.ssh
目录
# 创建 .ssh 目录(如果报文件夹已存在的错误,忽略即可)
$ mkdir ~/.ssh
# 进入 .ssh 目录
$ cd ~/.ssh
2. 生成多个 ssh key
2.1. 操作步骤
# 需要管理几个账号就生成几次,请使用实际邮箱地址替换 ${emailAddress}
$ ssh-keygen -t rsa -C "${emailAddress}"
# 提示输入 id_rsa 文件的保存位置
Enter file in which to save the key (.../.ssh/id_rsa):
$ ${emailName}
# 提示输入密码(直接回车)
Enter passphrase (empty for no passphrase):
$
# 提示再次输入密码(再次回车)
Enter same passphrase again:
$
2.2. 实际操作演示
# 1. 生成 account_1@qq.com 的 ssh key $ ssh-keygen -t rsa -C "account_1@qq.com" Enter file in which to save the key (.../.ssh/id_rsa): $ account_1 Enter passphrase (empty for no passphrase): $ Enter same passphrase again: $ # 2. 生成 account_2@qq.com 的 ssh key $ ssh-keygen -t rsa -C "account_2@qq.com" Enter file in which to save the key (.../.ssh/id_rsa): $ account_2 Enter passphrase (empty for no passphrase): $ Enter same passphrase again: $
3. 创建并配置 config
文件
3.1. 创建 config
文件
文件在
~/.ssh
下
# 创建 config 文件夹
$ touch ~/.ssh/config
3.2. 编辑 ~/.ssh/config
文件
向其中加入如下内容:
# account_1(account_1@qq.com)
Host account_1.gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/account_1
User account_1
# account_2(account_2@qq.com)
Host account_2.gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/account_2
User account_2
4. 部署 ssh key
参见其他部署 ssh key
的教程
5. 使用
# 原命令
$ git clone git@gitee.com:${username}/${projectName}.git
# 新命令(假如是 account_1@qq.com 的项目)
$ git clone git@account_1.gitee.com:${username}/${projectName}.git