You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub多账号SSH密钥配置:解决终端重启后重复添加密钥的问题

解决多GitHub账号SSH密钥需重复执行ssh-add的问题

步骤1:创建SSH配置文件

在~/.ssh目录下创建或编辑名为config的文件,添加以下内容(根据你的密钥文件名调整):

# 第一个GitHub账号配置
Host github.com-acc1
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa
  AddKeysToAgent yes
  IdentitiesOnly yes

# 第二个GitHub账号配置
Host github.com-acc2
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519
  AddKeysToAgent yes
  IdentitiesOnly yes
  • Host:自定义别名,用于区分不同账号的GitHub连接
  • IdentityFile:指定对应账号的SSH密钥路径
  • AddKeysToAgent yes:首次连接时自动将密钥加入ssh-agent,无需手动执行ssh-add
  • IdentitiesOnly yes:强制使用指定的密钥,避免SSH尝试其他密钥导致认证混乱

步骤2:修改仓库远程地址

针对第二个账号的仓库,将原远程地址(如git@github.com:your-username/repo.git)替换为配置的别名地址:

git remote set-url origin git@github.com-acc2:your-username/repo.git

如果是新克隆仓库,直接用别名地址克隆:

git clone git@github.com-acc2:your-username/repo.git

步骤3:配置ssh-agent自动启动

编辑你的终端配置文件(Bash用~/.bashrc,Zsh用~/.zshrc,Windows Git Bash用~/.bash_profile),添加以下脚本:

# 自动启动ssh-agent并加载密钥
if [ -z "$SSH_AUTH_SOCK" ]; then
  eval "$(ssh-agent -s)"
  # 加载所有需要的密钥
  ssh-add ~/.ssh/id_rsa
  ssh-add ~/.ssh/id_ed25519
fi

保存后,重启终端或执行source ~/.bashrc(对应你的配置文件)使生效。

验证配置

执行以下命令测试第二个账号的认证:

ssh -T git@github.com-acc2

返回Hi your-username! You've successfully authenticated, but GitHub does not provide shell access.则配置成功。

内容的提问来源于stack exchange,提问作者yitian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:37:18