如何配置Git SSH?SSH密钥创建与设置问题求助
解决SSH密钥创建问题及Git SSH配置指南
一、SSH密钥创建故障排查与解决
先确认OpenSSH是否安装
终端输入ssh -V,能返回版本号就说明没问题;如果报错,按系统类型安装:- Windows:PowerShell里执行
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Client*',要是状态不是Installed,就运行Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0 - macOS/Linux:mac用Homebrew执行
brew install openssh,Debian/Ubuntu类系统用sudo apt install openssh-client
- Windows:PowerShell里执行
用基础命令生成密钥测试
别搞复杂参数,先跑最稳妥的生成命令:ssh-keygen -t ed25519 -C "your_email@example.com"按回车用默认路径,密码可选(加了更安全)。要是还失败,检查权限:
~/.ssh目录权限必须是700:chmod 700 ~/.ssh- 私钥文件权限设为
600:chmod 600 ~/.ssh/id_ed25519 - 公钥文件权限可以是
644:chmod 644 ~/.ssh/id_ed25519.pub
验证密钥能否正常连接
生成完用ssh -T git@github.com(以GitHub为例)测试,成功会返回你的用户名。要是报"Permission denied",先确认公钥已经粘贴到Git平台的SSH密钥设置页面里。
二、正确的Git SSH配置方法
首先,git config ssh是错误命令,Git没有这个配置项。正确配置分这几步:
1. 把公钥关联到Git账户
- 复制公钥内容:
cat ~/.ssh/id_ed25519.pub,把输出的全部内容粘贴到GitHub/GitLab等平台的SSH keys设置页。
2. 让Git默认用SSH连接仓库
- 先看当前仓库的远程地址:
git remote -v - 如果是HTTPS地址,换成SSH地址:
git remote set-url origin git@github.com:username/repo-name.git - 全局设置自动替换HTTPS为SSH(可选):
编辑~/.gitconfig文件,加上这段:
以后所有GitHub的HTTPS仓库都会自动用SSH连接。[url "git@github.com:"] insteadOf = https://github.com/
3. 多密钥管理(可选)
如果有多个SSH密钥(比如个人和工作账户),创建~/.ssh/config文件来区分:
# 个人GitHub账户 Host github-personal HostName github.com User git IdentityFile ~/.ssh/id_ed25519-personal # 工作GitLab账户 Host gitlab-work HostName gitlab.com User git IdentityFile ~/.ssh/id_ed25519-work
用的时候把远程地址改成git@github-personal:username/repo.git,就会自动对应指定密钥。
内容的提问来源于stack exchange,提问作者Hanif Rizqi Ferdana
相关产品推荐
相关产品推荐

