2017-08-04 81 views
0

我正在將工具從Ruby轉換爲Python,Ruby版本使用Net::SSH連接到遠程主機,併發送命令並檢索響應/數據。我一直在Python中使用paramiko,但我對Channels in paramiko.的目的感到困惑從我迄今讀過的內容來看,在我看來,一個通道(使用paramiko Transport)用於保持持續連接到SSH而不是執行命令然後終止連接。在Paramiko中使用頻道

是必需的渠道?爲了順序發送和接收多個命令並獲取響應,打開與主機的持久SSH連接所需的堆棧是什麼?然後在完成手動關閉連接後需要什麼?

這些都是我無法翻譯成Python兩條主線,因爲我不知道,如果一個Ruby「通道」直接映射到一個的paramiko「通道」:

@ssh_connection = Net::SSH.start(@linux_server_name, 
         @server_user_name, 
         :password => @password, 
         :paranoid => false) 

,後來在代碼

@channel = @ssh_connection.open_channel do |new_channel| 

編輯:爲了進一步說明我的問題,我能夠使用的paramiko連接到遠程主機並執行多個連續的命令,並得到他們的結果,而無需使用傳輸或通道,如此反覆,什麼是t他在paramiko使用頻道的理由是什麼?

def connect(self): 
    ssh_connection = paramiko.SSHClient() 
    ssh_connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    ssh_connection.connect(self.linux_server_name) 
    stdin, stdout, stderr = ssh_connection.exec_command("ls -l") 
    print(stdout.readlines()) 
    stdin, stdout, stderr = ssh_connection.exec_command("ls -l /tmp") 
    print(stdout.readlines()) 
    ssh_connection.close() 

回答

1

exec_command()是不夠的,如果SSH服務器支持運行命令(如ssh [email protected] "cmd; cmd; ..."。但有些SSH服務器(例如如交換機,路由器的網絡設備,...)只支持啓動的交互式會話。然後,你需要使用invoke_shell()它返回一個通道

交通運輸通道都SSH項(比的paramiko的除外),請參閱以下RFC更多信息:。

+0

參見:HTTPS:/ /stackoverflow.com/questions/41570124/ping-isnt-allowed-to-be-executed,https://stackoverflow.com/questions/41183971/paramiko-session-times-out-but-i-need-to-execute -a-lot-of-commands,https://stackoverflow.com/q uestions/40090445/paramiko-exec-command-not-executed-and-returns-extra-params-found-in-cli – pynexj

+0

invoke_shell()是什麼你會使用,例如,當你需要使用PTY?似乎是這樣的... –

+0

不完全。 'exec_command(command,get_pty = True)'也可以得到一個pty。請參閱https://stackoverflow.com/questions/43111173/ – pynexj