我们知道,ssh协议可以通过输入账号名和密码来连接远程的服务器。那么,可以免去输入账号和密码吗,直接登录。答案是可以的,并且在日常工作中,这种需求也是常见的。比如,使用scp来做异地备份,想要把scp写入到crontab中,但是在crontab肯定不能够输入账号密码的,那么就需要做免账号密码登录了。
ssh是一种非对称加密协议,有公钥和私钥。公钥是用来加密信息用的,各个主机中会在自己的家目录的.ssh目录下的known_hosts文件中存放其他主机的公钥。想要做免账号密码,关键点就是这个公钥。
假设一台服务器主机server,一台客户机client,客户机想要免登陆连接server。那么只需将客户机的公钥追加到server机的~/.ssh/authorized_keys末尾即可。下面分两种情况演示如何免密码登录:
客户机为windows系统
客户机为linux系统
客户机为windows系统
首先第一步需要去生成秘钥对,在这里,我们使用git工具来生成秘钥对(如何在windows系统上安装git,这个自己去查询,非常的简单,一路next即可)。
ssh-keygen
在git终端输入上述命令后,会有一系列的提示信息,直接输入enter键(共需输入三次enter)。之后,就可以在$homt/.ssh/目录下看到公钥以及私钥,以pub结尾的是公钥。
admin@laptop-7p19b9sh mingw64 ~/.ssh$ lltotal 13-rw-r--r-- 1 admin 197121 1679 5月 3 2019 id_rsa-rw-r--r-- 1 admin 197121 398 5月 3 2019 id_rsa.pub
接下来就把该公钥上传到服务器上,然后把该公钥信息追加到~/.ssh/authorized_keys中。
# cat id_rsa.pub >> .ssh/authorized_keys
下面演示如何使用xshell来免密码登录
第一步、输入远程主机的ip
第二步、点击用户身份验证,然后选择方法为public key。然后输入用户名,这里我们填root。最后选择密钥,注意这里需要选择是的私钥,而不是公钥。
这两步设置好了后,就完成了免密码登录了。
客户机为linux主机
第一步也是生成秘钥对
# ssh-keygen -t rsagenerating public/private rsa key pair.enter file in which to save the key (/root/.ssh/id_rsa): enter passphrase (empty for no passphrase): enter same passphrase again: your identification has been saved in /root/.ssh/id_rsa.your public key has been saved in /root/.ssh/id_rsa.pub.the key fingerprint is:sha256:gcyx2csye6yr7xcuuvof0omvp5feoxv0y2woqvmrb98 root@lijiathe key's randomart image is:+---[rsa 2048]----+| .*=oo || * ox.. || o b=.* e ||. + o+ o || ooooo. s ||.. +.+= || . ++*o || .o*+. || o=. |+----[sha256]-----+
第二步,将刚生产的公钥传送给另一台机器
# ssh-copy-id root@121.***.***.64/usr/bin/ssh-copy-id: info: source of key(s) to be installed: "/root/.ssh/id_rsa.pub"/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 keysroot@121.196.12.64's password: number of key(s) added: 1now try logging into the machine, with: "ssh 'root@121.***.***.64'"and check to make sure that only the key(s) you wanted were added.
第三步,登录远程主机
# ssh root@121.196.12.64welcome to alibaba cloud elastic compute service !activate the web console with: systemctl enable --now cockpit.socketlast login: fri nov 20 10:28:37 2020 from 111.38.123.86# 免密码登录成功
更多相关技术文章,请访问linux系统教程栏目!
以上就是如何配置ssh服务使得不用输入账号密码即可连接远程主机的详细内容。