我很難從 Ruby 腳本在后臺運行 bash 命令。
對于這個問題,我使用了一個簡化的示例。
這就是我從 PuTTY 運行命令時命令按預期作業的方式。
在后臺運行 basch 命令 (點擊查看圖片,因為 StackOverlow 還不允許我顯示圖片)
現在,我嘗試使用如下所示的小腳本從 Ruby 復制它:
ruby 腳本 (點擊查看圖片,因為 StackOverlow 還不允許我顯示圖片)
這是我運行這樣一個 Ruby 腳本時得到的結果:
腳本輸出 (點擊查看圖片,因為 StackOverlow 還不允許我顯示圖片)
為了您的分析,這里是 Ruby 腳本的轉錄:
require 'net/ssh'
net_remote_ip = '74.****122'
ssh_username = 'bots'
ssh_password = 'San*****'
get_ssh_port = '22'
ssh = Net::SSH.start(net_remote_ip, ssh_username, :password => ssh_password, :port => get_ssh_port)
s = "bash --login -c 'sleep 600' &"
print "run (#{s})... "
stdout = ssh.exec!(s)
puts "done (#{stdout.strip})"
ssh.close
exit(0)
uj5u.com熱心網友回復:
您需要將 stdout 和 stderr 都重定向到終端以外的其他地方,否則exec!將掛起等待行程輸出。
這是我找到的最簡單的解決方案:
ssh.exec!("sleep 600 &> /dev/null &")
&>同時重定向標準輸入和標準錯誤。如果要重定向輸出以進行日志記錄,可以根據需要單獨執行此操作:
ssh.exec!("command 2> error.log > output.log &")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475464.html
