Featured image of post SSH - 連接新主機時跳過 Key Checking

SSH - 連接新主機時跳過 Key Checking

SSH - 連接新主機時跳過 Key Checking

使用 SSH 首次連接未知主機時都會詢問是否加入 known hosts:

1
2
3
The authenticity of host '172.16.1.251 (172.16.1.251)' can't be established.
ECDSA key fingerprint is SHA256:QsGHt7QytEa6v3kp+c/31Yz0jhefppoUrgJZD1jUDOA.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

過去作法: StrictHostKeyChecking=no (不安全)

1
ssh -o StrictHostKeyChecking=no [email protected]

OpenSSH 7.6 為 StrictHostKeyChecking 加入新參數 accept-new

首次連接主機時,會自動將主機 host-key 加入 ~/.ssh/known_hosts

如果 host-key 變更了,依然能到起到警示的作用

  • ssh(1): expand the StrictHostKeyChecking option with two new
    settings. The first “accept-new” will automatically accept
    hitherto-unseen keys but will refuse connections for changed or
    invalid hostkeys. This is a safer subset of the current behaviour
    of StrictHostKeyChecking=no. The second setting “off”, is a synonym
    for the current behaviour of StrictHostKeyChecking=no: accept new
    host keys, and continue connection for hosts with incorrect
    hostkeys. A future release will change the meaning of
    StrictHostKeyChecking=no to the behaviour of “accept-new”. bz#2400

將參數換成 accept-new 後,直接加入 host-key 並建立連線

1
2
3
ssh -o StrictHostKeyChecking=accept-new [email protected]
Warning: Permanently added '172.16.1.251' (ECDSA) to the list of known hosts.
[email protected]'s password:

也可以在/etc/ssh/ssh_config直接加入設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Include /etc/ssh/ssh_config.d/*.conf

Host *
#   ForwardAgent no
#   ForwardX11 no
#   ForwardX11Trusted yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   GSSAPIKeyExchange no
#   GSSAPITrustDNS no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
    StrictHostKeyChecking accept-new # 這邊
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   IdentityFile ~/.ssh/id_ecdsa
#   IdentityFile ~/.ssh/id_ed25519
#   Port 22
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,[email protected]
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any

但是還有比直接覆寫系統層級設定更好的選擇,那就是使用者個人設定: ~/.ssh/config

StrictHostKeyChecking accept-new 加到 Host * block 內存檔後即生效

這樣使用 ssh 指令就不用再打 -o StrictHostKeyChecking=accept-new

1
2
3
4
5
6
7
8
Host *
     IdentityFile ~/.ssh/id_rsa
     # Send keep-alive packet in every 5 minutes (300 seconds).
     ServerAliveInterval 300
     # Close SSH session when 2 keep-alive packets send failed.
     ServerAliveCountMax 2
     # Auto add unknown host into ~/.ssh/known_hosts
     StrictHostKeyChecking accept-new

Reference: key authentication - how to avoid ssh asking permission? - Unix & Linux Stack Exchange

Licensed under CC BY-NC-SA 3.0 TW
最後更新 2026-05-07
comments powered by Disqus