ssh协议原理
场景需求
win是多用户系统,操作系统自身并不提供管理多个ssh密钥对的功能。当某个用户需要使用ssh连接github,连接gitlab,连接gitte,连接远程服务器等等多个场景时,需要对多个密钥对进行管理和配置
使用步骤
以配置git多个账号和连接远程服务器为例:
- win11安装和配置ssh-agent为开机启动服务,详细的教程链接
- ssh的相关配置参数可以查看opensssh官网
- 生成公钥和私钥
- ssh-keygen -t rsa -C "yourgitlabemail",私钥保存到 ~/.ssh/id_rsa_gitlab
- ssh-keygen -t rsa -C "yourgithubemail",私钥保存到 ~/.ssh/id_rsa_github
- ssh-keygen -t rsa -C "servername",私钥保存到 ~/.ssh/id_rsa_servername
- 将生成的私钥添加到ssh-agent进行管理
- ssh-add ~/.ssh/id_rsa_gitlab
- ssh-add ~/.ssh/id_rsa_github
- ssh-add ~/.ssh/id_rsa_servername 输入ssh-add -l验证是否添加成功
- 如果ssh连接的服务器为ssh服务提供了shell
- ssh username@domain连上服务端
- linux默认用户公钥是保存在~/.ssh/authorized_keys(可通过sshd_config配置),
scp
/.ssh/id_rsa_servername.pub username@domain:/.ssh/authorized_keys 如果是github,gitlab等不对外提供shell的ssh服务,我们需要手动将公钥拷贝到网站 设定的位置,以github为例,github.com->yourprifile->setting->ssh,拷贝本地生 公钥~/.ssh/id_rsa_github到对应位置就可以了
到这里是不是完成了呢??? no,no,no,win系统是无法识别github,gitlab,server用的公钥是哪个,也就无法使用对应的私钥来加密和解密。简单说,服务器传递数据-本机使用服务器的公钥验证签名,本地的私钥解密数据,本地私钥加密数据,上传到服务器-服务器使用本机的公钥验证签名,使用服务器的私钥解密数据。我们需要在ssh_config添加配置
- 配置ssh_config,案例如下,host是hostname别名,user对应的账名,指定私钥验证路径IdentityFile
Host tengxunyun
HostName qtfs.site
User serveruseranme
Host github
HostName github.com
User githubname
IdentityFile ~/.ssh/id_rsa_github
Host gitlab
HostName gitlab.com
User gitlabname
IdentityFile ~/.ssh/id_rsa_gitlab
总结
管理多个ssh账号,首先是要操作系统能够识别到多个密钥对,ssh-agent添加管理私钥,其次是操作系统能够识别本地公钥对应的ssh服务,通过ssh_config来配置