这些天,当我在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 ?


当前回答

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

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

或者是一个新项目

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

其他回答

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

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

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

你需要在ssh中克隆,而不是在https中。

$ ssh-keygen -t ed25519 -C "your_email@example.com"

添加~/.ssh/id_rsa的内容。在github.com上发布您的SSH密钥。

如果你需要为不同的主机设置不同的密钥,你可以使用这个脚本:

#!/usr/bin/env bash

if [ $# -lt 2 ]; then
  echo "Provide email and hostname"
  exit 1
fi

email="$1"
hostname="$2"
keypath="$HOME/.ssh/${hostname}_rsa"
ssh-keygen -t ed25519 -C $email -f $keypath

if [ ! $? -eq 0 ]; then
  echo "Error when running ssh-keygen"
  exit 1
fi

exit 0
cat >> $HOME/.ssh/config <<EOF
Host $hostname
        Hostname $hostname *.$hostname
        User git
    IdentitiesOnly yes
        IdentityFile $keypath
EOF

然后像这样运行

bash generate_ssh.sh your_email@example.com github.com

更改远程url

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

(或者直接编辑。git/config)

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

检查连接

ssh -T git@github.com

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

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

或者是一个新项目

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

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/