基于密钥认证登陆Linux服务器

时间:2022-12-03 16:55:45

基于密钥认证登陆Linux服务器

环境描述

  1. 服务端

    Linux操作系统,服务器上生成公私钥

  2. 客户端

    客户端上,只需导入私钥;客户端无限制、建议使用Xshell6、MobaXterm

技术点摘要

  1. ssh-keygen 介绍

    -b:指定密钥长度

    -e:读取openssh的私钥或者公钥文件

    -C:添加注释

    -f:指定用来保存密钥的文件名

    -i:读取未加密的ssh-v2兼容的私钥/公钥文件,然后在标准输出设备上显示openssh兼容的私钥/公钥

    -l:显示公钥文件的指纹数据

    -N:提供一个新密语

    -P:提供(旧)密语

    -q:静默模式

    -t:指定要创建的密钥类型

创建证书

例如: 创建名称为"hostname_id_rsa",密钥长度为4096,密钥类型为rsa,且注释为"jerry.pub@qq.com",密钥密码为"Hello"

$ ssh-keygen -t rsa -b 4096 -f hostname_id_rsa -C "jerry.pub@qq.com"

Generating public/private rsa key pair. 
Enter passphrase (empty for no passphrase):Hello
Enter same passphrase again:Hello
Your identification has been saved in hostname_id_rsa.
Your public key has been saved in hostname_id_rsa.pub.
The key fingerprint is:
SHA256:WipUC36qn93/r0Xm1JkdQ1y13xivpSISQYFcH+JcuKE jerry.pub@qq.com
The key's randomart image is:
+---[RSA 4096]----+
|     . o=oo   ..=|
|      o+o+ .  ...|
|    . ..+o.   .+ |
|   . oE...     =O|
|    o o S     =oB|
|   . o + .   = + |
|    o o . . . =  |
|   . + . . . o   |
|  ..o . ....oo.  |
+----[SHA256]-----+

查看证书

$ ssh-keygen -lf hostname_id_rsa

4096 SHA256:WipUC36qn93/r0Xm1JkdQ1y13xivpSISQYFcH+JcuKE jerry.pub@qq.com (RSA)

导入证书到SSH服务中ssh/authorized_keys

例如: 导入"hostname_id_rsa.pub"公钥到SSH服务器中

$ ssh-copy-id -i hostname_id_rsa.pub root@localhost -p 55020

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "hostname_id_rsa.pub"
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is SHA256:EKgJ8CkW7nSx0F2HlCBwxPQ0InxIzvYVH1PMGHUfvA4.
ECDSA key fingerprint is MD5:54:cd:e0:08:62:96:5b:d1:f1:85:18:50:d7:87:0b:84.
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@localhost's password: 

Number of key(s) added: 1

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

新增加证书到SSH服务中ssh/authorized_keys

例如: 增加"hostname02_id_rsa.pub"公钥到SSH服务器中

$ cat /root/hostname02_id_rsa.pub  >> /root/.ssh/authorized_keys

调整服务器设置

例如:调整SSHD服务支持公私钥认证

$ vi /etc/ssh/sshd_config

PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh2/authorized_keys

$ service sshd restart					#重启生效

客户端配置RSA证书认证方式

  1. 客户端Xshell导入证书-->结合私钥密码登陆服务器

  2. 客户端MobaXterm导入证书-->结合私钥密码登录服务器

  3. Linux跳板机使用私钥连接登录SSH_Server服务器(参考下面)

# 上传1030_id_rsa私钥文件到Linux跳板机上
# ssh-agent bash					# 启用密钥管理器

# chmod 400 1030_id_rsa				# 修改私钥文件权限(否则: Permissions 0644 for '1030_id_rsa' are too open)
# ssh-add 1030_id_rsa
	***		# 输入私钥密码
# ssh-add -l 						# 查看已导入的私钥
# ssh-add -d 1030_id_rsa			# 删除私钥
# ssh root@10.10.10.30 -p 16325		# 远程登录SSH-Server服务器

# 注意此过程只适用于当前会话,退出后将无法查询到已导入的证书