Linux密钥认证及Windows使用密钥连接Linux

概述

Linux中我们要连接主机,输入用户名密码然后连接,我们发现每次连接都要输入密码,对于一些批量操作不方便
我们需要一种新的认证方式,每次连接不需要输入密码,这个方法就叫密钥认证

密钥认证原理

image

原理详解:

  1. 使用ssh-keygen命令生成私钥和公钥。
  2. 使用ssh-copy-id命令将公钥发送到目标服务器端。
  3. 本地发送连接请求至目标服务器
  4. 目标服务器携带公钥加密询问发送至本地
  5. 本地用私钥解密发送会目标服务器
  6. 目标服务器进行验证,验证通过建立连接

创建密钥及分发密钥

创建密钥

使用ssh-keygen命令创建

root@master-01:~# 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:k3DbjIYDG3PPlfVgCdTgae4WvtIcLI5mlvyfGGohn6E root@master-01
The key's randomart image is:
+---[RSA 2048]----+
|         .+++.   |
|         . =oo   |
|    + o . *   .  |
|     * * X       |
|    . o S.=      |
|    . oo.+o.     |
|     = B.++.     |
|    E @.o+oo     |
|     =..oo+      |
+----[SHA256]-----+

#创建好的私钥和公钥默认存储在/root/.ssh/目录下
root@master-01:~# ll /root/.ssh/
total 12
-rw------- 1 root root    0 Feb 17 10:31 authorized_keys
-rw------- 1 root root 1823 Mar 31 15:38 id_rsa
-rw-r--r-- 1 root root  396 Mar 31 15:38 id_rsa.pub
-rw-r--r-- 1 root root  888 Mar 14 15:23 known_hosts

root@master-01:~#

上面演示的为创建密钥,输入ssh-keygen命令之后,连续三个回车即可,创建好的密钥保存在/root/.ssh目录下面,id_rsa为私钥,id_rsa.pub为公钥

一键创建密钥对

ssh-keygen -f /root/.ssh/id_rsa -P ''

-f 指定密钥文件位置和文件名
-P 指定密码短语,''或者""表示设置为空

分发密钥

使用ssh-copy-id命令进行分发
语法:ssh-copy-id [-i [identity_file]] [user@]machine

#分发密钥
root@master-01:~# ssh-copy-id -i /root/.ssh/id_rsa.pub root@10.3.0.85
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/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@10.3.0.85's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@10.3.0.85'"
and check to make sure that only the key(s) you wanted were added.


windows中使用密钥连接Linux

Windows使用密钥连接Linux很简单,我们生成密钥之后,将公钥(id_rsa.pub)写入到authorized_keys文件中,然后将私钥(id_rsa)保存到Windows本地,Windows连接Linux时使用该私钥即可

#将公钥写入到authorized_keys文件中
root@master-01:~/.ssh# cat /root/.ssh/id_rsa.pub >> authorized_keys
posted @ 2025-03-31 15:50  huangSir-devops  阅读(298)  评论(0)    收藏  举报
作者:你的名字
出处:你的博客链接
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。