GitHub连接本地Git配置笔记
一、GitHub账号申请
-
注册账号
- 访问 GitHub官网,点击
Sign up
。 - 输入用户名、邮箱、密码,完成人机验证。
- 验证邮箱:登录邮箱点击GitHub发送的验证链接。
- 访问 GitHub官网,点击
-
生成SSH密钥(推荐)或使用HTTPS
- SSH:更安全,免密推送代码。
- HTTPS:需使用Personal Access Token(PAT)代替密码。
二、本地Git配置
-
安装Git
- 下载地址:https://git-scm.com/
- 验证安装:
git --version
-
配置全局用户信息
git config --global user.name "YourGitHubUsername" git config --global user.email "your-email@example.com"
-
生成SSH密钥(SSH方式)
ssh-keygen -t ed25519 -C "your-email@example.com" # 默认保存路径:~/.ssh/id_ed25519(私钥)和 id_ed25519.pub(公钥)
-
添加SSH公钥到GitHub
- 复制公钥内容:
cat ~/.ssh/id_ed25519.pub
- GitHub设置:
Settings -> SSH and GPG keys -> New SSH Key
,粘贴公钥。
- 复制公钥内容:
-
HTTPS方式配置(备用)
- 生成Personal Access Token(PAT):
Settings -> Developer settings -> Personal Access Tokens -> Generate new token
,勾选repo
权限。
- 使用PAT代替密码:
git clone https://github.com/username/repo.git # 输入用户名,密码处粘贴PAT
- 生成Personal Access Token(PAT):
三、测试连接
-
SSH连接测试
ssh -T git@github.com # 成功提示:Hi YourUsername! You've successfully authenticated...
-
HTTPS克隆测试
git clone https://github.com/username/repo.git
四、连接失败的常见解决方案
-
SSH密钥问题
- 检查密钥路径:确保
~/.ssh/id_ed25519.pub
正确添加到GitHub。 - 修复权限:
chmod 700 ~/.ssh chmod 600 ~/.ssh/id_ed25519
- 检查密钥路径:确保
-
网络问题
- 测试网络连通性:
ping github.com curl -v https://github.com
- 如果使用代理:
# 设置代理(示例) git config --global http.proxy http://127.0.0.1:1080 git config --global https.proxy http://127.0.0.1:1080
- 测试网络连通性:
-
端口被防火墙封锁
- SSH默认使用22端口,可能被公司/学校网络屏蔽。
- 改用HTTPS端口(443):
# 修改 ~/.ssh/config Host github.com Hostname ssh.github.com Port 443
-
GitHub服务状态
- 检查 GitHub Status,确认服务正常。
-
DNS解析问题
- 尝试刷新DNS缓存:
# Windows ipconfig /flushdns # macOS/Linux sudo killall -HUP mDNSResponder
- 尝试刷新DNS缓存:
-
更新Git版本
- 旧版本可能导致兼容问题:
git update # 或通过包管理器更新
- 旧版本可能导致兼容问题:
-
手动配置hosts文件
- 无可用ip可在C:\Windows\System32\drivers\etc\hosts下手动配置ip:
140.82.112.4 github.com # 可再网上再找找其他可用ip
- 无可用ip可在C:\Windows\System32\drivers\etc\hosts下手动配置ip:
五、总结
- 推荐使用SSH:安全且免密。
- 备选HTTPS+PAT:适合无法使用SSH的环境。
- 常见问题排查顺序:密钥配置 → 网络 → 代理 → 端口/DNS。
参考链接: