目录
1、采用 https 协议的缺点
如果你采用的是 https 协议提交代码到 github 的话,会发现每次 push 代码时都需要验证你的用户名和密码,这样就会很繁琐,我们可以通过使用 ssh 协议代替 https 协议的方法,这样就不需要在每次 push 代码的时候验证用户名和密码了,具体怎么做呢?
首先打开Git Bash,粘贴以下文本,替换为您的 GitHub 电子邮件地址。然后根据提示按三次回车,这时会在指定目录( 一般是:/c/Users/你的用户文件/.ssh/id_rsa)下生成ssh 的公要和私钥,id_rsa(私钥),id_rsa.puh(公钥),私钥谁都不好给,除非你想让你的代码晚节不保,公钥需要上传到 github。github 找到 Settings → SSH and GPG keys → New SSH key ,然后起一个 title 并将公钥复制到 Key 输入框中,完成。
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
这里有一篇 github 的帮助文档可参考:Generating a new SSH key and adding it to the ssh-agent
2、如何切换 https 到 ssh
公钥和私钥都已经生成完了,该有的 github 也配置完了。如果通过 ssh 协议 clone 的项目,以后在 push 的过程中就不需要验证用户名和密码了。但是这里有一个问题,如果你项目已经采用的是 https 协议了,那如何将 https 协议切换为 ssh 协议呢?
git remote -v <!--查看当前的 remote-->
origin https://github.com/yourUserName/ProjectName.git (fetch)
origin https://github.com/yourUserName/ProjectName.git (push)
<!--切换 http 到 ssh-->
git remote set-url origin [email protected]:yourUserName/ProjectName.git
完成如上操作之后,第一次提交代码到 github 会提示:The authenticity of host 'github.com' can't be established. Are you sure you want to continue connecting (yes/no/[fingerprint])?...字样的提示,这里直接输入 yes 即可,会提示一个 warning 后将代码 push 到 github 上,这样就完成了,而且在以后的 push 过程中都不需要验证用户名和密码。耶!