Linux设置免密登录及原理
免密登录原理如下,简单明了( 图片来自于网络)
图解,server A免登录到server B:
1.在A上生成公钥私钥。
2.将公钥拷贝给server B,要重命名成authorized_keys(从英文名就知道含义了)
3.Server A向Server B发送一个连接请求。
4.Server B得到Server A的信息后,在authorized_key中查找,如果有相应的用户名和IP,则随机生成一个字符串,并用Server A的公钥加密,发送给Server A。
5.Server A得到Server B发来的消息后,使用私钥进行解密,然后将解密后的字符串发送给Server B。Server B进行和生成的对比,如果一致,则允许免登录。
总之:A要免密码登录到B,B首先要拥有A的公钥,然后B随机生成字符串,要做一次公钥加密。公钥加密后,将密文发给A,由机器A使用私钥解密,A将解密后得到的的字符串传送给B,B两字符串进行对比。若两字符串一致,则A可以免密登录B。
———————————————————————————————————————————————————————————————————————
方法
步骤一,生成A公私钥
dandeliondeMacBook-Pro:~ dandelion$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/Users/dandelion/.ssh/id_rsa): Created directory '/Users/dandelion/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /Users/dandelion/.ssh/id_rsa. Your public key has been saved in /Users/dandelion/.ssh/id_rsa.pub. The key fingerprint is: SHA256:WOCu7RVGa82QBXWxg44lj6ERZZmjHM9yqcG1klCFCDU dandelion@dandeliondeMacBook-Pro.local The key's randomart image is: +---[RSA 2048]----+ | .oEo++==o o. | | ooo+=o o . | | +oBB+o o | | .O**& . | | +*S = | | o.o . | | . . . | | . . | | . | +----[SHA256]-----+ dandeliondeMacBook-Pro:~ dandelion$ dandeliondeMacBook-Pro:.ssh dandelion$ pwd /Users/dandelion/.ssh dandeliondeMacBook-Pro:.ssh dandelion$ ls id_rsa id_rsa.pub dandeliondeMacBook-Pro:.ssh dandelion$
步骤二,将公钥拷贝到B机器
1 dandeliondeMacBook-Pro:.ssh dandelion$ ssh-copy-id -i id_rsa.pub root@192.168.3.163 2 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub" 3 /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed 4 /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 5 root@192.168.3.163's password: 6 7 Number of key(s) added: 1 8 9 Now try logging into the machine, with: "ssh 'root@192.168.3.163'" 10 and check to make sure that only the key(s) you wanted were added. 11 12 dandeliondeMacBook-Pro:.ssh dandelion$
方法二 拷贝
1.拷贝A机器的公钥id_rsa.pub到B机器: scp id_rsa.pub root@192.168.3.163:/home 2.将A的公钥加到B的授权列表 .ssh/authorized_keys 若不存在,手动创建: cat /home/id_rsa.pub >> ../.ssh/authorized_keys 3..ssh目录的权限必须是700 ,chmod 700 .ssh 4.授权列表authorized_keys的权限必须是600,chmod 600 authorized_keys
最后 成功免密登录
dandeliondeMacBook-Pro:.ssh dandelion$ ssh root@192.168.3.163 Last login: Sat Mar 21 20:37:52 2020 from 192.168.3.26 [root@localhost ~]#