我使用 HTTPS 克隆了我的公司项目存储库,我想迁移到 SSH,因为它与我的个人 git 帐户冲突。如何迁移到 SSH 而不是使用 HTTPS?
步骤
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 密钥
删除 GitHub 凭据(如果您使用 HTTPS,则 GitHub 凭据很可能保存在您的系统中),我们不需要这些凭据,因为我们使用 SSH (可选步骤)
将远程 URL 更改为 SSH
>git remote set-url origin <SSH url>
示例:
git remote set-url origin [email protected]:username/repo_name.git
输入密码
验证您的远程 URL 已更改
git remote -v
您需要生成 ssh 密钥,将其添加到您的个人资料中,然后更改 url
来源:https://help.github.com/en/enterprise/2.15/user/articles/adding-a-new-ssh-key-to-your-github-account
ssh-keygen
并按照屏幕上的消息进行操作(或只需单击 Enter 直至结束)复制密钥文件(公钥的内容)位于:
~/.ssh/id_rsa.pub
如果您来这里寻找批量执行此操作的方法(基于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' {} \;