目标是这三件事一次到位:
- 系统级:由 Windows 服务托管,不依赖某个终端窗口
- 持久化:重启后仍可用,不反复输密钥口令
- 多账号:个人/公司/多平台账号并存,按仓库自动走对应身份
一、先统一到底用哪套 SSH
建议统一使用 Windows 自带 OpenSSH,避免和 Git for Windows 自带 ssh 混用。
where ssh
where ssh-add
git config --global core.sshCommand "C:/Windows/System32/OpenSSH/ssh.exe"
如果 where 结果里有多套 ssh,核心是确保 Git 走上面这条路径。
把下面内容加到 ~/.bashrc:
alias ssh='/c/Windows/System32/OpenSSH/ssh.exe'
alias ssh-add='/c/Windows/System32/OpenSSH/ssh-add.exe'
然后执行:
source ~/.bashrc
二、启用系统级 ssh-agent 服务(关键)
Get-Service ssh-agent
Set-Service -Name ssh-agent -StartupType Automatic
Start-Service ssh-agent
Get-Service ssh-agent
看到状态为 Running 后,说明系统代理已启用。
三、为不同账号分别生成密钥
示例:一个个人 GitHub,一个公司 GitHub。都建议用 ed25519,并设置强口令。
ssh-keygen -t ed25519 -C "[email protected]" -f "$env:USERPROFILE\.ssh\id_ed25519_github_personal"
ssh-keygen -t ed25519 -C "[email protected]" -f "$env:USERPROFILE\.ssh\id_ed25519_github_work"
生成后会得到:
- 私钥:id_ed25519_github_personal / id_ed25519_github_work
- 公钥:对应的 .pub 文件
把两个 .pub 分别添加到对应 Git 账号的 SSH Keys 页面。
四、把私钥加入 Windows ssh-agent(通常可持久化)
ssh-add "$env:USERPROFILE\.ssh\id_ed25519_github_personal"
ssh-add "$env:USERPROFILE\.ssh\id_ed25519_github_work"
ssh-add -l
你会在添加时输入一次口令,之后由代理托管,日常不再重复输入。
(极少数环境在系统更新或服务重置后需要重新 add,一般很稳定。)
五、配置多账号路由(核心中的核心)
编辑 %USERPROFILE%.ssh\config,写成这样:
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github_personal
IdentitiesOnly yes
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github_work
IdentitiesOnly yes
解释:
- Host 是你本地自定义别名
- 两个别名都指向 github.com,但使用不同私钥
- IdentitiesOnly yes 防止客户端乱试其他密钥
六、克隆与远程地址要用别名
个人仓库用:
git clone git@github-personal:yourname/repo.git
公司仓库用:
git clone git@github-work:your-org/repo.git
已有仓库可改 remote:
git remote set-url origin git@github-work:your-org/repo.git
七、Git 提交身份也分开(避免邮箱串号)
仓库级设置最稳妥:
git config user.name "Your Name"
git config user.email "[email protected]"
你也可以做目录级自动切换(进阶):
全局 ~/.gitconfig 增加:
[includeIf "gitdir/i:C:/Users/你的用户名/repos/work/"]
path = C:/Users/你的用户名/.gitconfig-work
[includeIf "gitdir/i:C:/Users/你的用户名/repos/personal/"]
path = C:/Users/你的用户名/.gitconfig-personal
然后在两个文件里分别写 user.name / user.email。
八、验证是否真的“无感使用”
ssh -T git@github-personal
ssh -T git@github-work
ssh-add -l
如果能分别显示对应账号欢迎信息,并且 push/pull 不再反复要口令,方案就完全生效。
常见坑与排查
- 仍然频繁输入口令
检查 ssh-agent 是否 Running;检查是不是 Git 没走 Windows OpenSSH(看 core.sshCommand)。 - 走错账号
90% 是 remote URL 没用别名,或者 ~/.ssh/config 没配 IdentitiesOnly yes。 - 公钥加错账号
personal.pub 必须加到个人账号,work.pub 必须加到公司账号。 - 连接超时或拒绝
先测网络与 22 端口;受限网络可改走 443 的 SSH over HTTPS 端点(可再给你一版 config)。
这套方案本质上是:Windows 服务托管密钥 + SSH Host 别名做账号路由 + Git remote 显式绑定别名。
配置完后,体验就是“开机即用、仓库即分流、几乎不再输口令”。