这些天,当我在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 ?
将存储库的源分支设置为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的文章,以及如何避免重新输入密码
你需要在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