PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

如何配置ssh服务使得不用输入账号密码即可连接远程主机

齐天大圣
齐天大圣 原创
2020-11-20 11:40:02 3083浏览

我们知道,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
$ ll
total 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

360截图1757111999115121_看图王.jpg

第二步、点击用户身份验证,然后选择方法为Public Key。然后输入用户名,这里我们填root。最后选择密钥,注意这里需要选择是的私钥,而不是公钥。

360截图17321130404837.jpg

这两步设置好了后,就完成了免密码登录了。

客户机为linux主机

第一步也是生成秘钥对

# ssh-keygen -t rsa
Generating 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@lijia
The 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 keys
root@121.196.12.64's password: 
Number of key(s) added: 1
Now 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.64
Welcome to Alibaba Cloud Elastic Compute Service !
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Fri Nov 20 10:28:37 2020 from 111.38.123.86
# 免密码登录成功

更多相关技术文章,请访问linux系统教程栏目!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。