Linux下的OpenSSH,你知道多少?


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
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM