首页 文章

如何让git默认为ssh而不是https用于新的存储库

提问于
浏览
148

这些天,当我在设置页面上的GitHub上创建一个新的存储库时,我得到:

git remote add origin https://github.com/nikhilbhardwaj/abc.git
git push -u origin master

每当我必须提交提交时,我需要输入我的GitHub用户名和密码 .

我可以手动将其更改为

git@github.com:nikhilbhardwaj/abc.git

.git/config . 我觉得这很烦人 - is there some way I can configure git to use SSH by default?

5 回答

  • 240

    将存储库的origin分支设置为SSH

    GitHub存储库设置页面只是一个建议的命令列表(GitHub现在建议使用HTTPS协议) . 除非您拥有对GitHub网站的管理访问权限,否则我不知道有任何方法可以更改其建议的命令 .

    如果您更愿意使用SSH协议,只需添加一个类似的远程分支(即使用此命令代替GitHub的建议命令) . 要修改现有分支,请参阅下一节 .

    $ git remote add origin git@github.com:nikhilbhardwaj/abc.git
    

    修改预先存在的存储库

    如您所知,要将预先存在的存储库切换为使用SSH而不是HTTPS,您可以更改 .git/config 文件中的远程URL .

    [remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        -url = https://github.com/nikhilbhardwaj/abc.git
        +url = git@github.com:nikhilbhardwaj/abc.git
    

    一个快捷方式是使用 set-url 命令:

    $ git remote set-url origin git@github.com:nikhilbhardwaj/abc.git
    

    有关SSH-HTTPS开关的更多信息

  • 40
    • GitHub
    git config --global url.ssh://git@github.com/.insteadOf https://github.com/
    
    • BitBucket
    git config --global url.ssh://git@bitbucket.org/.insteadOf https://bitbucket.org/
    

    这告诉git在连接到GitHub / BitBucket时总是使用SSH而不是HTTPS,因此默认情况下您将通过证书进行身份验证,而不是提示输入密码 .

  • 3

    response provided by Trevor is correct .

    但是这里有你可以直接添加到你的_713886中:

    # Enforce SSH
    [url "ssh://git@github.com/"]
      insteadOf = https://github.com/
    [url "ssh://git@gitlab.com/"]
      insteadOf = https://gitlab.com/
    [url "ssh://git@bitbucket.org/"]
      insteadOf = https://bitbucket.org/
    
  • 2

    如果您需要许多不同主机的密钥,请执行以下操作:

    创建一个脚本

    #!/usr/bin/env bash
    email="$1"
    hostname="$2"
    hostalias="$hostname"
    keypath="$HOME/.ssh/${hostname}_rsa"
    ssh-keygen -t rsa -C $email -f $keypath
    if [ $? -eq 0 ]; then
    cat >> ~/.ssh/config <<EOF
    Host $hostalias
            Hostname $hostname
            User git
        IdentitiesOnly yes
            IdentityFile $keypath
    EOF
    fi
    

    并运行它

    sh script.sh myemail@example.com github.com
    

    更改您的远程网址

    git remote set-url origin git@github.com:user/foo.git
    

    将〜/ .ssh / github.com_rsa.pub的内容添加到github.com上的ssh密钥

    检查连接

    ssh -T git@github.com
    
  • 119

    您可能在https而不是ssh中意外克隆了存储库 . 我在github上多次犯过这个错误 . 确保在克隆时首先复制ssh链接,而不是https链接 .

相关问题