Ruby - checking ping status featback with ssh, backtick via ssh?

被刻印的时光 ゝ 提交于 2019-12-11 19:12:22

问题


In my project I want to write a script to check if every device in my network is online/reachable. I have a method called pingtest and it works for now..

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

Now I wanted to ping via a ssh session with an other device in my network:

#--------------------------------
require 'net/ssh' 
Net::SSH.start(@ip, @user, :password => @password)
#--------------------------------

@ssh = Ssh.new(@config)
@ssh.cmd("ping -c 3 #{@IP}")

The ping works fine but how can I use my backtrack idea now to determine if it was succesful or not?
I thought about using a sftp connection..

"ping -c 3 #{@IP} => tmpfile.txt" => download => check/compare => delete

(or something like that) to check if it was correct, but im not statusfied with that. Is there a possibility to check the success status like I did before?
I also tried something like this..

result = @ssh.cmd("ping -c 3 #{@IP}")
if result.success? == 0 # and so on..

I startet learning ruby some days ago, so im a newbie looking forward for your ideas to help me with this problem.


回答1:


You can use Net::SSH to run the command remotely, similarly to what you've already got there.

The result returned from running the command will be whatever is written to both stdout and stderr.

You can use the contents of that returned value to check if it was successful or not.

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


来源:https://stackoverflow.com/questions/29842698/ruby-checking-ping-status-featback-with-ssh-backtick-via-ssh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!