学习目标:
掌握Git的知识
学习内容:
1.HTTPS和SSH方式的区别 2.完整配置SSH秘钥和公钥的步骤 3.多个github账号的SSH冲突解决 4.SSH端口被防火墙屏蔽问题解决 5.通过HTTPS或者SSH克隆私有项目学习时间:
2022.2.10学习产出:
1.HTTPS和SSH方式的区别
2.完整配置SSH秘钥和公钥的步骤
请看我该专栏的另外一篇文章
3.多个github账号的SSH冲突解决
首先cd到~/.ssh 使用 ssh-keygen -t -rsa -C ‘second@mail.com’ 生成新的SSH key:id_rsa_second,生成完后将新的SSH public key添加到github。
ssh-keygen -t -rsa -C 'second@mail.com'
默认SSH只会读取id_rsa,所以为了让SSH识别新的私钥,需要将其添加到SSH agent
ssh-add ~/.ssh/id_rsa_second
该命令如果报错:Could not open a connection to your authentication agent
. 无法连接到ssh agent,可执行ssh-agent bash
命令后再执行ssh-add
命令。
完成以上步骤后在~/.ssh目录创建config文件,该文件用于配置私钥对应的服务器。内容如下:
Default github user(first@mail.com)
Host github.com
HostName github.com
User git
IdentityFile C:/Users/username/.ssh/id_rsa
#second user(second@mail.com)
Host github-second
HostName github.com
User git
IdentityFile C:/Users/username/.ssh/id_rsa_second
配置完成后,在连接非默认帐号的github仓库时,远程库的地址要对应地做一些修改, 比如现在添加second帐号下的一个仓库test,则需要这样添加:
git remote add test git@github-second:second/test.git
#并非原来的git@github.com:second/test.git
这样每次连接都会使用id_rsa_second与服务器进行连接。至此,大功告成!
注意: github根据配置文件的user.email来获取github帐号显示author信息, 所以对于多帐号用户一定要记得将user.email改为相应的email(second@mail.com)。
4.SSH端口被防火墙屏蔽问题解决
设置SSH使用HTTPS的403端口
在局域网中SSH的22端口可能会被防火墙屏蔽,可以设置SSH使用HTTPS的403端口。
测试HTTPS端口是否可用
$ ssh -T -p 443 git@ssh.github.com
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.
编辑SSH配置文件 ~/.ssh/config 如下:
Host github.com
Hostname ssh.github.com
Port 443
测试是否配置成功
$ ssh -T git@github.com
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.
5.通过HTTPS或者SSH克隆私有项目
目前来说,github的私人项目已经可以免费使用了一段时间,但是当你用普通的clone方式去下载到本地的时候,会发现提示clone失败,报错显示
remote: Repository not found.
fatal: repository ‘https://github.com/github-username/github-template-name.git’ not found
正常来说,clone的链接格式一般是
https://github.com/github-username/github-template-name.git
那么当你想要在本地clone自己的私人项目的时候,为了私人项目的安全,就需要加上账号与密码进行验证
git clone https://github-username:github-password@github.com/github-username/github-template-name.git
在clone的时候,在https://后面先加上github-username:github-password,再@项目的链接就可以正常的把项目clone下来,这是相对比较简单的clone自己的私人项目的方法。
有些图形化的Git软件,可以提示你输入账户和密码,这样就比较方便。比如说
输入私有仓库的HTTPS的链接,点击克隆,它会自动弹出输入框,让你输入账号密码,这比较人性化
但是,SourceTree这个软件
输入HTTPS的链接,无法克隆。因为这是私有仓库
解决办法就是在SourceTree登录远程账户
便可拉取私有仓库
或者,使用SSH链接的方式也可以达到需求。因为SSH通过秘钥和公钥进行匹配,不需要输入账户和密码