4.3 KiB
4.3 KiB
tags, create time
| tags | create time | |||
|---|---|---|---|---|
|
2026-07-01 00:00 |
Git & SSH 配置
概述
Git 本地配置、SSH Key 管理与多账户/多主机路由,确保 GitHub 与私有 Gitea 实例能同时免密协作。核心在于 ~/.ssh/config 文件将不同主机映射到独立的私钥。
核心概念
Git 全局配置项速览
git config --global user.name "hezhaohui"
git config --global user.email "hezhaohui0807@163.com"
git config --global core.autocrlf input # 写时转 LF,避免 Windows CRLF 混入仓库
git config --global init.defaultBranch main # 初始化用 main(不再过时默认的 master)
git config --global init.forcedCloneProtocol https # git clone 默认走 HTTPS(可选)
[!info] 查看 / 删除配置
git config --global --list— 列出所有全局设置git config --global --unset user.name— 删除某项git config --edit --global— 直接编辑~/.gitconfig
SSH Key 为什么需要独立密钥对
同一个 GitHub / Gitea 账号如果共用一个 SSH Key 是可以的,但 按服务分 key 有以下好处:
| 优势 | 说明 |
|---|---|
| 隔离风险 | Gitea 服务器如果泄露某个部署密钥(deploy key),不会牵连你的 GitHub 主身份 |
| 审计清晰 | 服务端日志中 Host A uses id_ed25519_github vs id_ed25519_gitea,一眼区分来源 |
| 灵活轮换 | 替换 Gitea 密钥不影响 GitHub 已授权的 session |
~/.ssh/config 路由机制
SSH 客户端在发起连接时会顺序读取 ~/.ssh/config,第一个匹配规则生效。关键指令:
| 指令 | 作用 |
|---|---|
Host |
别名(不是真实主机名),匹配 .git@remote-url 中的 hostname 部分 |
HostName |
真实 DNS 名或 IP |
Port |
SSH 端口(默认 22) |
User |
SSH 认证用户名 |
IdentityFile |
使用的私钥路径 |
IdentitiesOnly yes |
强制只使用指定 key,不尝试系统其他 key |
示例完整配置:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
IdentitiesOnly yes
Host gitea-self
HostName 47.121.181.112
Port 3000
User git
IdentityFile ~/.ssh/id_ed25519_gitea
IdentitiesOnly yes
连接测试验证:
ssh -T git@github.com # Hi hezhaohui! You've successfully authenticated...
ssh -T git@gitea-self # logged in as hezhaohui
[!tip] verbose 调试 遇到 "Permission denied" 时加
-v打印详细握手日志:ssh -Tv git@github.com 2>&1 | grep "Offering" # 看客户端主动发送了哪个 key、服务端拒绝了哪一个
常见陷阱与最佳实践
1. SSH Config Host 别名必须与实际 URL 一致
# ❌ 错误:.git 远端仍指向原始地址
git remote add origin git@47.121.181.112:3000/user/repo.git
# ✅ 正确:使用 alias,让 config 中的 Host 匹配
git remote add origin git@gitea-self:3000/user/repo.git
Git 克隆时的远程 URL 格式为 git@[Host]:path,Host 必须和 ~/.ssh/config 里的 Host 完全一致才会命中对应的 IdentityFile 规则。
2. Git 的 HTTP 代理干扰 SSH
如果你设置了 http.proxy 或 https.proxy,某些工具链可能影响 ssh 命令的网络行为。对于 SSH 专用代理(如 proxychains),要排除内网地址:
# .gitconfig 中排除 Gitea 内网段
[url "ssh://git@gitea-self:3000/"]
insteadOf = ssh://git@47.121.181.112:3000/
3. 私钥权限过松导致被拒绝
chmod 600 ~/.ssh/id_ed25519_gitea
chmod 600 ~/.ssh/config # SSH client 也要求 config 不能开放可读
OpenSSH 如果检测到私钥文件对其他用户可读写,会直接忽略它——这是最常见的新手踩坑。
4. Ed25519 vs RSA:优先用 Ed25519
| 算法 | 公钥长度 | 私钥长度 | 安全性 | 速度 |
|---|---|---|---|---|
| Ed25519 ✅ | 68 bytes | 68 bytes | 高 | 快 |
| RSA 4096 | 968 bytes | ~3 KB | 中高 | 慢 |
Ed25519 不受 Heartbleed 类漏洞影响,且密钥更小、签名更快。除非服务端明确限制(极老设备),否则一律用 ed25519。
延伸阅读
- mac-dev-env-setup/homebrew-intro — Homebrew 包管理器安装 Git
- mac-dev-env-setup/node-nvm-pnpm — Node.js 环境搭建(后续依赖)