Linux下的SSH,你知道多少?
阅读原文时间:2021年07月09日阅读:1

Openssh介绍

  • OpenSSH 是 SSH (Secure Shell) 协议的免费开源实现。SSH协议族可以用来进行远程控制, 或在计算机之间传送文件。而实现此功能的传统方式,如telnet(终端仿真协议)、 rcp ftp、 rlogin、rsh都是极为不安全的,并且会使用明文传送密码。OpenSSH提供了服务端后台程序和客户端工具,用来加密远程控件和文件传输过程中的数据,并由此来代替原来的类似服务。

SSH工作原理

    

  • 1.服务器建立公钥: 每一次启动 sshd 服务时,该服务会主动去找 /etc/ssh/ssh_host* 的文件,若系统刚刚安装完成时,由于没有这些公钥,因此 sshd 会主动去计算出这些需要的公钥,同时也会计算出服务器自己需要的私钥。
  • 2.客户端主动联机请求: 若客户端想要联机到 ssh 服务器,则需要使用适当的客户端程序来联机,包括 ssh, putty 等客户端程序连接。
  • 3.服务器传送公钥给客户端: 接收到客户端的要求后,服务器便将第一个步骤取得的公钥传送给客户端使用 (此时应是明码传送,反正公钥本来就是给大家使用的)。
  • 4.客户端记录并比对服务器的公钥数据及随机计算自己的公私钥: 若客户端第一次连接到此服务器,则会将服务器的公钥记录到客户端的用户家目录内的 ~/.ssh/known_hosts 。若是已经记录过该服务器的公钥,则客户端会去比对此次接收到的与之前的记录是否有差异。若接受此公钥, 则开始计算客户端自己的公私钥。
  • 5.回传客户端的公钥到服务器端: 用户将自己的公钥传送给服务器。此时服务器:具有服务器的私钥与客户端的公钥,而客户端则是: 具有服务器的公钥以及客户端自己的私钥,你会看到,在此次联机的服务器与客户端的密钥系统 (公钥+私钥) 并不一样,所以才称为非对称加密系统。
  • 6.开始双向加解密:
    • (1)服务器到客户端:服务器传送数据时,拿用户的公钥加密后送出。客户端接收后,用自己的私钥解密。
    • (2)客户端到服务器:客户端传送数据时,拿服务器的公钥加密后送出。服务器接收后,用服务器的私钥解密,这样就能保证通信安全。

环境准备:

属性

跳板机

服务器-01

服务器-02

节点

wenCheng

Server-01

Server-02

系统

CentOS Linux release 7.5.1804 (Minimal)

CentOS Linux release 7.5.1804 (Minimal)

CentOS Linux release 7.5.1804 (Minimal)

内核

3.10.0-862.el7.x86_64

3.10.0-862.el7.x86_64

3.10.0-862.el7.x86_64

SELinux

setenforce 0 | disabled

setenforce 0 | disabled

setenforce 0 | disabled

Firewlld

systemctl stop/disabled firewalld

systemctl stop/disabled firewalld

systemctl stop/disabled firewalld

IP地址

172.16.70.182

172.16.70.186

172.16.70.187

检查sshd相关设置信息,以跳板机为例。

# 是否已安装
[root@wenCheng ~]# rpm -qa | grep ssh
libssh2-1.4.3-10.el7_2.1.x86_64
openssh-clients-7.4p1-16.el7.x86_64
openssh-7.4p1-16.el7.x86_64
openssh-server-7.4p1-16.el7.x86_64

是否已监听端口

[root@wenCheng ~]# netstat -untpl | grep ssh
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 882/sshd
tcp6 0 0 :::22 :::* LISTEN 882/sshd

查看ssh版本

[root@wenCheng ~]# ssh -V
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017

是否开机启动

[root@wenCheng ~]# systemctl is-enabled sshd.service
enabled

默认3对以不同方式加密的hostkey和配置文件config

[root@wenCheng ~]# ls -l /etc/ssh/ssh*
-rw-r--r--. 1 root root 2276 Apr 11 2018 /etc/ssh/ssh_config
-rw-------. 1 root root 3907 Apr 11 2018 /etc/ssh/sshd_config
-rw-r-----. 1 root ssh_keys 227 Dec 4 2020 /etc/ssh/ssh_host_ecdsa_key
-rw-r--r--. 1 root root 162 Dec 4 2020 /etc/ssh/ssh_host_ecdsa_key.pub
-rw-r-----. 1 root ssh_keys 387 Dec 4 2020 /etc/ssh/ssh_host_ed25519_key
-rw-r--r--. 1 root root 82 Dec 4 2020 /etc/ssh/ssh_host_ed25519_key.pub
-rw-r-----. 1 root ssh_keys 1679 Dec 4 2020 /etc/ssh/ssh_host_rsa_key
-rw-r--r--. 1 root root 382 Dec 4 2020 /etc/ssh/ssh_host_rsa_key.pub

默认/etc/ssh/sshd_config解析。

[root@Server-01 ~]# cat /etc/ssh/sshd_config
……

default value.

#Port 22            # 默认ssh端口;可去掉"#"自定义数字,例 Port 2211
#AddressFamily any      # 默认any:IPv4,IPv6
#ListenAddress 0.0.0.0    # 默认监听所有IP地址;可去掉"#"自定义方式,例 ListenAddress host|IPv4|IPv4_addr:port
#ListenAddress ::

私钥保存位置

HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

Ciphers and keying        # 密码和密钥

#RekeyLimit default none

Logging             # 日志

#SyslogFacility AUTH       # #当有人使用SSH登录系统的时候,SSH会记录信息
SyslogFacility AUTHPRIV
#LogLevel INFO          # 设置日志等级

Authentication:         # 身份认证

#LoginGraceTime 2m         # 限制登录时间不输入密码两分钟自动退出
#PermitRootLogin yes        # 是否允许root直接登录;建议设置为no
#StrictModes yes          # 是否检查.ssh/文件的所有者,权限
#MaxAuthTries 6           # 最大认证次数6;一般设为3
#MaxSessions 10           # 克隆会话最大连接

#PubkeyAuthentication yes     # 是否支持公钥验证(一般开启公钥验证关闭用户登录)

The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2

but this is overridden so installations will only check .ssh/authorized_keys

AuthorizedKeysFile .ssh/authorized_keys      # 基于公钥认证机制时,来自客户端的公钥的存放位置

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

For this to work you will also need host keys in /etc/ssh/ssh_known_hosts

#HostbasedAuthentication no

Change to yes if you don't trust ~/.ssh/known_hosts for

HostbasedAuthentication

#IgnoreUserKnownHosts no

Don't read the user's ~/.rhosts and ~/.shosts files

#IgnoreRhosts yes

To disable tunneled clear text passwords, change to no here!

#PasswordAuthentication yes      
#PermitEmptyPasswords no        # 是否允许空密码,如果使用密码验证,这里最好设置no
PasswordAuthentication yes       # 是否使用密码验证,如果使用密钥对验证可以改为no

Change to no to disable s/key passwords

#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no    # 是否禁用s/key密码

Kerberos options      # 与Kerberos 有关的参数设定,不用设定

#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

GSSAPI options

GSSAPIAuthentication yes     # 是否开启GSSAOI身份认证机制;建议设置no,加快ssh连接
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no

Set this to 'yes' to enable PAM authentication, account processing,

and session processing. If this is enabled, PAM authentication will

be allowed through the ChallengeResponseAuthentication and

PasswordAuthentication. Depending on your PAM configuration,

PAM authentication via ChallengeResponseAuthentication may bypass

the setting of "PermitRootLogin without-password".

If you just want the PAM account and session checks to run without

PAM authentication, then enable this but set PasswordAuthentication

and ChallengeResponseAuthentication to 'no'.

WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several

problems.

UsePAM yes         # 是否启用PAM身份认证

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no      # 是否允许被远程主机所设置的本地转发端口绑定在非环回地址上
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes       # 登入后是否显示设定的信息;建议设为no
#PrintLastLog yes      # 是否显示上次登入的信息
#TCPKeepAlive yes
#UseLogin no        # 是否接受login 这个程序的登入
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no  # 是否允许用户将环境选项呈现给ssh守护进程
#Compression delayed
#ClientAliveInterval 0   # 设置了ssh服务器端向其客户端发送请求消息(alive消息)的间隔时间,以检测客户端是否还存在,0表示不发送
#ClientAliveCountMax 3   # 允许客户端在接收到服务端的alive消息未响应的最大超时次数,如果客户端在最大超时次数内均未响应,ssh服务会自动终止与客户端的会话。
#ShowPatchLevel no
#UseDNS yes        # 是否将客户端主机名解析为IP,以检查此主机名是否与其IP地址真实对应;建议去到"#"设为no
#PidFile /var/run/sshd.pid   # sshd的PID路径文件
#MaxStartups 10:30:100  # 当连接数超过10会以30%的失败率拒绝用户登录(达到100,100%拒绝)
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

no default banner path

#Banner none    # ssh登录提示信息,可去掉"#"自定义,指定全路径文件即可

Accept locale-related environment variables

AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

===== 以下可自行添加到配置文件 =====

AllowUsers wen    允许的用户登录(包括root)白名单

DenyUsers cheng   拒绝的用户登录,黑名单(优先级高)

AllowGroups XX    允许的用户组登录 

DenyGroups XXX    拒绝的用户组登录

================================================

override default of no subsystems

Subsystem sftp /usr/libexec/openssh/sftp-server

Example of overriding settings on a per-user basis

#Match User anoncvs

X11Forwarding no

AllowTcpForwarding no

PermitTTY no

ForceCommand cvs server

默认/etc/ssh/ssh_config解析。

[root@wenCheng ~]# cat /etc/ssh/ssh_config
…….

Host *               # 选项“Host”只对能够匹配后面字串的计算机有效。“*”表示所有的计算机

ForwardAgent no        # 连接是否经过验证代理(如果存在)转发给远程计算机

ForwardX11 no         # X11连接是否被自动重定向到安全的通道和显示集

RhostsRSAAuthentication no  # 是否使用用RSA算法的基于rhosts的安全验证

RSAAuthentication yes     # 是否使用RSA算法进行安全验证

PasswordAuthentication yes  # 是否使用口令验证

HostbasedAuthentication no  # 是否启用基于主机的身份认证机制

GSSAPIAuthentication no

GSSAPIDelegateCredentials no

GSSAPIKeyExchange no

GSSAPITrustDNS no

BatchMode no          # 是否在这台计算机上使用“rlogin/rsh”

CheckHostIP yes        # 是否查看连接到服务器的主机的IP地址以防止DNS欺骗。建议设置为“yes”

AddressFamily any      

ConnectTimeout 0

StrictHostKeyChecking ask   # 自动把计算机的密匙加入“$HOME/.ssh/known_hosts”文件;ask(默认)新的主机密钥将添加到用户知道的主机文件

IdentityFile ~/.ssh/identity  # 从哪个文件读取用户的RSA安全验证标识

IdentityFile ~/.ssh/id_rsa

IdentityFile ~/.ssh/id_dsa

IdentityFile ~/.ssh/id_ecdsa

IdentityFile ~/.ssh/id_ed25519

Port 22            # 连接到远程主机的端口

Protocol 2

Cipher 3des          # 加密用的算法

Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc

MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160

EscapeChar ~         # 设置escape字符

Tunnel no

TunnelDevice any:any

PermitLocalCommand no

VisualHostKey no

ProxyCommand ssh -q -W %h:%p gateway.example.com

RekeyLimit 1G 1h

Uncomment this if you want to use .local domain

Host *.local

CheckHostIP no

Host *
GSSAPIAuthentication yes

If this option is set to yes then remote X11 clients will have full access

to the original X11 display. As virtually no X11 client supports the untrusted

mode correctly we set this to yes.

ForwardX11Trusted yes  

Send locale-related environment variables

SendEnv LANG LC\_CTYPE LC\_NUMERIC LC\_TIME LC\_COLLATE LC\_MONETARY LC\_MESSAGES  
SendEnv LC\_PAPER LC\_NAME LC\_ADDRESS LC\_TELEPHONE LC\_MEASUREMENT  
SendEnv LC\_IDENTIFICATION LC\_ALL LANGUAGE  
SendEnv XMODIFIERS

SSH认证过程分两种:

1.基于口令认证。

  • SSH命令基本用法。

openssh套件中的客户端连接工具
ssh [options] [user@]hostname [command]
  -1:强制使用ssh协议版本1;
  -2:强制使用ssh协议版本2;
  -4:强制使用IPv4地址;
  -6:强制使用IPv6地址;
  -A:开启认证代理连接转发功能;
  -a:关闭认证代理连接转发功能;
  -b:使用本机指定地址作为对应连接的源ip地址;
  -C:请求压缩所有数据;
  -F:指定ssh指令的配置文件;
  -f:后台执行ssh指令;
  -g:允许远程主机连接主机的转发端口;
  -i:指定身份文件;
  -l:指定连接远程服务器登录用户名;
  -N:不执行远程指令;
  -o:指定配置选项;
  -p:指定远程服务器上的端口;
  -q:静默模式;
  -v:详细模式,将输出debug消息,可用于调试。"-vvv"可更详细。
  -V:显示版本号并退出。
  -o:指定额外选项,选项非常多。
user@hostname :指定ssh以远程主机hostname上的用户user连接到的远程主机上,若省略user部分,则表示使用本地当前用户。
:如果在hostname上不存在user用户,则连接将失败(将不断进行身份验证)。
command :要在远程主机上执行的命令。指定该参数时,ssh的行为将不再是登录,而是执行命令,命令执行完毕时ssh连接就关闭。

例:远程主机IP:172.16.70.186 用户:Wen 端口:2221
shell> ssh -l Wen 172.16.70.186 -p2221
shell> ssh Wen@172.16.70.186 -p2221
shell> ssh Wen@172.16.70.186 -p2221 'hostname'

  • # 跳板机首次远程连接服务器-01过程

[root@wenCheng ~]# ssh root@172.16.70.186
The authenticity of host '172.16.70.186 (172.16.70.186)' can't be established.
ECDSA key fingerprint is SHA256:ZGZdN+a+izupZH7iY2/2VLQhB60QNKvIBLiAJHmf4o4.
ECDSA key fingerprint is MD5:e4:2b:df:ac:73:b7:0b:95:a4:7e:4c:97:ba:6e:30:1a.
Are you sure you want to continue connecting (yes/no)? yes        ## 主机验证

这段话的意思是,无法确认host主机的真实性,只知道它的公钥指纹,问你还想继续连接吗?

所谓"公钥指纹",是指公钥长度较长很难比对,所以对其进行MD5计算,将它变成一个128位的指纹。上例中是e4:2b:df:ac:73:b7:0b:95:a4:7e:4c:97:ba:6e:30:1a,再进行比较,就容易多了。

那么用户怎么知道远程主机的公钥指纹应该是多少?回答是没有好办法,远程主机必须在自己的网站上贴出公钥指纹,以便用户自行核对。

Warning: Permanently added '172.16.70.186' (ECDSA) to the list of known hosts.
root@172.16.70.186's password:      ## 用户验证
Last login: Fri Jun 18 08:19:10 2021 from 172.16.70.182

当远程主机的公钥被接受以后,它就会被保存在文件$HOME/.ssh/known_hosts之中。下次再连接这台主机,系统就会认出它的公钥已经保存在本地了,从而跳过警告部分,直接提示输入密码。

[root@Server-01 ~]# ls -l /etc/ssh/ssh_host*
-rw-r-----. 1 root ssh_keys 227 Jun 17 15:59 /etc/ssh/ssh_host_ecdsa_key
-rw-r--r--. 1 root root 162 Jun 17 15:59 /etc/ssh/ssh_host_ecdsa_key.pub
-rw-r-----. 1 root ssh_keys 387 Jun 17 15:59 /etc/ssh/ssh_host_ed25519_key
-rw-r--r--. 1 root root 82 Jun 17 15:59 /etc/ssh/ssh_host_ed25519_key.pub
-rw-r-----. 1 root ssh_keys 1679 Jun 17 15:59 /etc/ssh/ssh_host_rsa_key
-rw-r--r--. 1 root root 382 Jun 17 15:59 /etc/ssh/ssh_host_rsa_key.pub

查看服务器-01上的ecdsa_key.pub

[root@Server-01 ~]# cat /etc/ssh/ssh_host_ecdsa_key.pub
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDiaBpVrOEa+c82sjAXHl7TiQ9RJaPh9U4YLCinNAh3LH2ZX5ykkgEr7gA4Rq1Syd1S6/P3cUHQ5AbgkKiTOpcw=
[root@Server-01 ~]#
[root@Server-01 ~]# ssh-keygen -l -f /etc/ssh/ssh_host_ecdsa_key
256 SHA256:ZGZdN+a+izupZH7iY2/2VLQhB60QNKvIBLiAJHmf4o4 /etc/ssh/ssh_host_ecdsa_key.pub (ECDSA)

[root@Server-01 ~]# logout    # Ctrl + d 退出;返回到跳板机
Connection to 172.16.70.186 closed.

查看跳板机上的known_hosts,对应服务器-01的ecdsa_key.pub

[root@wenCheng ~]# cat .ssh/known_hosts
172.16.70.186 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDiaBpVrOEa+c82sjAXHl7TiQ9RJaPh9U4YLCinNAh3LH2ZX5ykkgEr7gA4Rq1Syd1S6/P3cUHQ5AbgkKiTOpcw=
[root@wenCheng ~]#
[root@wenCheng ~]# ssh-keygen -l -f .ssh/known_hosts
256 SHA256:ZGZdN+a+izupZH7iY2/2VLQhB60QNKvIBLiAJHmf4o4 172.16.70.186 (ECDSA)

2.基于公钥认证。

  • 使用口令认证,每次都必须输入密码,非常麻烦。好在SSH还提供了公钥登录,可以省去输入密码的步骤。

  • 所谓"公钥认证",原理很简单,就是用户将自己的公钥储存在远程主机上。登录的时候,远程主机会向用户发送一段随机字符串,用户用自己的私钥加密后,再发回来。远程主机用事先储存的公钥进行解密,如果成功,就证明用户是可信的,直接允许登录shell,不再要求密码。

  • ssh-keygen命令基本用法。

为ssh生成、管理和转换认证密钥
ssh-keygen [options] [command]
  -b:指定密钥长度;对于RSA密钥,最小要求768位,默认是2048位。DSA密钥必须恰好是1024位
  -e:读取openssh的私钥或者公钥文件;
  -c:修改私钥和公钥文件中的注释。
  -C:添加注释;
  -f:指定用来保存密钥的文件名;
  -i:读取未加密的ssh-v2兼容的私钥/公钥文件,然后在标准输出设备上显示openssh兼容的私钥/公钥;
  -l:显示公钥文件的指纹数据;
  -N:提供一个新密语;
  -P:提供(旧)密语;
  -q:静默模式;
  -t:指定要创建的密钥类型,dsa | ecdsa | ed25519 | rsa | rsa1。
  -v:详细模式。ssh-keygen 将会输出处理过程的详细调试信息。常用于调试模数的产生过程。

例:在服务器上生成rsa,4096位,使用者为Wen的密钥对。
shell> ssh-keygen -t rsa -b 4096 -C Wen

  • ssh-copy-id命令基本用法。

可以把本地主机的公钥复制到远程主机的authorized_keys文件上
ssh-copy-id [option] [user@]hostname
  -i 指定认证文件(公钥)
  -f 强制模式
  -n 测试,不实际替换
  -p port 指定端口
  -o option 指定其他 ssh 参数

例:将跳板机的/root/.ssh/id_rsa.pub公钥发送到远程服务器172.16.0.1的Wen用户上。
shell> ssh-copy-id -i /root/.ssh/id_rsa.pub Wen@172.16.0.1

  • # 跳板机首次远程连接服务器-02过程

# 在跳板机wenCheng操作
例1:交互式生成密钥对
[root@wenCheng ~]# ssh-keygen                    # 可自定义参数 -t rsa -b 4096 -C WenCheng
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):    # 回车,默认key保存路径/root/.ssh/id_rsa;可自定义,如/root/.ssh/WenCheng_rsa
Enter passphrase (empty for no passphrase):            # 回车,默认key不设置密码;建议设置密码
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:zyMrRak1AcDZf9SzJKKXLGwJwNjJfsdztHzF08t+URI root@wenCheng
The key's randomart image is:
+---[RSA 2048]----+
| =.+.+.. o .E. |
|. = + . + o B o .|
| . + B B + = o.|
| . . X & o . o. |
| . o OS+ . .|
| . .o . .|
| .. + . |
| . o . |
| .. |
+----[SHA256]-----+

[root@wenCheng ~]# ssh-keygen -l -f .ssh/id_rsa.pub    # 查看生成公钥指纹
2048 SHA256:zyMrRak1AcDZf9SzJKKXLGwJwNjJfsdztHzF08t+URI root@wenCheng (RSA)

[root@wenCheng ~]# ls -l .ssh/
-rw-------. 1 root root 1679 Jun 18 17:23 id_rsa
-rw-r--r--. 1 root root 395 Jun 18 17:23 id_rsa.pub

[root@wenCheng ~]# ssh-copy-id -i .ssh/id_rsa.pub root@172.16.70.187    # 将生成的公钥保存至172.16.70.187的root用户的/root/.ssh/authorized_keys
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/id_rsa.pub"
The authenticity of host '172.16.70.187 (172.16.70.187)' can't be established.
ECDSA key fingerprint is SHA256:c/5+RMbf79VeNEzwtdtk9cvRoWIDDRg890ew82Hfj+g.
ECDSA key fingerprint is MD5:41:ce:da:7c:7d:ce:93:ed:6f:c3:1d:81:6d:02:18:3b.
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@172.16.70.187's password:    # root@172.16.70.187登入密码

Number of key(s) added: 1

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

在Server-02操作

[root@Server-02 ~]# ssh-keygen -l -f .ssh/authorized_keys
2048 SHA256:zyMrRak1AcDZf9SzJKKXLGwJwNjJfsdztHzF08t+URI root@wenCheng (RSA)

===================================================================================
例2:非交互式生成密钥对
[root@wenCheng ~]# ssh-keygen -f .ssh/id_rsa -N ''
Generating public/private rsa key pair.
Your identification has been saved in .ssh/id_rsa.
Your public key has been saved in .ssh/id_rsa.pub.
The key fingerprint is:
SHA256:/fbMSIjWa4wzqiuBs8y7bbvTk4DK4Qc3BB37rf4JGn0 root@wenCheng
The key's randomart image is:
+---[RSA 2048]----+
| … |
| . .. |
| .. |
| .. . . |
| .o . .S . |
|o+.+. . o o |
|*o+o++.Eooo + |
|o=o+++o.= o+ = |
| o=**+++ +. . + |
+----[SHA256]-----+

[root@wenCheng ~]# ls -l .ssh/
-rw-------. 1 root root 1679 Jun 18 17:47 id_rsa
-rw-r--r--. 1 root root 395 Jun 18 17:47 id_rsa.pub

[root@wenCheng ~]# ssh-keygen -l -f .ssh/id_rsa.pub
2048 SHA256:/fbMSIjWa4wzqiuBs8y7bbvTk4DK4Qc3BB37rf4JGn0 root@wenCheng (RSA)

[root@Server-02 ~]# ls -l .ssh/
-rw-------. 1 root root 395 Jun 18 17:49 authorized_keys
[root@Server-02 ~]#
[root@Server-02 ~]# ssh-keygen -l -f .ssh/authorized_keys
2048 SHA256:/fbMSIjWa4wzqiuBs8y7bbvTk4DK4Qc3BB37rf4JGn0 root@wenCheng (RSA)

  • 跳板机批量实现非交互式双机互信

#跳板机root@172.16.70.182需要和root@172.16.70.186~root@172.16.70.190配置双机互信
[root@wenCheng ~]# cat ~/sshKey.sh
#!/bin/bash

创建密钥对

ssh-keygen -t rsa -b 4096 -C WenCheng -f ~/.ssh/wencheng_rsa -P "123456" &>/dev/null

是否安装sshpass

rpm -q sshpass &>/dev/null || yum -y install sshpass &>/dev/null

#批量分发公钥
for ip in `grep Server all_hosts | awk '{print $2}'`
do
echo "==== hsot $ip ===="

ssh-keyscan $ip >> ~/.ssh/known_hosts 2 > /dev/null

sshpass -p 'centos' ssh-copy-id -i /root/.ssh/wencheng_rsa.pub -o StrictHostKeyChecking=no root@$ip &>/dev/null
REVAL=$?
if [ $REVAL -eq 0 ]
then
echo -e "\033[32m Send publickey to host $ip success!!!\033[0m"
echo
else
echo -e "\033[41;37m Send publickey to host $ip fail!!! \033[0m"
echo
fi
done

[root@wenCheng ~]# cat ~/all_hosts
hostname ip
Server-01 172.16.70.186
Server-02 172.16.70.187
Server-03 172.16.70.188
Server-04 172.16.70.189
Server-05 172.16.70.190

[root@wenCheng ~]# ls .ssh/
id_rsa id_rsa.pub known_hosts wencheng_rsa wencheng_rsa.pub

[root@wenCheng ~]# ssh -i .ssh/wencheng_rsa 172.16.70.186
Enter passphrase for key '.ssh/wencheng_rsa':        # 私钥密码 123456
Last login: Mon Jun 21 15:58:06 2021 from 172.16.70.182
[root@Server-01 ~]# hostname -I
172.16.70.186

虽然上面脚本实现了批量互信,但每次指定私钥的时候还得输入这个passphrase密码,此时该如何解决?

  • ssh-agent可以通过ssh-add命令向ssh-agent注册本机的私钥,ssh-agent会自动推导出这个私钥的指纹(实际上是ssh-add计算的)保存在自己的小本本里(内存),以后只要ssh连接某主机(某用户),将自动转发给ssh-agent,ssh-agent将自动从它的小本本里查找私钥的指纹并将其发送给服务端(sshd端)。如此一来,ssh客户端就无需再指定使用哪个私钥文件去连接。

  • 总的看上去,ssh-agent的角色就是帮忙存储、查找并发送对应的指纹而已,也就是说它是一个连接的转发人,扮演的是一个代理的角色。

  • ssh-agent命令基本用法。

ssh-agent就是一个密钥管理器,运行ssh-agent以后,使用ssh-add将私钥交给ssh-agent保管,其他程序需要身份验证的时候可以将验证申请交给ssh-agent来完成整个认证过程。
ssh-agent [options] [command [arg …]
  -a bind_address:bind the agent to the UNIX-domain socket bind_address.
  -c:生成C-shell风格的命令输出。
  -d:调试模式。
  -k:把ssh-agent进程杀掉。
  -s:生成Bourne shell 风格的命令输出。
  -t life:设置默认值添加到代理人的身份最大寿命。

例:运行ssh-agent
shell> eval `ssh-agent`
shell> eval "$(ssh-agent)"

  • ssh-add命令基本用法。

把专用密钥添加到ssh-agent的高速缓存中
ssh-add [options] [file …]
  -D:删除ssh-agent中的所有密钥.
  -d:从ssh-agent中的删除密钥
  -e pkcs11:删除PKCS#11共享库pkcs1提供的钥匙。
  -s pkcs11:添加PKCS#11共享库pkcs1提供的钥匙。
  -L:显示ssh-agent中的公钥
  -l:显示ssh-agent中的密钥
  -t life:对加载的密钥设置超时时间,超时ssh-agent将自动卸载密钥
  -X:对ssh-agent进行解锁
  -x:对ssh-agent进行加锁

使用ssh-agent和ssh-add命令完美解决。

# 跳板机使用指定公钥远程连接服务器
[root@wenCheng ~]# ls .ssh/
id_rsa id_rsa.pub known_hosts wencheng_rsa wencheng_rsa.pub

[root@wenCheng ~]# eval `ssh-agent`
Agent pid 16800
[root@wenCheng ~]# ssh-add .ssh/wencheng_rsa
Enter passphrase for .ssh/wencheng_rsa:      # 只在这里输入私钥一次密码
Identity added: .ssh/wencheng_rsa (.ssh/wencheng_rsa)
[root@wenCheng ~]# ssh-add -l
4096 SHA256:m9Og2cC65AIfkT6/jXa/L09BUzBsyOV4V9t0XEmNK/0 .ssh/wencheng_rsa (RSA)

[root@wenCheng ~]# ssh 172.16.70.186    # 无需再输私钥密码
Last failed login: Mon Jun 21 16:11:53 CST 2021 from 172.16.70.182 on ssh:notty
There were 2 failed login attempts since the last successful login.
Last login: Mon Jun 21 15:59:50 2021 from 172.16.70.182
[root@Server-01 ~]# hostname -I
172.16.70.186
[root@Server-01 ~]# logout
Connection to 172.16.70.186 closed.

[root@wenCheng ~]# ssh 172.16.70.187    # 无需再输私钥密码
Last login: Mon Jun 21 15:58:10 2021 from 172.16.70.182
[root@Server-02 ~]# hostname -I
172.16.70.187

  • 查询ssh-agent PID 并结束进程

[root@wenCheng ~]# pgrep -l -f ssh-agent
16797 ssh-agent
16800 ssh-agent
[root@wenCheng ~]# ps -ef | grep ssh-agent
root 16797 1 0 16:13 ? 00:00:00 ssh-agent
root 16800 1 0 16:13 ? 00:00:00 ssh-agent

[root@wenCheng ~]# ssh-agent -k
[root@wenCheng ~]# pkill ssh-agent

  • SSH 别名设置,此方法配合ssh 免密码登录 密钥登录可以快速登录服务器。

[root@wenCheng ~]# cat .ssh/config
Host Server-01
HostName 172.16.70.186
User root
Port 22
IdentityFile ~/.ssh/wencheng_rsa

Host Server-02
Hostname 172.16.70.187
User root
Port 22
IdentityFile ~/.ssh/wencheng_rsa

解析:
Host:别名
HostName:指定登录的主机名或IP地址
Port:指定登录的端口号
User:登录用户名
IdentityFile:登录的私钥文件

[root@wenCheng ~]# eval `ssh-agent`
Agent pid 18137
[root@wenCheng ~]# ssh-add .ssh/wencheng_rsa
Enter passphrase for .ssh/wencheng_rsa:      # 前面已设置的密码 123456
Identity added: .ssh/wencheng_rsa (.ssh/wencheng_rsa)

[root@wenCheng ~]# ssh-add -l
4096 SHA256:m9Og2cC65AIfkT6/jXa/L09BUzBsyOV4V9t0XEmNK/0 .ssh/wencheng_rsa (RSA)

使用别名远程登录172.16.70.186,172.16.70.187 也已无需反复输入key密码

[root@wenCheng ~]# ssh Server-01
Last login: Tue Jun 22 16:14:04 2021 from 172.16.70.182
[root@Server-01 ~]# hostname -I
172.16.70.186
[root@Server-01 ~]# logout
Connection to 172.16.70.186 closed.

[root@wenCheng ~]# ssh Server-02
Last login: Tue Jun 22 16:13:51 2021 from 172.16.70.182
[root@Server-02 ~]# hostname -I
172.16.70.187

附:ssh排查问题

1.判断物理链路是否通ping 本身是icmp协议

2.判断服务是否正常
telnet 172.16.70.186

3.Linux防火墙
systemctl status firewalld  

4.打开ssh的调测进行观察
ssh -vvv Wen@172.16.70.186