Git的一些使用
目录
- 下载
- 安装
- 命令
- 配置用户名和邮箱
- 连接远程仓库
- 1. 检查是否已有 SSH 密钥
- 2. 生成新的 SSH 密钥
- 3. 将公钥添加到远程仓库
- 4. 配置 Git 使用 SSH
- 可能遇到的问题
- 方法 1:永久解决方案(修改 SSH 配置)
- 方法 2:更新服务器密钥(推荐)
下载
官方下载:下载地址
Git 是一个跨平台的分布式版本控制系统,支持在 Windows、macOS 和 Linux 等多个操作系统上运行。
安装
参考:Git安装(保姆教程)
命令
配置用户名和邮箱
git config --global user.name "用户名"
git config --global user.email "邮箱"
连接远程仓库
1. 检查是否已有 SSH 密钥
在终端(Windows 用 Git Bash 或 WSL)运行:
ls ~/.ssh
如果看到 id_rsa(私钥)和 id_rsa.pub(公钥),说明已有密钥,可跳过生成步骤。
2. 生成新的 SSH 密钥
运行以下命令(替换邮箱为你的账号邮箱):
ssh-keygen -t ed25519 -C "邮箱"
-t ed25519
:使用更安全的 Ed25519 算法(推荐)。
如果系统不支持,改用 RSA
:
ssh-keygen -t rsa -b 4096 -C "邮箱"
按提示操作:
直接回车使用默认路径(~/.ssh/id_ed25519 或 ~/.ssh/id_rsa)。
设置密钥密码(可选,增加安全性)。
3. 将公钥添加到远程仓库
复制公钥内容
cat ~/.ssh/id_ed25519.pub # 或 id_rsa.pub
复制输出的全部内容(以 ssh-ed25519 或 ssh-rsa 开头)。
添加到远程仓库
GitHub:Settings → SSH and GPG keys → New SSH key → 粘贴公钥。
GitLab:Preferences → SSH Keys → 粘贴公钥。
Gitee:设置 → SSH 公钥 → 粘贴公钥。
4. 配置 Git 使用 SSH
检查远程仓库地址
确保远程仓库地址是 SSH 格式(非 HTTPS):
git remote -v
如果显示 HTTPS 地址(如 https://github.com/…),需修改为 SSH:
git remote set-url origin git@github.com:username/repo.git
(替换 username/repo 为你的仓库路径)
测试 SSH 连接
ssh -T git@github.com # GitHub
ssh -T git@gitlab.com # GitLab
如果看到 You’ve successfully authenticated,说明配置成功。
可能遇到的问题
Unable to negotiate with xxxx port xxxx: no matching host key type found. Their offer: ssh-rsa,ssh-dss fatal: Could not read from remote repository.
这个错误是由于 Git 客户端和 SSH 服务器之间的主机密钥类型不匹配导致的。具体来说,你的 SSH 客户端拒绝了服务器提供的 ssh-rsa 和 ssh-dss 密钥类型,认为它们不够安全。
以下是几种解决方法:
方法 1:永久解决方案(修改 SSH 配置)
打开或创建 SSH 配置文件:
nano ~/.ssh/config
添加以下内容:
Host *HostkeyAlgorithms +ssh-rsaPubkeyAcceptedKeyTypes +ssh-rsa
方法 2:更新服务器密钥(推荐)
最好的解决方案是让服务器管理员更新 SSH 主机密钥,使用更安全的密钥类型(如 ecdsa 或 ed25519)。