SSH连接GitHub账号

简单介绍一下用SSH连接GitHub的流程参考链接

1. Mac环境下检查一下已存在的 SSH Keys

1
$ ls -al ~/.ssh

可能的keys:id_rsa.pub、id_ecdsa.pub、id_ed25519.pub

2. 生成新的 SSH keys

在Terminal中输入

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

如果不支持ed25519,可以用

1
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

生成一个新的ssh key,用邮箱作为label

1
> Generating public/private ed25519 key pair.

Press enter

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

可设置passphrase

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

3. 将 SSH keys加入ssh-agent

启动ssh-agent

1
2
$ eval "$(ssh-agent -s)"
> Agent pid 59566

如果你是macOS Sierra 10.12.2或更高,需要修改~/.ssh/config文件,才能自动把keys加载到ssh-agent并在keychain中储存passphrases

1
2
$ open ~/.ssh/config
> The file /Users/you/.ssh/config does not exist.

如果该文件不存在,创建该文件

1
$ touch ~/.ssh/config

如果你使用默认路径和命名,修改为如下内容

1
2
3
4
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ed25519

将SSH私钥加入到ssh-agent,并在keychain中储存passphrase

1
$ ssh-add -K ~/.ssh/id_ed25519

4. 将 SSH key加入到 GitHub账号中

拷贝SSH公钥

1
2
$ pbcopy < ~/.ssh/id_ed25519.pub
# Copies the contents of the id_ed25519.pub file to your clipboard

进入GitHub Settings => “SSH and GPG keys”,新建并添加新key

5. 测试连接

在Terminal中输入

1
2
$ ssh -T git@github.com
# Attempts to ssh to GitHub
1
2
3
4
> 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)?
# print yes
1
2
> Hi username! You've successfully authenticated, but GitHub does not
> provide shell access.

现在可进行关联远程仓库等操作

关联远程仓库

1
$ git remote add origin git@github.com:<username>/<repositoryName>.git
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2021 Zirun Lin

Thanks~

支付宝
微信