背景:在工作中,都会有一个工作的Git帐号(公司Gitlab),而空闲时间做的个人东西又想放进Github里面,这时候就需要配置两个帐号和服务器。假设之前已经配置好了工作的帐号,打开git bash:
#新建SSH key:
$ cd ~/.ssh # 切换到C:\Users\Administrator\.ssh
ssh-keygen -t rsa -C "youremail@example.com" # 新建工作的SSH key
# 设置名称为id_rsa_hason(名字随意)
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa_hason
因为默认只读取id_rsa,为了让SSH识别新的私钥,需将其添加到SSH agent中:
ssh-add ~/.ssh/id_rsa_hason
注意:如果出现Could not open a connection to your authentication agent,参考底部详情
若~/.ssh/目录下不存在config文件,则新建一个,内容写上:
# 该配置用于工作
# Host 服务器别名
Host 192.168.2.36
# HostName 服务器ip地址或机器名
HostName 192.168.2.36
# User连接服务器的用户名
User huanghs
# IdentityFile 密匙文件的具体路径
IdentityFile C:/Users/P/.ssh/id_rsa
# 该配置用于个人 github 上
# Host 服务器别名
Host github.com
# HostName 服务器ip地址或机器名
HostName github.com
# User连接服务器的用户名
User hasonHuang
# IdentityFile 密匙文件的具体路径
IdentityFile C:/Users/P/.ssh/id_rsa_hason
把~/.ssh/id_rsa_hason.pub的内容添加到Github的SSH keys中
使用ssh -T git@Host进行测试,其中Host指上面配置的服务器别名
ssh -T git@github.com
常见问题:
出现Could not open a connection to your authentication agent
3种解决方法:
先输入ssh-agent bash,然后再输入ssh-add ~/.ssh/id_rsa_hason;
先输入eval $(ssh-agent),然后输入ssh-add ~/.ssh/id_rsa_hason;
使用Git GUI生成密钥,密钥会自动被加进ssh-agent中;