git ssh失败

git 报错:

1
2
3
4
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
1
2
3
4
5
PS D:\822lib> git remote -v
origin git@github.com:dkyou/822lib.git (fetch)
origin git@github.com:dkyou/822lib.git (push)
PS D:\822lib> ssh -T git@github.com
git@github.com: Permission denied (publickey).

原因:没有正确配置ssh密钥

解决步骤

1. 生成 SSH 密钥对

1
ssh-keygen -t ed25519 -C "你的邮箱@example.com"

按提示操作,可以直接按回车使用默认路径和空密码。

1
2
3
4
5
6
7
8
9
10
11
12
13
PS C:\Users\dky\.ssh> ls

目录: C:\Users\dky\.ssh

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2025/8/22 11:30 278 config
-a---- 2025/8/22 11:11 411 id_ed25519 # 新生成
-a---- 2025/8/22 11:11 100 id_ed25519.pub # 新生成
-a---- 2024/6/25 17:47 2602 id_rsa
-a---- 2024/6/25 17:47 571 id_rsa.pub
-a---- 2025/4/23 22:13 1205 known_hosts
-a---- 2025/3/27 23:01 926 known_hosts.old

2. 启动 ssh-agent 并添加密钥

1
2
basheval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

需要用git bash终端执行

2.1 配置SSH config文件,在~/.ssh/config文件中添加:

1
2
3
4
Host github.com
AddKeysToAgent yes
UseKeychain yes # macOS 专用
IdentityFile ~/.ssh/id_ed25519

3. 获取并添加公钥到 GitHub

  • 查看公钥内容:

    1
    cat ~/.ssh/id_ed25519.pub
  • 复制输出的内容

  • 登录 GitHub → 点击右上角头像 → Settings → SSH and GPG keys → New SSH key

  • Title 填写标识名称(如 “My PC”),Key type 选择 “Authentication”,Key 中粘贴刚才复制的内容

  • 点击 “Add SSH key”

4. 验证连接

1
ssh -T git@github.com

如果显示 “Hi xxx! You’ve successfully authenticated…” 表示配置成功。

5. 重新推送

1
git push -u origin master