导读 | 你可以配置 SSH 使用基于密钥的身份验证,而不是使用用户名密码的方式验证。为了使用密钥身份验证方式,你需要生成一对密钥(公钥与私钥—)。私钥作业 “密码” 保存在用户端,公钥放到用户想连接到的远端主机上。本地计算机通过私钥去验证远端主机上的公钥,以确定远端主机的 “合法” 性。 |
环境介绍:
两台虚拟机 —— workstation 和 servera,workstation 作为客户端,servera 作为服务端,我们现在就是要从 workstation 这台虚拟机上面,通过密钥验证的方式使用 ssh 连接到 servera。
通过 ssh-keygen 在 workstation 上面生成密钥对,并指定密钥的密码(如果不指定密码,则表示不使用密码,在使用密钥登录的时候,不会提示让你输入密码。)
[it@workstation ~]ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/it/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/it/.ssh/id_rsa. Your public key has been saved in /home/it/.ssh/id_rsa.pub. The key fingerprint is: SHA256:bUXox2I6qVu4frpCPSgXhFo8b48tc8qyzsv851UGaoc it@workstation.lab.test The key's randomart image is: +---[RSA 3072]----+ | . . .. | | = . .. | | o + .. .. | |. + o o+.o | | . BE S+=o | | . B.*o++ | | = =.oo. | | +. + o+. | | .B=.=B= | +----[SHA256]-----+ [it@workstation ~] ls .ssh/ id_rsa id_rsa.pub [it@workstation ~]$
id_rsa 是私钥,id_rsa.pub 是公钥(这里我使用的是系统默认的名称)
使用 ssh-copy-id 上传公钥到 servera
[it@workstation ~]$ ssh-copy-id -i .ssh/id_rsa it@servera /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/id_rsa.pub" The authenticity of host 'servera (10.10.10.25)' can't be established. ECDSA key fingerprint is SHA256:/Xj4qZo8BWSfrzHt3OpZ4sLuasIFYxd6Wf/ucFN2UL8. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys it@servera's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'it@servera'" and check to make sure that only the key(s) you wanted were added.
通过 ssh 连接到 servera,在弹出的窗口里输入私钥的密码(我 workstation 是图形界面的,所有会以弹出窗口的方式,让你输入密钥密码。)。
[it@workstation ~]ssh it@servera Last login: Thu Oct 29 14:41:13 2020 from 10.10.10.20 [it@servera ~]
有人可能会觉得这样一直重复输入密码很烦,有没有办法不输入密码?我们可以使用 ssh-agent 在 bash 进程中缓存私钥的密码。
[it@workstation ~]eval(ssh-agent) Agent pid 3191 [it@workstation ~]ssh-add .ssh/id_rsa Enter passphrase for .ssh/id_rsa: Identity added: .ssh/id_rsa (it@workstation.lab.test) [it@workstation ~] ssh it@servera Last login: Thu Oct 29 14:42:51 2020 from 10.10.10.20 [it@servera ~]$
因为密码是缓存在当前 bash 中的,当我们切换到一个新的 bash 时,将依然要输入私钥密码。
使用相同的方式,将密钥传输到 serverb 上。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/125660.html