为Hexo博客仓库配置独立的Deploy Key(git)

Why?

关于 ssh-key 与 deploy-key

ssh-key 是用于认证 Github 账户的密钥,对所有的 repository (下文简写为 repo ) 都有操作权限;而 deploy-key 只允许对特定 repo 进行操作,每个 repo 的 deploy key 都是独有的,其他 repo 无法使用相同的 key。

下面是 Github 官方的说明:

Deploy key is a SSH key set in your repo to grant client read-only (as well as r/w, if you want) access to your repo.

As the name says, its primary function is to be used in the deploy process, where only read access is needed. Therefore keep the repo safe from the attack, in case the server side is fallen.

出于安全考虑(尝试新事物),我决定为托管在 Github 上的这个博客配置单独的 deploy-key.

What to do?

创建 deploy key

p.s. 以下演示均在 Windows 平台完成;终端均为 “cmd”

打开终端,切换到你的账户的主文件夹:

1
cd /d "%HOMEDRIVE%%HOMEPATH%"

然后输入命令:

1
ssh-keygen -t rsa -f ".\.ssh\deploy_key_blog" -C "用于区分key的注释"

其中 deploy_key_blog 是新密钥的名字,可以自己修改,不要和已有密钥重名。

回车之后,一般会出现:

1
2
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):

这个是让你为私钥设置密码的,不需要的话什么都不用输,“连续按两次回车” 即可进入下一环节。

如果成功,你会看到类似这样的输出:

1
2
3
4
5
6
7
8
9
10
Your identification has been saved in .\.ssh\deploy_key_blog.
Your public key has been saved in .\.ssh\deploy_key_blog.pub.
The key fingerprint is:
SHA256: “这里是一大串字符” example@example.com # 这里是你的邮箱
The key's randomart image is:
+---[RSA 2048]----+
# 这中间是一张随机图像
# 这中间是一张随机图像
# 这中间是一张随机图像
+----[SHA256]-----+

这样,一个 deoloy key 就创建完成了

部署 deploy key

  1. 在 Github 网页端登陆账号,然后打开 Hexo 博客所在的 repo 。
  2. 先点击横向菜单栏中的 “Settings” ,接下来在左侧纵向菜单栏点击 “Deploy keys”
  3. 点击 Add deploy key ,Title 可以随便起(用于自己区分)。
  4. 打开用户主文件夹中的 .ssh 文件夹(可能是隐藏文件),用文本编辑工具打开刚刚生成的 “deploy_key_blog.pub” 。(注意,是 .pub 后缀的文件)
  5. 复制文件中的所有内容(应以 ssh-rsa 开头),粘贴到网页中 Key 文本框中,然后勾选 “Allow write access”,点击 “Add key” 即可。

修改配置 config

  1. 打开用户主文件夹下的 ".ssh" 文件夹,右键 - “Git Bash Here” ,输入 touch config 然后回车。

    也可以新建一个文本文档,然后重命名为 config (没有后缀名)

  2. 用文本编辑工具打开 config ,写入下列内容:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 第一个账号(默认使用的账号),一般不用更改
    Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa

    # 第二个新账号,其中"hexo"为前缀名,可以任意设置,要记住,后面需要用到
    # 最后一行的 deploy_key_blog 是你创建的新密钥的名称(根据实际情况替换)
    Host xxxxxx.github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/deploy_key_blog
  3. 保存 / 另存为 ,编码选择 “UTF-8 ” 。

  4. 打开终端 输入下列指令(其中 “hexo” 是你刚刚设置的 Host):

    1
    ssh -T git@hexo.github.com

    如果显示下列信息,表示配置成功:

    1
    Hi 你的用户名/repo名! You've successfully authenticated, but GitHub does not provide shell access.

修改配置 _config.yml

  1. 用文本编辑器打开 博客本地 repo 中根目录下的 _config.yml ,修改 deploy 部分如下(其中 ”hexo.github.com“ 是你刚刚设置的 Host):

    1
    2
    3
    4
    deploy:
    type: git
    repository: git@hexo.github.com:你的用户名/你的用户名.github.io.git
    branch: master
  2. 打开终端,切换工作路径为 “博客本地 repo 的根目录“ ,输入 hexo g && hexo d 即可提交。

End

参考资料:

  1. 一台电脑使用两个/多个GitHub账号部署两个/多个Hexo博客 作者:TRHX

在此表示感谢!