Git使用SSH方式

我平时git clone时用的都是HTTPS协议,也设置了:

1
git config --global credential.helper store

这行代码的作用是在 .gitconfig 文件中加这些内容:

1
2
[credential]
helper = store

以及生成一个 .git-credentials 文件,里面内容是明文的用户名密码:https://<用户名>:<密码>@github.com

这个方法在一段时间内有用,设置完后输入一次用户名密码,之后就不用再输了,但最近不行了。

顺便一提,当我设置完后输入一次用户名密码后,电脑的 凭据管理器 -> Windows凭据 里也保存了一个凭据。

但现在这些即使重新设置一遍都没有用!!

无奈,我选择改用SSH协议


使用SSH协议,首先要生成SSH公私钥并把公钥配置到 GitHub 上。”SSH keys”只有在使用 SSH 协议时才会使用。

在 GitHub 上添加好公钥后,需要用以下命令测试一下:

1
ssh -T git@github.com

如果提示:”Hi <你的用户名>! You’ve successfully authenticated, but GitHub does not provide shell access.” 说明配置成功。
如果提示:”ssh: connect to host github.com port 22: Connection timed out” 说明配置不成功,需要修改端口。

在 .ssh 目录下新建一个 config 文件,不带后缀。【这个文件的作用待研究…
文件内容:

1
2
3
4
5
6
Host github.com
User <id_rsa.pub 文件中的邮箱>
Hostname ssh.github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Port 443

文件保存好后,重新执行 ssh -T git@github.com 就OK了。


接着,要把原本用HTTPS的仓库改为SSH。一般的仓库可以先删除再重新 git clone,记得用SSH方式clone。

hexo博客改为SSH的步骤:

1) _config.yml 文件中,git地址改为SSH地址:

1
2
3
deploy:
type: git
repo: git@github.com:<用户名>/<用户名>.github.io.git

2) 执行命令

1
git remote set-url origin <git SSH地址>

执行完后检查:

1
2
3
> git remote -v 
origin git@github.com:<用户名>/<用户名>.github.io.git (fetch)
origin git@github.com:<用户名>/<用户名>.github.io.git (push)

修改成功!以后 hexo -d 时用的就是SSH协议了!