Featured image of post 「git」从克隆到同步

「git」从克隆到同步

实践是检验真理的唯一标准。—— 光明日报


git 克隆项目后更换为ssh地址记录

git clone 拉取了代码(通常默认是 HTTPS 地址),现在想要切换为 SSH 地址以便实现免密推送,按照以下步骤操作即可:

  1. 获取仓库的 SSH 地址 在 GitHub/Gitee 的仓库页面,点击 Code 按钮,选择 SSH 选项卡,复制类似 git@github.com:用户名/仓库名.git 的地址。

  2. 修改远程仓库地址 在本地仓库根目录下,使用 set-url 命令将原本的 origin 地址替换为 SSH 地址:

1
git remote set-url origin git@github.com:用户名/仓库名.git

git remote常用指令:

  • git remote:列出当前仓库中已配置的远程仓库。
  • git remote -v:列出当前仓库中已配置的远程仓库,并显示它们的 URL。 git remote add <remote_name> <remote_url>:添加一个新的远程仓库。指定一个远程仓库的名称和 URL,将其添加到当前仓库中。
  • git remote rename <old_name> <new_name>:将已配置的远程仓库重命名。
  • git remote remove <remote_name>:从当前仓库中删除指定的远程仓库。
  • git remote set-url <remote_name> <new_url>:修改指定远程仓库的 URL。
  • git remote show <remote_name>:显示指定远程仓库的详细信息,包括 URL 和跟踪分支。
  1. 验证修改是否成功 运行以下命令查看远程链接:
1
git remote -v
  • 如果输出显示为 git@github.com:… 而不再是 https://…,说明设置成功。
  1. 本地生成 SSH 密钥,把公钥添加到 GitHub。

快速解决:

  • 生成密钥: 运行 ssh-keygen -t rsa -C “你的邮箱”(一路回车即可)。
  • 获取公钥内容: 运行 cat ~/.ssh/id_rsa.pub 并复制输出的内容。
  • 添加到 GitHub: 进入 GitHub 的 Settings -> SSH and GPG keys -> New SSH Key,把刚才复制的内容贴进去保存。
  1. 运行测试命令 在终端输入以下命令:
1
ssh -T git@github.com

看到的结果:

  • 如果是第一次连接: 你会看到一段警告,提示无法确认主机的真实性。
  • The authenticity of host ‘github.com (IP ADDRESS)’ can’t be established.Are you sure you want to continue connecting (yes/no)?
  • 输入 yes 并回车即可。
  • 如果测试成功: 你会看到类似下面的欢迎信息(包含你的 GitHub 用户名):
  • Hi [你的用户名]! You’ve successfully authenticated, but GitHub does not provide shell access.
  • 如果测试失败: 你会看到错误提示,通常是:Permission denied (publickey).

至此就可以通过ssh免密管理仓库了。

热爱生活 学无止境
使用 Hugo 构建
主题 StackJimmy 设计