这些天,当我在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。我发现这很烦人——有没有什么方法可以配置git默认使用SSH ?


当前回答

Trevor提供的回答是正确的。

但是下面是你可以直接在你的.gitconfig中添加的:

# 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/

其他回答

而这里的其他答案直接回答了标题问题(以一种我不知道可能的方式!)关于自动神奇地将基于https的远程转换为git+ssh的远程,“正常”的方法从一开始就“正确”地做到这一点是不给git https url。

GitHub(以及其他流行的git托管服务)总是有一个小按钮,让你得到git应该克隆的URL。你只需要点击一个小小的“SSH”按钮:

或者是一个新项目

一旦你选择了“SSH”选项,GitHub(和其他人)就会记住(只要你登录了),并在未来将其设置为默认。

SSH文件

~/.ssh/config file
Host *
    StrictHostKeyChecking no
    UserKnownHostsFile=/dev/null
    LogLevel QUIET
    ConnectTimeout=10
Host github.com
        User git
        AddKeystoAgent yes
        UseKeychain yes
        Identityfile ~/github_rsa

编辑 reponame/.git/config

[remote "origin"]
        url = git@github.com:username/repo.git

供参考-我使用这个是因为github不再允许ssh:

[url "git@github.com:"]
    insteadOf = https://github.com/
[url "git@gist.github.com:"]
    insteadOf = https://gist.github.com/

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

GitHub存储库设置页面只是一个建议的命令列表(GitHub现在建议使用HTTPS协议)。除非你对GitHub的网站有管理权限,否则我不知道有什么方法可以改变他们建议的命令。

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

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

修改预先存在的存储库

如您所知,要将现有存储库切换为使用SSH而不是HTTPS,您可以在.git/配置文件中更改远程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开关的更多信息

“为什么Git总是问我密码?”- GitHub帮助页面。 GitHub的切换到智能HTTP相关的StackOverflow问题 用于手腕友好的Git使用的凭据缓存- GitHub博客关于HTTPS的文章,以及如何避免重新输入密码

Trevor提供的回答是正确的。

但是下面是你可以直接在你的.gitconfig中添加的:

# 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/