使用秘钥登录linux服务器
介绍
有时候我们希望不用每次登录linux服务器都要输入密码,那么这个时候可以选择ssh密钥登录,就是rsa公钥放到服务器上,私钥放在客户端上,每次登录的时候,用密钥登录;这样更方便也更安全
两台主机(服务器)秘钥登录流程图
我们从A主机(左边)秘钥登录到B服务器(右边)
A主机生成公钥
生成公钥私钥,一般不需要特殊设置一路回车默认下一步即可
> ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:+ims1qKnA9kAUbwuaGmGLdg+V4w1PMj7RO4gMHI7NCU root@JD
The key's randomart image is:
+---[RSA 2048]----+
|.+. |
|. E . |
|. = o |
|= = o * |
|=%.o B oS |
|O=O + =. |
|+= o O. |
| + = *. . |
| oO.o .o |
+----[SHA256]-----+
查看公钥
> ls -al ~/.ssh
-rw------- 1 root root 1675 May 7 21:39 id_rsa //私钥
-rw-r--r-- 1 root root 389 May 7 21:39 id_rsa.pub //公钥
> cat id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDULg8kwT2rW8Z/r0h5lvO6KziZWV1roM/0eKVnkxeKOF9A0JAL46WF4ZA2XsNfG2camxTekC0ZwArB6uvFQTR8RZtDCwdsdsdsds6K3ytR/FOzira6z+7xbk6LvPylaCLfjfMmta04Q7dsdsdsdsdsds5MDr7oY73TWt2XToDA3FynMnl9MQjO4SoTU/Z1PiKsdOoCnbeP/O6KL+6sh9tbd5HoPPLm8LtDCeebZNhvZSulsbeTFZ5Z+HzPLostXJVhRFtiwUlaemAhXngVdIB5D9feXCYdQiP3NM0zAI94XUFCFyaSnZdv3+OTqHmxJ root@local
id_rsa.pub公钥要发送到B服务器
B服务器添加A主机的公钥
在B服务器对应登录账号的家目录下的.ssh/authorized_keys文件添加A主机的公钥
比如我们要使用code404账号进行秘钥登录,就是配置/home/code404/.ssh/authorized_keys
> cat /home/code404/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDULg8kwT2rW8Z/r0h5lvO6KziZWV1roM/0eKVnkxeKOF9A0JAL46WF4ZA2XsNfG2camxTekC0ZwArB6uvFQTR8RZtDCwdsdsdsds6K3ytR/FOzira6z+7xbk6LvPylaCLfjfMmta04Q7dsdsdsdsdsds5MDr7oY73TWt2XToDA3FynMnl9MQjO4SoTU/Z1PiKsdOoCnbeP/O6KL+6sh9tbd5HoPPLm8LtDCeebZNhvZSulsbeTFZ5Z+HzPLostXJVhRFtiwUlaemAhXngVdIB5D9feXCYdQiP3NM0zAI94XUFCFyaSnZdv3+OTqHmxJ root@local
给公钥及目录添加权限
> chmod 600 /home/code404/.ssh/authorized_keys
> chmod 700 /home/code404/.ssh
sshd服务安全配置 开启秘钥登录
> vim /etc/ssh/sshd_config
RSAAuthentication yes
PubkeyAuthentication yes
重启sshd服务
密钥方式登录成功后,再禁用密码登录
一定要秘钥登录成功后,再禁用密码登录。
> service sshd restart
> vim /etc/ssh/sshd_config
PasswordAuthentication no
> service sshd restart
秘钥登录测试 A主机的命令行输入
> ssh code404@B服务器ip
Last login: Tue Mar 11 11:23:22 2021
CSDN_码404:使用秘钥登录linux服务器
https://www.code404.icu/1485.html