Github配置 SSH Keys

先说一下,https 和 SSH 的区别:

1
2
3
1、前者可以随意克隆github上的项目,而不管是谁的;而后者则是你必须是你要克隆的项目的拥有者或管理员,且需要先添加 SSH key ,否则无法克隆。

2、https url 在push的时候是需要验证用户名和密码的;而 SSH 在push的时候,是不需要输入用户名的,如果配置SSH key的时候设置了密码,则需要输入密码的,否则直接是不需要输入密码的。

配置步骤:

1. 本地下载Git工具

​ 网址:https://git-scm.com/

2. 添加用户

打开Gitbash,输入

1
2
git config --global user.name 'your_name' # 设置用户名(github)
git config --global user.email 'your_email@example.com' # 设置邮箱(注册github时用的邮箱)

3. 添加SSH Keys

打开Gitbash,输入

1
ls -al ~/.ssh # 检查是否已存在ssh keys
1
ssh-keygen -t rsa -C "your_email@example.com" # 创建新的秘钥

接下来要求你输入密码,这个密码是使用SSH链接 push的时候用的,可以选择设,如果不想设 按Enter就可以了。 然后如果输出下面内容,表示key创建成功。

1
Your identification has been saved in /home/you/.ssh/id_rsa. #  Your public key has been saved in /home/you/.ssh/id_rsa.pub. # The key fingerprint is: # 01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db your_email@example.com

然后,把ssh key添加到github上

1
2
3
4
打开刚才的目录(例如/home/you/.ssh/id_rsa.pub),里面会有两个或三个文件:
id_rsa # 本地私钥
id_rsa.pub # 公钥
known_hosts # 前期可能没生成,这个只是日志记录文件,后期会生成,而且不重要

浏览器打开 https://github.com/settings/keys 点击“New SSH key”,标题可以随便起,key内容:将id_rsa.pub里面的内容复制到这里

4. 测试

打开Gitbash,输入

1
ssh -T git@github.com  # 试图连接github

如果看到提示,输入“yes”,按enter

最后会的得到以下信息:

1
Hi username! You've successfully authenticated, but GitHub does not provide shell access.

如果该用户名是你的,你已经成功设置SSH密钥!

此时,你用git克隆仓库时,HTTPS和SSH的方式都可以使用了。

5.Gitee 怎么配置SSH key

Gitee(码云)是另一个云端软件开发协作平台,能帮助开发者/团队/企业更好地管理代码。虽然它的社区活跃度没有GIthub高,但是因为是国产的,访问速度特别快。

所以,有些正在开发的软件,我会选择使用Gitee进行版本管理和协同开发。

Gitee怎么配置SSH key 呢?

我总结了一下,您也可以在官网地址:https://gitee.com/help/articles/4229#article-header0上查看更多帮助。

1
ssh-keygen -t ed25519 -C "xxxxx@xxxxx.com"   # 创建新的秘钥

官网提到SSH key的名称不要求必须是邮箱,这只是传统惯例而已。

其次,中间的编码使用ed25519和rsa不知道有什么区别,反正我是改成了rsa

后面的步骤跟github类似,验证使用下面的语句(如有提示,记得输入yes再enter)

1
ssh -T git@gitee.com

6.Git配置多个SSH-Key

背景

当有多个git账号时,比如:

a. 一个gitee,用于公司内部的工作开发;
b. 一个github,用于自己进行一些开发活动;

解决方法
  1. 生成一个公司用的SSH-Key
1
$ ssh-keygen -t rsa -C 'xxxxx@company.com' -f ~/.ssh/gitee_id_rsa
  1. 生成一个github用的SSH-Key
1
$ ssh-keygen -t rsa -C 'xxxxx@qq.com' -f ~/.ssh/github_id_rsa
  1. 在 ~/.ssh 目录下新建一个config文件(名称就是config,无后缀),添加如下内容(其中Host和HostName填写git服务器的域名,IdentityFile指定私钥的路径)
1
2
3
4
5
6
7
8
9
10
# gitee
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/gitee_id_rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa

4.用ssh命令分别测试

1
2
$ ssh -T git@gitee.com
$ ssh -T git@github.com

这里以gitee为例,成功的话会返回下图内容(如有提示,记得输入yes再enter)

1
Hi username! You've successfully authenticated, but GITEE.COM does not  provide shell access.
1
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2019-2022 PAYIZ
  • |

感谢您的支持😊

支付宝
微信