本文主要记录linux免密登录的原理
前提
- 有两台机器A和B
- A需要免密登录机器B(反之则按照下面步骤从B操作到A)
实现原理
- 在机器A上生成一对公私钥
- A将公钥拷贝给B,在B中重命名为authorized_keys(放在当前用户目录下的.ssh目录下)
- A向B发送一个登录链接请求
- B得到A的登录请求信息后,在authorized_keys中查找,如果有相应的用户名和IP,则随机生成一个字符串string_text,并且使用A的公钥加密,随后发送给A
- A接收到B发送过来的消息后,使用自己的私钥解密,然后将解密后的字符串发送给B
- B接收到A解密后的字符串,检查是否与string_text一致,如果一致则允许免密登录
操作步骤
- 在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机器
方式一:
dandeliondeMacBook-Pro:.ssh dandelion$ ssh-copy-id -i id_rsa.pub root@192.168.3.163
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "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@192.168.3.163's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.3.163'"
and check to make sure that only the key(s) you wanted were added.
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 ~]#