如何从 HTTPS 迁移到 SSH github

问题描述 投票:0回答:3

我使用 HTTPS 克隆了我的公司项目存储库,我想迁移到 SSH,因为它与我的个人 git 帐户冲突。如何迁移到 SSH 而不是使用 HTTPS?

git github ssh
3个回答
41
投票

步骤

  1. 创建 ssh 密钥
    ssh-keygen -t rsa -b 4096 -C "[email protected]"

输入密码,然后复制它

pbcopy < ~/.ssh/id_rsa.pub
如果您没有 pbcopy、xclip 或 vim,只需输入:
cat ~/.ssh/id_rsa.pub

将其添加到您的 GitHub 中 向您的 GitHub 帐户添加新的 SSH 密钥

  1. 删除 GitHub 凭据(如果您使用 HTTPS,则 GitHub 凭据很可能保存在您的系统中),我们不需要这些凭据,因为我们使用 SSH (可选步骤)

  2. 将远程 URL 更改为 SSH

>git remote set-url origin <SSH url>

示例:

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

  1. 输入密码

  2. 验证您的远程 URL 已更改

    git remote -v


3
投票

您需要生成 ssh 密钥,将其添加到您的个人资料中,然后更改 url

来源:https://help.github.com/en/enterprise/2.15/user/articles/adding-a-new-ssh-key-to-your-github-account

生成 ssh 密钥

  • 打开 Git Bash。
  • 运行
    ssh-keygen
    并按照屏幕上的消息进行操作(或只需单击 Enter 直至结束)
  • 复制密钥文件(公钥的内容)位于:

     ~/.ssh/id_rsa.pub
    

将密钥添加到Github

  • 在任意页面的右上角,单击您的个人资料照片,然后单击“设置”。

  • 在用户设置侧栏中,单击 SSH 和 GPG 密钥。

  • 单击新建 SSH 密钥或添加 SSH 密钥。

  • 将您的密钥粘贴到“密钥”字段中。

  • 单击添加 SSH 密钥。


0
投票

如果您来这里寻找批量执行此操作的方法(基于mike提出的通用格式):

#!/bin/bash

# Check if the Git repository is initialized
if [ ! -d .git ]; then
  echo "This directory is not a Git repository."
  exit 1
fi

# Get the current origin URL
origin_url=$(git config --get remote.origin.url)

# Check if the origin URL is empty
if [ -z "$origin_url" ]; then
  echo "No origin URL found."
  exit 1
fi

# Check if the origin URL is using HTTPS
if [[ $origin_url == https://* ]]; then
  # Extract domain, user, and repo name
  ssh_url=$(echo $origin_url | sed 's|https://\([^/]*\)/\([^/]*\)/\([^/]*\).git|git@\1:\2/\3|')

  # Change the origin URL to SSH
  git remote set-url origin $ssh_url

  echo "Git origin URL has been migrated from HTTPS to SSH."
else
  echo "Git origin URL is not using HTTPS."
fi

然后您可以对所有子目录运行此命令,如下所示:

find . -maxdepth 1 -type d -exec sh -c 'echo "Subdirectory: $0" && cd "$0" && ../migrate-to-ssh.sh; echo' {} \;
© www.soinside.com 2019 - 2024. All rights reserved.