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

每次关闭终端ssh-agent就清空,GitHub推送遇权限拒绝如何解决?

解决GitHub SSH权限问题的方案

一、让ssh-agent自动加载身份(永久生效)

方法1:配置shell启动脚本

  1. 打开对应shell的配置文件:bash用~/.bashrc,zsh用~/.zshrc,在文件末尾添加以下内容:
# 自动启动ssh-agent并加载指定密钥
if ! pgrep -u "$USER" ssh-agent > /dev/null; then
    ssh-agent -s > "$HOME/.ssh-agent-info"
fi
if [[ -f "$HOME/.ssh-agent-info" ]]; then
    source "$HOME/.ssh-agent-info" > /dev/null
fi
# 检查密钥是否已加载,未加载则添加
if ! ssh-add -l | grep -q id_ed25519_desktop; then
    ssh-add ~/.ssh/id_ed25519_desktop
fi
  1. 保存后执行source ~/.bashrc(或对应shell的配置文件),重启终端后会自动加载密钥。

方法2:通过ssh-config自动匹配密钥

创建或编辑~/.ssh/config文件,添加以下内容:

Host github.com
    IdentityFile ~/.ssh/id_ed25519_desktop
    IdentitiesOnly yes
  • IdentitiesOnly yes会强制使用指定密钥,避免ssh-agent尝试其他身份导致冲突
  • 后续连接GitHub时会自动调用该密钥,无需手动添加到ssh-agent

二、解决多SSH身份冲突问题

如果存在多个GitHub账号或不同服务器的密钥,修改~/.ssh/config为每个主机单独指定密钥:

# 第一个GitHub账号配置
Host github.com-account1
    HostName github.com
    IdentityFile ~/.ssh/id_ed25519_desktop
    IdentitiesOnly yes

# 第二个GitHub账号配置
Host github.com-account2
    HostName github.com
    IdentityFile ~/.ssh/id_ed25519_laptop
    IdentitiesOnly yes

使用时需替换仓库的主机名:

# 克隆第一个账号的仓库
git clone git@github.com-account1:account1/repo.git

# 已有仓库修改远程地址
git remote set-url origin git@github.com-account1:account1/repo.git

这样每个仓库会对应使用指定密钥,不会出现多身份冲突。

三、验证配置有效性

执行以下命令测试连接:

ssh -T git@github.com

返回Hi [你的用户名]! You've successfully authenticated, but GitHub does not provide shell access.则说明配置成功。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:34:55