【问题标题】:How to change a connection to GitHub from SSH to HTTPS?如何将与 GitHub 的连接从 SSH 更改为 HTTPS?
【发布时间】:2015-08-21 09:35:43
【问题描述】:

我昨天在 GitHub 上创建了我的第一个存储库。建立连接时,我使用 SSH 而不是 HTTPS,所以我经历了一个痛苦的 SSH 密钥创建和连接过程。在某些时候,我被卡住了,连接失败了。那时我想知道如何恢复我开始的过程并从 HTTPS 连接开始。令人高兴的是,今天我通过 SSH 建立了连接,但我想知道能够更改连接类型(SSH 与 HTTPS)的价值以及是否有办法做到这一点。

【问题讨论】:

  • 如果你想将git push本地修改为github,你最好保持ssh连接。阅读一些 ssh 教程,并配置私钥和公钥以避免多次输入密码。
  • @BasileStarynkevitch,SSH 和 HTTPS 连接都可用于push 到 GitHub(和许多其他主机)。
  • 我通常对 .git/config 文件进行文本编辑,而不是 git remote set-url。您只需要在某些 repo 服务器上观察两者的不同 url 结构。
  • 我经常使用 https 作为 fetch url 和 ssh 作为 Push url,好处是我不需要解锁我的 ssh 密钥来随机获取。

标签: git github ssh https git-remote


【解决方案1】:

假设你的遥控器叫做origin,运行

  • git remote set-url origin https://...
  • git remote set-url --push origin https://...

您可以使用git remote -v 查看配置的遥控器,现在应该会显示您更新后的网址。

更多详情请见the documentation for git-remote

【讨论】:

    【解决方案2】:

    这里有一些别名(oneliners)可以将你的 repo 从 ssh 切换到 https 并返回。假设您的默认遥控器名为 origin 并且您的遥控器是 github.com

    alias git-https="git remote set-url origin https://github.com/$(git remote get-url origin | sed 's/https:\/\/github.com\///' | sed 's/git@github.com://')"
    alias git-ssh="  git remote set-url origin git@github.com:$(    git remote get-url origin | sed 's/https:\/\/github.com\///' | sed 's/git@github.com://')"
    

    它们比使它们具有幂等性所需的时间长一些

    【讨论】:

    • 谢谢。以下版本适用于非 github.com 和路径中有或没有前导 / 的 URL:git remote set-url origin $(git remote get-url origin | sed 's/^git@\(.*\):\/*\(.*\).git/https:\/\/\1\/\2.git/')
    • .. 和 @TimBunce 的版本相反:git remote set-url origin $(git remote get-url origin | sed 's/^https:\/\/\([^\/]*\)\/\(.*\).git/git@\1\:\2.git/')(假设结果的路径中不应有前导 /)。
    【解决方案3】:

    把这些别名定义放在你的~/.bashrc:

    alias git-ssh='git remote set-url origin "$(git remote get-url origin | sed -E '\''s,^https://([^/]*)/(.*)$,git@\1:\2,'\'')"'
    
    alias git-https='git remote set-url origin "$(git remote get-url origin | sed -E '\''s,^git@([^:]*):/*(.*)$,https://\1/\2,'\'')"'
    

    那么,

    • https切换到sshgit-ssh
    • ssh切换到httpsgit-https

    通过 github.comgitlab.com repos 成功测试。

    注意:我使用-E 表示扩展正则表达式,我使用逗号而不是通常的斜线来分隔替换操作的各个部分。这些共同帮助减少了leaning toothpick syndrome

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2019-11-12
      • 2016-05-18
      相关资源
      最近更新 更多