ssh免密登陆

ssh无密码登录要使用公钥与私钥。linux下可以用用ssh-keygen生成公钥/私钥对,下面我以CentOS为例。

系统:CentOS7
主机:A(192.168.66.100);B(192.168.66.110)
为方面,用户都为root

1、在A下生成公钥/私钥对
命令:

ssh-keygen -t rsa -P ‘’

-P表示密码,-P '' 就表示空密码,也可以不用-P参数,这样就要三车回车,用-P就一次回车。
它在/root下生成.ssh目录,其他用户的话在对应的家目录下(/home/用户名),.ssh下有id_rsa和id_rsa.pub。

2、将把A机下的id_rsa.pub复制到B机下,在B机的.ssh/authorized_keys文件里。
方式一:

ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.66.110

方式二:
    使用scp将文件复制过去

scp .ssh/id_rsa.pub chenlb@192.168.66.110:/root/id_rsa.pub

    回车后输入B的root密码
        root@192.168.66.110's password:
          id_rsa.pub                                    100%  223     0.2KB/s   00:00

3、B机把从A机复制的id_rsa.pub添加到.ssh/authorzied_keys文件里。

[root@B ~]# cat id_rsa.pub >> .ssh/authorized_keys
[root@B ~]# cat id_rsa.pub >> .ssh/authorized_keys

   authorized_keys的权限要是600。

[root@B ~]# chmod 600 .ssh/authorized_keys


4、A机登陆B机

 [root@A ~]# ssh root@192.168.66.110
 The authenticity of host '192.168.66.110 (192.168.66.110)' can't be established.
 RSA key fingerprint is 00:a6:a8:87:eb:c7:40:10:39:cc:a0:eb:50:d9:6a:5b.
 Are you sure you want to continue connecting (yes/no)? yes
 Warning: Permanently added '192.168.66.110' (RSA) to the list of known hosts.
 Last login: Thu Jul  3 09:53:18 2017 from root

    第一次登录是时要你输入yes。

5、现在A机可以无密码登录B机了。

小结:登录的机子可有私钥,被登录的机子要有登录机子的公钥。这个公钥/私钥对一般在私钥宿主机产生。上面是用rsa算法的公钥/私钥对,当然也可以用dsa(对应的文件是id_dsa,id_dsa.pub)

注意一:
CentOS默认公钥登陆关闭状态需要开启
修改配置文件:/etc/ssh/sshd_conf
命令:

vim /etc/ssh/sshd_conf

    找到下面两行注释将前面的#去掉并将后面的no改为yes

 RSAAuthentication yes
 PubkeyAuthentication yes

    重启sshd服务:  

systemctl restart sshd


注意二:
SSH出现 The authenticity of host xxx can't be established.
使用ssh连接远程主机时加上“-o StrictHostKeyChecking=no”的选项,去掉对主机的验证检查。

ssh  -o StrictHostKeyChecking=no  主机地址


问题一:上述操作完成后免密登陆失败时,查看配置文件/etc/ssh/sshd_conf
命令:

vim /etc/ssh/sshd_conf

    在配置文件中修改:
        严苛模式:
        StrictModes no

    :wq保存退出
    重启sshd服务:   

systemctl restart sshd


问题二:如果遇到权限不够,无法修改读取authorzied_keys文件中的内容
    修改.ssh文件夹的权限为777

chmod -R 777 ~/.ssh


问题三:
SSH出现Agent admintted fauiler to sign using password!
使用 ssh-agent bash

ssh-add ~/.ssh/id_rsa