477 字
2 分钟
如何使用ssh连接github仓库
生成 ssh 密钥
-
创建 ssh 密钥存放目录并进入
# 创建目录mkdir ~/.ssh# 进入目录cd ~/.ssh -
生成 ssh 密钥
# 将邮箱替换为你的邮箱ssh-keygen -t rsa -C "your_email@example.com" -
查看 ssh 公钥
cat id_rsa.pub# 将全部输出复制
将公钥添加到 github
- 登录 GitHub。
- 点击右上角的头像 → Settings(设置)。

- 在左侧菜单选择 SSH and GPG keys。

- 点击 New SSH key 。

- 在 Title 中填写一个名称(例如:
My Laptop)。 - 在 Key 中粘贴你之前复制的公钥内容。

- 点击 Add SSH key。
测试 ssh 连接
运行以下命令测试是否成功连接:
ssh -T git@github.com# 第一次可能要输入yes来添加github主机密钥如果看到类似下面的信息,说明配置成功:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.完成
现在可以使用 SSH 地址克隆仓库了:
git clone git@github.com:username/repository.git如果你的远程仓库之前是 https 连接的,那可以运行如下命令改为 ssh 连接
- 查看仓库地址
应该有类似如下输出git remote -vorigin https://github.com/username/repo.git(fetch)origin https://github.com/username/repo.git(push)
- 修改远程仓库的 URL 为 SSH 格式
# username和repo根据之前输出的仓库地址自行更改git remote set-url origin git@github.com:username/repo.git
- 验证远程仓库地址
运行以下命令查看当前远程仓库的 URL:
输出应类似于:git remote -vorigin git@github.com:yourname/yourrepo.git (fetch)origin git@github.com:yourname/yourrepo.git (push)
如果你的远程仓库名称不是
origin,请替换为对应的名称。例如:git remote set-url <remote-name> git@github.com:username/repo.git
有什么用?
- 更加安全
- 更加方便,避免HTTPS频繁验证问题
- 似乎还能解决一些访问github时遇到的网络问题
之前在服务器上https连接不能推送,但是换成ssh连接就能推送了
如何使用ssh连接github仓库
https://locxl.site/posts/如何使用ssh连接github仓库/ 部分信息可能已经过时
鄂公网安备42011102005849号