平常會用 paramiko 批次管理幾百台設備。問題是,一旦伺服器本身或網路出狀況,返回值遲遲不來,程式就會卡在那裡一直等,這時候就必須有超時機制。
paramiko 執行遠端命令的寫法通常是:
stdin, stdout , stderr = s.exec_command(command)
但模組在這裡只提供一個參數,預設並不能直接設定超時。
其實 paramiko 內部是有這個介面的,只是預設沒開放。改原始碼就能啟用。推測開發方的考量是:有些命令天生就慢,例如大檔案壓縮,加超時反而會把正常執行的任務打斷,索然留下介面、不設預設值。但當你要用同一套程式去掃幾百台機器時,超時幾乎是必需品——否則一台啞掉的機器就能拖垮整批。
找到 C:\Python27\Lib\site-packages\paramiko 目錄下的 client.py,定位到 exec_command:
def exec_command(self, command, bufsize=-1):
"""
Execute a command on the SSH server...
"""
chan = self._transport.open_session()
chan.exec_command(command)
stdin = chan.makefile('wb', bufsize)
stdout = chan.makefile('rb', bufsize)
stderr = chan.makefile_stderr('rb', bufsize)
return stdin, stdout, stderr
改為:
def exec_command(self, command, bufsize=-1,timeout = None):
"""
Execute a command on the SSH server...
"""
chan = self._transport.open_session()
if timeout is not None:
chan.settimeout(timeout)
chan.exec_command(command)
stdin = chan.makefile('wb', bufsize)
stdout = chan.makefile('rb', bufsize)
stderr = chan.makefile_stderr('rb', bufsize)
return stdin, stdout, stderr
關鍵只有兩處:
1、函式簽章加上 timeout = None;
2、在 open_session() 之後補上判斷,若 timeout 不為 None 就呼叫 chan.settimeout(timeout)。
stdin, stdout , stderr = s.exec_command(command, timeout=10)
這樣命令執行超時時間就是 10 秒。要注意的是,直接改第三方庫原始碼在版本升級後會被覆蓋,若環境允許,更穩妥的做法是改用 subprocess 包裝 sshpass,或自行繼承、 monkey patch 這個方法。