ssh无密码登录需要使用公钥和私钥。linux环境下可以使用ssh-keygen命令生成密钥对。


有2台linux主机master:192.168.1.106    slave:192.168.1.107


1.创建密钥对

[root@master ~]# ssh-keygen -t rsa -P ''
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/master_rsa
Created directory '/root/.ssh'.
Your identification has been saved in /root/.ssh/master_rsa.
Your public key has been saved in /root/.ssh/master_rsa.pub.
The key fingerprint is:
da:1b:dc:e1:9e:e4:e8:67:b5:89:69:02:1d:5c:87:f9 root@master
The key's randomart p_w_picpath is:
+--[ RSA 2048]----+
|           o     |
|          + .    |
|       . . o     |
|        o   E    |
|       .S..      |
|      .+.o ..    |
|      ..+ ++ o   |
|        .B*.o    |
|       .+=+      |
+-----------------+
[root@master ~]# ll -d .ssh
drwx------. 2 root root 4096 1月  17 15:17 .ssh
[root@master ~]# ll  .ssh
总用量 8
-rw-------. 1 root root 1675 1月  17 15:17 master_rsa
-rw-r--r--. 1 root root  393 1月  17 15:17 master_rsa.pub

命令"ssh-keygen -t rsa -P ''"中的-t参数用于指定密钥类型,-P用于指定密码,因为我们要求ssh无密码登录,所以这里为空。而后可以指定密钥对的存放路径及密钥名称。


2. 在.ssh上创建.ssh目录,将公钥保存到slave的.ssh/authorized_keys文件中

[root@slave ~]# mkdir .ssh

[root@slave ~]# chmod 700 .ssh

[root@master ~]# scp .ssh/master_rsa.pub root@192.168.1.107:/root/.ssh
The authenticity of host '192.168.1.107 (192.168.1.107)' can't be established.
RSA key fingerprint is 2e:93:2c:ac:5e:cf:f5:d4:15:51:55:cb:ff:0a:b0:cf.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.107' (RSA) to the list of known hosts.
root@192.168.1.107's password:
master_rsa.pub                                                          100%  393     0.4KB/s   00:00    
[root@master ~]#
[root@slave ~]# chmod 600 .ssh/authorized_keys

如果提示未发现scp命令,就用yum -y install openssh-clients在两台机器上安装scp命令


3.清空iptables和关闭selinux,否则实验可能不成功

[root@slave ~]# iptables -F
[root@slave ~]# /etc/init.d/iptables save
iptables:将防火墙规则保存到 /etc/sysconfig/iptables:     [确定]
[root@slave ~]#

[root@slave ~]# setenforce 0

[root@slave ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

4.更改ssh_config文件

因为使用的不是预设的私钥名,所以要让ssh客户端程序监控自定义的私钥

echo "IdentityFile ~/.ssh/master_rsa"  >>/etc/ssh/ssh_config


测试实验结果

[root@master ~]# ssh root@192.168.1.107
Last login: Sun Jan 17 15:51:43 2016 from 192.168.1.106
[root@slave ~]# logout
Connection to 192.168.1.107 closed.
[root@master ~]#

如果要让slave登录master也无须密码登录时,只须重复上面的操作。