在我的项目中,我想编写一个脚本来检查我网络中的每个设备是否都在线/可访问。我有一个名为pingtest的方法,它现在可以工作。
def pingtest(destination)
system("ping -n 2 #{destination}")
if $? == 0 #checking status of the backtick
puts "n Ping was successful!"
else
close("Device is unreachable. Check the config.txt for the correct IPs.")
#close() is just print & exit..
end
end
现在我想通过与网络中其他设备的 ssh 会话 ping 操作:
#--------------------------------
require 'net/ssh'
Net::SSH.start(@ip, @user, :password => @password)
#--------------------------------
@ssh = Ssh.new(@config)
@ssh.cmd("ping -c 3 #{@IP}")
ping工作正常,但是我现在如何使用我的回溯想法来确定它是否成功?
我想过使用 sftp 连接。
"ping -c 3 #{@IP} => tmpfile.txt" => 下载 => 检查/比较 => 删除
(或类似的东西)来检查它是否正确,但我没有状态。是否有可能像以前一样检查成功状态?
我也尝试过这样的事情..
result = @ssh.cmd("ping -c 3 #{@IP}")
if result.success? == 0 # and so on..
几天前我开始学习 ruby,所以我是一个新手,期待你的想法来帮助我解决这个问题。
您可以使用Net::SSH远程运行该命令,类似于您已经获得的命令。
运行命令返回的result
将是写入stdout
和stderr
的任何内容。
您可以使用该返回值的内容来检查它是否成功。
Net::SSH.start(@ip, @user. password: @password) do |ssh|
response = ssh.exec! "ping -c 3 #{@other_ip}"
if response.include? 'Destination Host Unreachable'
close("Host unreachable. Result was: #{result}")
else
puts "n Ping was successful"
end
end