Github 如何支持 SSH 访问

976 阅读1分钟

一般有两种方式从 github 上 拉取代码

  • https
  • ssh

HTTPS

局限:提交代码时每次需要输入账户密码验证,很麻烦

git clone https://github.com/sialvsic/<repo name>.git

SSH

为了避免每次提交时反复输入账户密码进行验证,可以配置 ssh,做到一次配置,之后省事

git clone git@github.com:sialvsic/<repo name>.git

如何配置

思路:

  • 生成 ssh key
  • 在 github 上添加 ssh key
  • 测试 ssh key

生成 ssh key

其实可以直接看官方的文档,说的很清楚 Connecting to GitHub with SSH

a. 查看是否已经存在 ssh key - Checking for existing SSH keys

打开命令行

输入ls -al ~/.ssh,看是否存在以下文件名,如果存在说明已经有了

id_rsa.pub
id_ecdsa.pub
id_ed25519.pub

b. 如果存在说明已经有了 ssh key,则不需要在生成了,如果没有,需要生成 不同的环境的命令不大一样,有 Mac,Linux,Windows,参考

以 Linux 举例,其他环境可参考

打开命令行,输入以下命令

$ ssh-keygen -t ed25519 -C "your_email@example.com"

如果不支持Ed25519算法
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

当你看到提示,Enter a file in which to save the key,输入回车符(这会存储到默认的位置)

Enter a file in which to save the key (/home/you/.ssh/id_ed25519): [Press enter]

当你看到提示,Enter passphrase,这里可以输入回车符略过

Enter passphrase (empty for no passphrase): [Type a passphrase] Enter same passphrase again: [Type passphrase again]

之后就会生成两个 ssh 文件,一个公钥,一个私钥

id_xxx  <= 私钥
id_xxx.pub  <= 公钥

在 github 上添加 ssh key

a. 复制刚刚生成的公钥的内容

$ pbcopy < ~/.ssh/id_ed25519.pub

# Copies the contents of the id_ed25519.pub file to your clipboard

b. 打开 github,在头像 -> Setting -> SSH and GPG key -> New SSH key,粘贴上面复制的值到 key 的文本区内,title 部分可以自己随意填写

ssh-001

ssh-002

测试 SSH key 的配置

a. 打开命令行

b. 输入

$ ssh -T git@github.com

# Attempts to ssh to GitHub

可能会看到一个警告 ⚠️

> The authenticity of host 'github.com (IP ADDRESS)' can't be established.
> RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
> Are you sure you want to continue connecting (yes/no)?

c. 输入 yes 既可,你会看到以下信息,username 为自己的 github 账户名

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

至此,ssh key 配置完成