blog icon indicating copy to clipboard operation
blog copied to clipboard

SSH KEY 的管理

Open iq9891 opened this issue 4 years ago • 0 comments

生成一个 SSH-KEY

$ ssh-keygen -t rsa -C "[email protected]"

这时会在用户根目录下生成一个.ssh文件夹,一个私钥:id_rsa,一个公钥:id_rsa_pub,该公钥和私钥包含了你邮箱的信息,具有随机不可复现性!

ssh公钥私钥同时生成且唯一配对。公钥用于远程主机,私钥存储在本地工作机,私钥用于在push(即write操作)时验证身份。因为公钥与私钥的唯一对应性,只有能和公钥配对的私钥才能对远程主机进行写操作!

我们在使用github时会发现有两个地方牵涉到公钥添加,一个是账号设置下的ssh setting,另一个是单个仓库设置的Deploy key。添加至前者则代表 私钥主机可对当前远程主机的所有仓库进行写操作,添加至后者则代表 私钥主机只能对当前仓库进行写操作。

每次连接时SSH客户端发送本地私钥(默认~/.ssh/id_rsa)到远程主机进行公私钥配对验证!

同一工作主机,多个 ssh key

  • 生成新的ssh key并命名为second
ssh-keygen -t rsa -C "[email protected]" -f ~/.ssh/second

此时 ls 出 .ssh 目录,会发现多了 second 公钥和私钥

id_rsa
id_rsa.pub
known_hosts
list.txt
second
second.pub
  • 将ssh key添加到GitHub中

用自己喜欢的文本编辑器打开id_rsa.pub文件,里面的信息即为 SSH key,将这些信息复制到 GitHub 的 Add SSH key 页面即可

不同的操作系统,均有一些命令,直接将SSH key从文件拷贝到粘贴板中,如下:

  1. mac
pbcopy < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard
  1. windows
clip < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard
  1. linux
sudo apt-get install xclip
# Downloads and installs xclip. If you don't have `apt-get`, you might need to use another installer (like `yum`)

xclip -sel clip < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard
  • 在 ~/.ssh/ 目录下新建 config 文件,用于配置各个公私钥对应的主机
# Default github user([email protected])  默认配置,一般可以省略
Host github.com
Hostname github.com
User git
Identityfile ~/.ssh/github
# second user([email protected])  给一个新的Host称呼
Host second.github.com  // 主机名字,不能重名
HostName github.com   // 主机所在域名或IP
User git  // 用户名称
IdentityFile C:/Users/username/.ssh/id_rsa_second  // 私钥路径

注意:

  1. 每个邮箱能配置一个公私钥,邮箱是一个重要的身份识别标志
  2. 几个主机的命名不能相同;
  3. 私钥路径也可以写为 ~/.ssh/...;
  4. 如有需要还可以添加Port:xxxx端口配置。
  • 测试连接情况
$ ssh -T [email protected]

iq9891 avatar Jun 07 '21 01:06 iq9891