解决 Git Permission denied 问题
前言
push项目时出现git@github.com: Permission denied (publickey). fatal: Could not read from remote repository.Please make sure you have the correct access rights and the repository exists.
出现这个问题表示你在尝试将本地代码推送到GitHub时,没有提供正确的公钥,或者你的公钥没有被添加到你的GitHub账户中。
删除现有 SSH 密钥
rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub
生成新的SSH密钥
cd ~/.ssh && ssh-keygen -t rsa -b 4096 -C "your_email"
复制密钥到剪贴板
Linux:
xclip -sel clip < ~/.ssh/id_rsa.pub
Mac:
pbcopy < ~/.ssh/id_rsa.pub
查看 Git 密钥
cat ~/.ssh/id_rsa.pub
配置Git使用新的SSH密钥
git config --global user.name "your_name"
git config --global user.email "your_email"
完整重置Git密钥脚本
适用于:Linux&Mac
#!/bin/bash
# 检查是否已经安装了Git
if ! command -v git &> /dev/null
then
echo "Git 未安装,请先安装Git。"
exit 1
fi
# 设置环境变量
YOUR_EMAIL="1926585708@qq.com"
YOUR_NAME="LCZ"
# 删除现有的SSH密钥
echo "删除现有的SSH密钥..."
rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub
# 生成新的SSH密钥
echo "生成新的SSH密钥..."
ssh-keygen -t rsa -b 4096 -C "$YOUR_EMAIL"
# 添加新的SSH密钥到ssh-agent
echo "启动ssh-agent并在后台运行..."
eval "$(ssh-agent -s)"
echo "将SSH私钥添加到ssh-agent..."
ssh-add ~/.ssh/id_rsa
# 复制公钥到剪贴板
echo "复制公钥到剪贴板..."
if command -v xclip &> /dev/null
then
xclip -sel clip < ~/.ssh/id_rsa.pub
echo "公钥已复制到剪贴板。"
elif command -v pbcopy &> /dev/null
then
pbcopy < ~/.ssh/id_rsa.pub
echo "公钥已复制到剪贴板。"
else
echo "无法自动复制公钥到剪贴板,请手动复制以下内容到GitHub/GitLab等平台的SSH密钥设置中:"
cat ~/.ssh/id_rsa.pub
fi
# 配置Git使用新的SSH密钥
echo "配置Git使用新的SSH密钥..."
git config --global user.name "$YOUR_NAME"
git config --global user.email "$YOUR_EMAIL"
echo "Git SSH配置完成。请将公钥添加到您的Git托管服务(如GitHub、GitLab等)中。"