2017-02-16 59 views
0

我想跑與rubynet::ssh遠程命令,並希望能夠打印輸出stdout,但我沒有看到任何東西在下面的代碼在印channel.on_data紅寶石淨:: SSH不標準輸出數據打印channel.on_data

見測試代碼:

Net::SSH.start('testhost', "root", :timeout => 10) do |ssh| 
    ssh.open_channel do |channel| 
    channel.exec('ls') do |_, success| 
     unless success 
     puts "NOT SUCCEESS:! " 
     end 
     channel.on_data do |_, data| 
     puts "DATAAAAAA:! " # ======> Why am i not getting to here?? <======= 
     end 
     channel.on_extended_data do |_, _, data| 
     puts "EXTENDED!!!" 
     end 
     channel.on_request("exit-status") do |_, data| 
     puts "EXIT!!!! " 
     end 
     channel.on_close do |ch| 
     puts "channel is closing!" 
     end 
    end 
    end 
end 

,輸出是:

channel is closing! 

爲什麼我沒有拿到入T他阻止on_data?我想抓住stdout

注意,我知道客戶端代碼能夠sshremote server,因爲當我問命令是ls > ls.log我看到ls.log目標主機上。

回答

2

請注意,打開通道是異步的,因此您必須等待通道執行任何有意義的操作,否則您將很快關閉連接。

試試這個:

Net::SSH.start('test', "root", :timeout => 10) do |ssh| 
    ch = ssh.open_channel do |channel| 
    channel.exec('ls') do |_, success| 
     unless success 
     puts "Error" 
     end 
     channel.on_data do |_, data| 
     puts data 
     end 
     channel.on_extended_data do |_, _, data| 
     puts data 
     end 
     channel.on_request("exit-status") do |_, data| 
     puts "Exit" 
     end 
     channel.on_close do |ch| 
     puts "Closing!" 
     end 
    end 
    end 

    ch.wait 
end 
+0

感謝,但我看到'channel.on_close'被稱爲無添加即使手術需要2分鐘'ch.wait',如果它是異步如何on_close工作和即使沒有'ch.wait'也不關閉連接? – Jas

+0

如果你不等,那麼因爲這個代碼是異步的,應用程序可以做任何想做的事情,包括退出。如果它退出然後它將關閉所有打開的連接,包括您的異步之一。如果你在這裏或任何其他地方使用ch.wait並不重要,但是如果在應用程序結束之前對你輸入了重要信息,你應該等待它完成 – SztupY

+0

我嘗試運行'sleep 20'作爲運行命令而沒有'ch.wait',我看到它正在等待它完成。所以從一邊等待它完成,但另一方面它不會在'on_data'上發送事件我不明白它是否在等待進程結束爲什麼不將數據發送到'on_data' ? – Jas