macOS 配置多个 Git 账户的 SSH-Key
XPoet 前端鼓励师

准备工作

请确保在你的Mac上已安装Git。安装Git请参考:传送门
在终端输入命令$ git --version, 能打印出具体的版本号,表示Git正确安装。

开始配置

本文以配置GitHubGitLab为案例,将生成两对公共/私有rsa密钥对,rsa_githubrsa_gitlab

在本地创建SSH-Key

1、打开终端,$ cd ~,进入到当前用户目录下。

2、使用命令$ ssh-keygen -t rsa -C "i@itpoet.cn"生成公共/私有rsa密钥对。此时会看到终端提示输入要保存密钥的文件名,为了做区分,我们给文件名加个后缀,本例第一个rsa密钥对:rsa_github
接着会看到终端提示输入密码,敲两次 Enter回车键 则不需要密码。最终在 .ssh 文件夹 里生成 rsa_githubrsa_github.pub 两个文件,如图:
image
image
注意:在 第2步 执行完后,如果用户目录下没有生成 .ssh 文件夹 ,那我们需要手动创建。

1
2
3
$ cd ~
$ mkdir .ssh
$ cd .ssh

成功创建完 .ssh 文件夹 之后,再执行 第2步 操作。

3、创建本例的第二个rsa密钥对,rsa_gitlab

1
2
$ cd .ssh
$ ssh-keygen -t rsa -C "a@itpoet.cn"

如图:
image
image

4、为ssh添加config配置文件,在 .ssh文件夹 下,新建config文件。

1
2
$ cd ~/.ssh
$ touch config

config文件创建好之后,将其内容修改为:

1
2
3
4
5
6
7
Host github.com
User itPoet_github
IdentityFile ~/.ssh/rsa_github

Host gitlab.com
User itPoet_gitlab
IdentityFile ~/.ssh/rsa_gitlab

5、配置 .gitconfig 文件。使用如下命令将会在用户目录下自动创建 .gitconfig 文件。

1
2
3
$ cd ~
$ git config --global user.name "itPoet_github"
$ git config --global user.email "i@itpoet.cn"

注意:在 第4步 执行完后,如果用户目录下没有生成 .gitconfig 文件 ,那我们需要手动创建。

1
2
$ cd ~
$ touch .gitconfig

最后将.gitconfig文件的内容修改为:

1
2
3
4
5
6
[user]
name = itPoet_github
email = i@itpoet.cn
[user]
name = itPoet_gitlab
email = a@itpoet.cn
在对应的Git网站添加SSH密钥设置

1、 GitHub
settings –> SSH and GPG keys –> New SSH Key
打开 rsa_github.pub,将里面的内容复制到 Key 输入框中,如图:
如图:
image
image

2、 GitLab
Profile –> SSH keys
打开 rsa_gitlab.pub,将里面的内容复制到 Key 输入框中,如图:
如图:
image
image

至此,在Mac下配置多个Git账户的SSH-Key参考教程也完成,同理,我们还可以配置Coding、码云等。现在让我们来体验使用SSH提交代码吧~~

 Comments