
SSH 中的 ServerAliveCountMax 其實有什麼角色?
我試圖確保當我透過 SSH 連接到我的伺服器時,連線在很長一段時間內保持開啟狀態,而不是在短時間內不活動後連線消失。這是例子
Host *
ServerAliveInterval 60
ServerAliveCountMax 2
我聽說一個來源只要伺服器收到該回應,上述設定將始終每 60 秒向伺服器發送回應。但是,如果由於某種原因響應沒有到達伺服器,它將嘗試發送另一個訊息。如果該訊息也失敗,那麼它將關閉連線。 (我感覺這是錯的)
這第二和第三然而消息來源卻說了不同的話。他們聲稱,如果有一段時間不活動,每 60 秒就會向伺服器發送一條訊息,但只會發送 2 個請求,然後就會關閉連線。
那麼 ServerAliveCountMax 到底做了什麼?
答案1
你的「這是錯的」的感覺是正確的。請參閱手冊頁:
ServerAliveCountMax
Sets the number of server alive messages (see below) which may be
sent without ssh(1) receiving any messages back from the server.
If this threshold is reached while server alive messages are
being sent, ssh will disconnect from the server, terminating the
session. It is important to note that the use of server alive
messages is very different from TCPKeepAlive (below). The server
alive messages are sent through the encrypted channel and there‐
fore will not be spoofable. The TCP keepalive option enabled by
TCPKeepAlive is spoofable. The server alive mechanism is valu‐
able when the client or server depend on knowing when a connec‐
tion has become inactive.
The default value is 3. If, for example, ServerAliveInterval
(see below) is set to 15 and ServerAliveCountMax is left at the
default, if the server becomes unresponsive, ssh will disconnect
after approximately 45 seconds. This option applies to protocol
version 2 only.
ServerAliveInterval
Sets a timeout interval in seconds after which if no data has
been received from the server, ssh(1) will send a message through
the encrypted channel to request a response from the server. The
default is 0, indicating that these messages will not be sent to
the server. This option applies to protocol version 2 only.
答案2
當 SSH 伺服器配置為在一段時間無流量後關閉連線時,伺服器活動訊息非常有用(例如,提供 SSH 存取的共用 Web 託管供應商幾乎總是這樣做)。設定這兩個選項將每秒發送一個資料包ServerAliveInterval
,發送次數最多,ServerAliveCountMax
從而保持會話處於活動狀態。
為了回答有關將任一選項設為 的不確定性的評論0
,我已閱讀了實現的源代碼openssh
,這是我所看到的...
設定
ServerAliveInterval
為0
不會傳送封包,但假設連線不會因為 TCP 逾時而被丟棄,且伺服器未配置為丟棄不活動的用戶端,則它將無限期地保持會話活動。設定
ServerAliveCountMax
為與設定為0
具有相同的效果。ServerAliveInterval
0
將任一值設為負數或任何大於
INT_MAX
(即 2,147,483,647)的值將導致“整數值...”錯誤。設定
ServerAliveCountMax
在INT_MAX/1000+1
(即 2,147,484) 到INT_MAX
(即 2,147,483,647) 之間也相當於將任一值設為0
。
因此,本質上,您可以獲得的最大超時(同時仍然發送資料包)是INT_MAX/1000
(即 2,147,483)。如果會話逾時1
並且完全沒有流量,那麼您將需要將近 25 天的時間。
顯然,SSH 的其他實作可能會產生不同的結果。