公钥管理
以下通过gitea 来演示,gitee github 基本大同小异
用户可以通过仓库主页 「设置」->「SSH /GPG密钥」 ,浏览/验证/删除当前仓库已添加的SSH Key。
生成/添加 SSH 公钥
Gitea 提供了基于 SSH 协议的 Git 服务,在使用 SSH 协议访问仓库之前,需要先配置好账户/仓库的 SSH 公钥。
你可以按如下命令来生成 sshkey:
ssh-keygen -t ed25519 -C "xxxxx@xxxxx.com"
# Generating public/private ed25519 key pair...
注意:这里的 xxxxx@xxxxx.com 只是生成的 sshkey 的名称,并不约束或要求具体命名为某个邮箱。 现网的大部分教程均讲解的使用邮箱生成,其一开始的初衷仅仅是为了便于辨识所以使用了邮箱。
按照提示完成三次回车,即可生成 ssh key。通过查看 ~/.ssh/id_ed25519.pub 文件内容,获取到你的 public key
cat ~/.ssh/id_ed25519.pub
# ssh-ed25519 AAAAB3NzaC1yc2EAAAADAQABAAABAQC6eNtGpNGwstc....
复制生成后的 ssh key,通过仓库主页「设置」->「SSH /GPG密钥」->「增加密钥」 ,添加生成的 public key 添加到仓库中。
添加后,在终端(Terminal)中输入
ssh -T git@maruifu.com
首次使用需要确认并添加主机到本机 SSH 可信列表。
maruifu@XMG-M4ProMax ~ % ssh -T git@maruifu.com
The authenticity of host '[maruifu.com] ([182.156.236.139])' can't be established.
ED25519 key fingerprint is SHA256:m7seiLokJsJhj9yuyrSQ6ZoEtHgRvHcV3tYEPNE9cRI.
This host key is known by the following other names/addresses:
~/.ssh/known_hosts:14: [git.maruifu.com]:222
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[maruifu.com]' (ED25519) to the list of known hosts.
Hi there, maruifu! You've successfully authenticated with the key named marf@pep.com.cn, but Gitea does not provide shell access.
If this is unexpected, please log in with password and setup Gitea under another user.
ssh -T -p 2222 git@maruifu.com
ssh
: Secure Shell 协议。-T
: 禁用伪终端(PTY)分配。对于只是测试连接或执行简单命令(如 Git 操作)来说,这很常用,因为它更简洁安全。-p 2222
: 指定连接远程主机的端口号为222
(而不是默认的222
)。22端口可以省略此参数git@maruifu.com
: 使用git
用户连接到maruifu.com
主机。
添加成功后,就可以使用 SSH 协议对仓库进行操作了。
Git 配置多个 SSH Key
背景
同时使用两个 Gitea 帐号,需要为两个帐号配置不同的 SSH Key:
- 帐号 A 用于公司;
- 帐号 B 用于个人。
解决方法
- 生成帐号 A 的 SSH Key,并在帐号 A 的 Gitea 设置页面添加 SSH 公钥:
ssh-keygen -t ed25519 -C "Gitea User A" -f ~/.ssh/Gitea_user_a_ed25519
- 生成帐号 B 的 SSH-Key,并在帐号 B 的 Gitea 设置页面添加 SSH 公钥:
ssh-keygen -t ed25519 -C "Gitea User B" -f ~/.ssh/Gitea_user_b_ed25519
- 创建或者修改文件
~/.ssh/config
,添加如下内容:
Host gt_a
User git
Hostname git@maruifu.com
Port 22
IdentityFile ~/.ssh/Gitea_user_a_ed25519
Host gt_b
User git
Hostname git@maruifu.com
Port 22
IdentityFile ~/.ssh/Gitea_user_b_ed25519
- 用 ssh 命令分别测试两个 SSH Key:
$ ssh -T gt_a
Hi Gitea User A! You've successfully authenticated, but git@maruifu.com does not provide shell access.
$ ssh -T gt_b
Hi Gitea User B! You've successfully authenticated, but git@maruifu.com does not provide shell access.
- 拉取代码:
将 git@git@maruifu.com
替换为 SSH 配置文件中对应的 Host
,如原仓库 SSH 链接为:
git@git@maruifu.com:owner/repo.git
使用帐号 A 推拉仓库时,需要将连接修改为:
gt_a:owner/repo.git
本文由 小马哥 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2025/08/20 01:16