这些天,当我在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而不是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文件

~/.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

你需要在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

将存储库的源分支设置为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/