问题
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