Linux免密登录
需求在开发中我们每次ssh到linux服务器都需要输入密码,似乎有点麻烦。有没有什么办法?原理在机器A上生成一对公私钥A将公钥拷贝给B,在B中重命名为authorized_keys(放在当前用户目录下的.ssh目录下)A向B发送一个登录链接请求B得到A的登录请求信息后,在authorized_keys中查找,如果有相应的用户名和IP,则随机生成一个字符串string_text,并且使用A的公钥加密
·
需求
在开发中我们每次ssh到linux服务器都需要输入密码,似乎有点麻烦。有没有什么办法?
原理
- 在机器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一致,如果一致则允许免密登录
直接操作
1.在本机生成密钥对
ssh-keygen -t rsa
[root@localhost ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:ZjXg+lrUvwGd0KzMN+la0BMAZBRnwR+kYvrllZcl4Q8 root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
| oB+=o. . |
| o +.=.. . |
| + =.+.E .|
| + * *.= * |
| o S O @ o .|
| * o B + |
| + . = |
| o o o |
| . . . |
+----[SHA256]-----+
3.查看公钥私钥文件
[root@localhost ~]# cd /root/.ssh/
[root@localhost .ssh]# ll
总用量 8
-rw-------. 1 root root 1675 5月 7 07:34 id_rsa
-rw-r--r--. 1 root root 408 5月 7 07:34 id_rsa.pub
[root@localhost .ssh]#
4.将公钥拷贝到需要免密登录的服务器
免密登录的公钥统一放在目标服务器该文件:/root/.ssh/authorized_keys中,文件不存在自行创建。注意:多个公钥注意换行。
拷贝的方式有多种
1.手动拷贝
2.使用 ssh-copy-id方式
[root@localhost .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.9.131
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
^C
[root@localhost .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.131
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.1.131 (192.168.1.131)' can't be established.
ECDSA key fingerprint is SHA256:EpxAt5y1VDhmCCzkoYFE1ekn1+ZkGwY3fQ7FUybvuno.
ECDSA key fingerprint is MD5:4a:06:cb:1e:7d:c1:6b:f4:41:80:fb:6d:7c:b3:f5:a2.
Are you sure you want to continue connecting (yes/no)? yes
/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.1.131's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.1.131'"
and check to make sure that only the key(s) you wanted were added.
测试是否成功
执行 ssh 如果没有提示输入密码直接登录成功,表示已经配置好免密登录了。
root@localhost .ssh]# ssh root@192.168.1.131
Last login: Sat May 7 07:22:58 2022 from 192.168.1.1
[root@localhost ~]#
我们可以在远程该文件(/root/.ssh/authorized_keys )中查看公钥。
参考:
更多推荐
已为社区贡献2条内容
所有评论(0)