一、生成 keys 并添加到 GitHub 的步骤

1、在本地生成生成 SSH 密钥

打开终端

使用以下命令生成 SSH 密钥对:

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

命令参数含义:

  • -t rsa: 指定使用 RSA 算法生成密钥。
  • -b 4096: 设置密钥长度为 4096 位,提高安全性。
  • -C "your_email@example.com": 在注释字段中添加你的电子邮件地址。

在生成密钥的过程中,系统可能会要求你选择 SSH 密钥文件的存储位置和设置密码(可选操作)。

如果设置了密码,可以选择是否将 SSH 密钥添加到 SSH 代理(可选操作),以便在会话期间不必重复输入密码。运行以下命令,其中替换 ~/.ssh/id_rsa 为你的私钥文件路径。

1
2
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

过程实操过程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ ssh-keygen -t rsa -b 4096 -C "z2huo9994@163.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/zhuozhuo/.ssh/id_rsa):
Created directory '/Users/zhuozhuo/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/zhuozhuo/.ssh/id_rsa
Your public key has been saved in /Users/zhuozhuo/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:71LMxAjgHH/K0w6oMIEsFu/7cmlDMU77tin3Ac6gayM z2huo9994@163.com
The key's randomart image is:
+---[RSA 4096]----+
| . o. |
|o oo o. |
|+o .o ...o |
|o.. * +. o |
|o .+.O.S+ |
| o .o+++..+ |
| .o. oo.o. |
| E +o* +o.. |
| o.=.=ooo. |
+----[SHA256]-----+

2、复制 SSH 公钥中的内容

打开你的 SSH 公钥文件,一般为 ~/.ssh/id_rsa.pub。你可以使用文本编辑器或命令行工具查看。

复制公钥的全部内容,可以通过$ cat id_rsa.pub | pbcopy复制,仅限于 macOS

3、添加 SSH 密钥到 GitHub

  • 登录到你的 GitHub 帐户。
  • 在右上角的头像中选择 “Settings”。
  • 在左侧导航栏中选择 “SSH and GPG keys”。
  • 点击 “New SSH key”。
  • 在 “Title” 字段中,为 SSH 密钥添加一个描述性的标题。
  • 在 “Key” 字段中,粘贴你复制的 SSH 公钥。
  • 点击 “Add SSH key”。

二、通过 SSH 协议与 github 交互

现在,你的 SSH 密钥已经添加到 GitHub 帐户中。你可以使用 SSH 协议克隆、推送或拉取 GitHub 仓库,而无需每次输入密码。确保在进行敏感操作时,使用加密的私钥和安全的密码来保护你的 SSH 密钥。

1
2
3
4
5
6
7
8
$ git init
$ vim .gitignore
$ vim README.md
$ git add .
$ git commit -m "init commit"
$ git remote add github git@github.com:z2huo/figures-bed.git
$ git remote set-url github git@github.com:z2huo/figures-bed.git
$ git push -u github master

相关链接

OB tags

#Git