summaryrefslogtreecommitdiff
path: root/content/notes/ssh-to-git-instead-of-http.md
blob: f76d849e278839fed9b6d5709a979ad4a04b3899 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
+++
date = '2026-03-05T12:41:33+08:00'
draft = false
title = '使用 SSH 替代 HTTPS 连接 Git'
+++

直接一直习惯使用 HTTPS 连接到远程 Git 仓库,偶尔会遇到 SSL 问题,比如这样:

```
LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to codeberg.org:443
```

可能是网络环境导致的,但既然是 SSL 问题,那不用 HTTPS 协议不就不会遇到这个问题了吗?改用 SSH 连接至远程仓库可能是更稳定的选择。

一般来说,HTTPS 协议的远程仓库 URL 是这样的:

```
https://codeberg.org/eltrac/essayer.git
```

对应的 SSH 链接就是这样:

```
ssh://git@codeberg.org/eltrac/essayer.Git
```

Codeberg(Forgejo)和 GitHub 都支持通过 SSH 连接。

设置远程仓库 URL:

```shell
git remote set-url origin git@codeberg.org:eltrac/essayer.git
```

直接 pull 或者 push 会遇到认证问题,需要配置 SSH 密钥进行认证。在 Codeberg/Forgejo/GitHub 的设置中找到「SSH / GPG keys」,添加自己的 SSH 公钥。[^1]

接下来要配置本地的 SSH 在连接至 Codeberg/Forgejo/GitHub 时使用相应的密钥进行认证,编辑 SSH 配置文件(macOS 的在 `~/.ssh/config`)。

添加这一段配置

```
Host codeberg.org
    HostName codeberg.org
    User git
    ProxyCommand nc -X 5 -x 127.0.0.1:7890 %h %p
    IdentityFile ~/.ssh/id_ed25519
    TCPKeepAlive yes
```

根据自己的情况修改 `Host`、`HostName`、`ProxyCommand` 和 `IdentityFile`。比如,如果你要通过 SSH 连接到 GitHub 而非 Codeberg,就把 `codeberg.org` 改为 `github.com`;如果你不使用代理,可以把 `ProxyCommand` 删掉,如果代理的端口不在 7890,也要手动修改;如果你用来跟远程服务器认证的 SSH 密钥名字不叫 `id_ed25519`,也请自行修改。

然后尝试 `git pull` 或者 `git push`,应该能够正常通过 SSH 连接到远程仓库了。

[^1]: 如果没有 SSH 公钥,使用 `ssh-keygen -t ed25519` 生成。