SSH密钥创建及登陆配置

一、SSH有关常识

SSH(Secure Shell)是一种能安全登陆和访问远程linux主机的协议。当然,前提是远程linux主机必须部署和配置sshd服务(linux默认安装此服务)。
远程linux主机的sshd服务能提供两种安全验证的方法,可以允许我们进行远程登陆和访问。
1)基于口令的验证-用户账户和密码来验证登陆。
2)基于密钥的验证-需要在生成密钥对,其中客户机中需存储密钥对中的私钥;而远程主机中必须存储密钥对中的公钥,且名称必须为authorized_keys。

二、密钥对创建及分配

假设远程主机ip为:192.168.10.10

1.客户机为linux系统,并确保能访问远程主机

1)通过ssh-keygen命令创建

[root@hollowman ~]# ssh-keygen
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:
d7:1b:9f:65:fd:9b:43:26:c3:8a:26:8f:04:98:2b:0a [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|                 |
|    o      .    .|
|   o .  S . +   +|
|    . .  .   B *.|
|E. .   .  . o B .|
|o .   ...o .   .o|
|.      .+.     o.|
+-----------------+

此时,密钥对创建成功,并保存在/root/.ssh目录下,其中私钥为id_rsa,公钥为id_rsa.pub

[root@hollowman ~]# ls /root/.ssh/
id_rsa  id_rsa.pub

2)将公钥上传至远程主机

[root@hollowman ~]# ssh-copy-id  192.168.10.10

此命令会将客户机中ssh密钥对中的公钥(id_rsa.pub)上传至远程主机中的/root/.ssh目录,并自动命名为authorized_keys

3)注意/root/.ssh目录必须为7权限,authorized_keys必须为6权限

2.客户机为windows

通过远程SSH协议工具(winscp,XShell,PuTTY等)来进行连接,前提是可以通过基于口令的验证方式登陆。

1)通过远程主机生成密钥对,并将私钥复制到客户机中(winscp可实现),供客户机中的SSH协议工具导入使用

在这里插入图片描述

也可通过客户机中的SSH协议工具生成密钥对,并将公钥上传至远程主机(winscp同样可实现);

2)确保远程主机中的公钥路径及名称格式正确(/root/.ssh/authorized_keys),并删除私钥(id_rsa)

[root@hollowman ~]# cd /root/.ssh
[root@hollowman .ssh]# mv id_rsa.pub authorized_keys
[root@hollowman .ssh]# rm -f id_rsa
[root@hollowman .ssh]# ls
authorized_keys

3)客户机SSH协议工具导入私钥(id_rsa),并通过基于密钥的验证方式访问远程主机

在这里插入图片描述

三、修改ssh配置文件(注意,是sshd_config而不是ssh_config)

[root@hollowman .ssh]# vim /etc/ssh/sshd_config
Port 22 //配置远程登录端口,默认为22端口 
PubkeyAuthentication yes // 授权密钥方式登录,默认允许 
AuthorizedKeysFile .ssh/authorized_keys // 授权密钥文件路径及名称,也就是为什么公钥要改名的原因 
PasswordAuthentication yes // 授权口令方式登陆,默认允许 
[root@hollowman .ssh]# systemctl restart sshd

猜你喜欢

转载自blog.csdn.net/ymz641/article/details/111465813