GitHub 添加 SSH keys

Using the SSH protocol, you can connect and authenticate to remote servers and services. With SSH keys, you can connect to GitHub without supplying your username or password at each visit.

SSH 协议可用于远程服务(器)的连接和认证。使用 SSH keys,不需要每次访问 GitHub 都要输入用户名和密码。

添加 SSH keys

生成 SSH keys

新建 SSH keys:

# 填写自己的 GitHub 账户邮箱
ssh-keygen -t rsa -b 4096 -C "your@email.com"

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/jeffcheng/.ssh/id_rsa):

输入 SSH keys 的存放路径和名称,自己命名并保存在当前用户的 .ssh 目录下:

/Users/jeffcheng/.ssh/imzhengfei_github_rsa

Enter file in which to save the key (/Users/jeffcheng/.ssh/id_rsa): /Users/jeffcheng/.ssh/imzhengfei_github_rsa
Enter passphrase (empty for no passphrase):

输入密码,用于以后链接 GitHub 时使用,可以直接回车省略密码:

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

再次输入密码回车,生成 SSH key:

Your identification has been saved in /Users/jeffcheng/.ssh/imzhengfei_github_rsa.
Your public key has been saved in /Users/jeffcheng/.ssh/imzhengfei_github_rsa.pub.
The key fingerprint is:
SHA256:…… your@email.com
The key's randomart image is:
+---[RSA 4096]----+
…...
+----[SHA256]-----+

添加公钥

复制公钥内容:

# 换成自己刚刚设置的名称
pbcopy < ~/.ssh/imzhengfei_github_rsa.pub

此时公钥内容已经被复制到剪切板,去 GitHub 添加 SSH key:

Settings > SSH and GPG keys > new SSH key

直接粘贴公钥内容并保存。

配置 SSH

一般配置

创建(修改)配置文件

vim ~/.ssh/config

插入配置:

# GitHub
Host github.com
  Hostname github.com
  User imzhengfei
	IdentityFile ~/.ssh/imzhengfei_github_rsa
	IdentitiesOnly yes

注意:

  • User 后面填写自己的用户名(username),不是姓名(name)。
  • IdentityFile 后面填写之前生成的私钥文件地址。

多个 SSH keys 配置

在配置文件中插入多个配置:

# GitHub
Host github.com
  Hostname github.com
  User imzhengfei
	IdentityFile ~/.ssh/imzhengfei_github_rsa
	IdentitiesOnly yes
	
# GitHub2
Host github2.com
  Hostname github.com
  User imzhengfei2
	IdentityFile ~/.ssh/imzhengfei_github2_rsa
	IdentitiesOnly yes
	
# Gitee
Host gitee.com
  Hostname gitee.com
  User imzhengfei
	IdentityFile ~/.ssh/imzhengfei_gitee_rsa
	IdentitiesOnly yes

注意:

  • Host 可随意设置,在使用 SSH 格式的地址操作 Git 仓库时会用到。比如在 Git 仓库地址 git@gitee.com:imzhengfei/xxx.git 中,其格式为 git@<host>:<user-name>/<project-name>.git 其中的 <host> 部分需要与上面配置中的 Host 对应,这样才能找到对应的仓库地址、用户名和对应的密钥。
  • Hostname 为 Git 仓库所在主机的访问域名或者 IP 地址。如果是域名,在第一次使用 SSH 链接时,会提示添加域名和对应的 IP,公钥信息到 ~/.ssh/known_hosts 文件中。

通信测试

ssh -T git@github.com

Warning: Permanently added the RSA host key for IP address '192.30.253.112' to the list of known hosts.
Enter passphrase for key '/Users/jeffcheng/.ssh/imzhengfei_github_rsa':

输入密码:

Hi imzhengfei! You've successfully authenticated, but GitHub does not provide shell access.

通信成功。

参考文献