如何在Linux中设置无密码登录
时间:2019-08-20 17:58:29 来源:igfitidea点击:
测试环境
主机名:Server1,用户名:test
主机名:Server2,用户名:test
我们想从Server1 不需要密码直接ssh登录到Server2。
使用用户test登录到server1.
执行下面命令
[test@server1 ~]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/test/.ssh/id_rsa): Created directory ‘/home/test/.ssh’. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/test/.ssh/id_rsa. Your public key has been saved in /home/test/.ssh/id_rsa.pub. The key fingerprint is: 49:a4:1e:b8:df:13:36:fa:25:5a:d3:d2:f5:9e:77:98 test@server1 [test@server1 ~]$
将会生成两个文件 id_rsa 和 id_rsa.pub
[test@server1 ~]$ ls -lrt .ssh/ total 8 -rw-r–r– 1 test test 410 Nov 27 23:06 id_rsa.pub -rw——- 1 test test 1671 Nov 27 23:06 id_rsa [test@server1 ~]$
把id_rsa.pub这个文件传到服务器server2中
[test@server1 ]$ cd /home/test/.ssh [test@server1 .ssh]$ ls -lrt total 8 -rw-r–r– 1 test test 410 Nov 27 23:06 id_rsa.pub -rw——- 1 test test 1671 Nov 27 23:06 id_rsa [test@server1 .ssh]$ [test@server1 .ssh]$ scp id_rsa.pub test@server2:~
使用test登录到Server2
检查.ssh目录是否存在
[ test@server2 }$ ls -ld /home/test/.ssh
如果不存在,则创建一个
[ test@server2 }$ mkdir -p /home/test/.ssh
在.ssh中创建一个新文件authorized_keys
[test@server2 .ssh]$ cd /home/test/.ssh [test@server2 .ssh]$ touch authorized_keys [test@server2 .ssh]$ ls authorized_keys
将id_rsa.pub(从server1中上传的)的内容复制到 authorized_keys
[[email protected]]$ cd ~ [test@server2 ~]$ [test@server2 ~]$ cat id_rsa.pub >> /home/test/.ssh/authorized_keys
检查.ssh和authorized_keys的所有者和权限,应该像下面这样
[test@server2 ~]$ ls -ld .ssh/ drw-r-xr-x 2 test test 4096 Nov 27 22:56 .ssh/ [test@server2 ~]$ [test@server2 ~]$ ls -lrt .ssh/ total 4 -rw-r–r– 1 test test 412 Nov 27 22:55 authorized_keys [test@server2 ~]$ [test@server2 ~]$
Server2切换到root用户
检查ssh配置文件
vi /etc/ssh/sshd_config RSAAuthentication yes PubkeyAuthentication yes
重启或重新加载sshd服务
/etc/init.d/sshd reload /etc/init.d/sshd restart
测试
现在我们就可以在Server1上通过test用户,不需密码登录到Server2中了
[test@server1 ~]$ ssh test@server2的ip