最近公司因为源代码泄露的事情,要求我们将git拉取代码从http全部切换成ssh的方式,简单记录下操作过程,下面教你如何把 Git 仓库的远程地址(remote)改成 SSH 地址。

场景1: 已存在项目使用http(s),要改成ssh的

假设目前的git地址为https://github.com/username/repo.git

查看当前的git地址

1
git remote -v

会输出以下信息

1
2
origin  https://github.com/username/repo.git (fetch)
origin https://github.com/username/repo.git (push)

这个时候可以用set-url命令进行设置新的ssh方式,注意替换你自己的git地址和用户名

1
git remote set-url origin [email protected]:username/repo.git

再检查

1
git remote -v

输出应该变成:

1
2
3
origin  [email protected]:username/repo.git (fetch)
origin [email protected]:username/repo.git (push)

场景2:新初始化的git仓库设置ssh

注意!只适用于刚执行git init或者没有设置过git remote的地址,可以通过以下方式修改

1
git remote add origin [email protected]:username/repo.git

⚠ 这里:

  • origin 是远程名称(你也可以叫别的,比如 upstream)
  • git@github.com:username/repo.git 是 SSH 格式的仓库地址
    (替换成你自己的)

场景3:对已存在的git仓库,想先删除再重新添加 remote

也可以这样:

1
2
git remote remove origin
git remote add origin [email protected]:username/repo.git

✨ 好出:

  • 更安全
  • 每次pull\push都输入密码

若没有配置过 SSH key,先生成 SSH key 并加到 GitHub:

1
ssh-keygen -t ed25519 -C "[email protected]"

然后把 ~/.ssh/id_ed25519.pub 内容复制到 GitHub → Settings → SSH and GPG keys。