diff options
author | pks <pks@pks.rocks> | 2021-03-21 11:31:02 +0100 |
---|---|---|
committer | pks <pks@pks.rocks> | 2021-03-21 11:31:02 +0100 |
commit | 26c6a0d934e36ffb26f770e740e9294d172a7d84 (patch) | |
tree | 792ae9f58e037c0cd3cba2ea7a744e8c2e7fa1a3 /up.rb |
init
Diffstat (limited to 'up.rb')
-rw-r--r-- | up.rb | 65 |
1 files changed, 65 insertions, 0 deletions
@@ -0,0 +1,65 @@ +#!/usr/bin/env ruby + +require "net/ping" +require "socket" + +class Host + def initialize s + # example: 'nash ssh:2001 mqtt:1883' + parts = s.split + @hostname = parts.first + @services_and_ports = {} + parts.slice(1, parts.size).each { |part| + service, port_and_protocol = part.split ":" + port, protocol = port_and_protocol.split "/" + @services_and_ports["#{service}/#{protocol}"] = [port.to_i, protocol] + } + end + + def hostname + return @hostname + end + + def up? hostname + ping = Net::Ping::External.new @hostname + ping.ping? + end + + def service_up? service, port, protocol + if protocol == "tcp" + begin + sock = TCPSocket.new @hostname, port + sock.close + return true + rescue + return false + end + elsif protocol == "udp" + system "nc -u -z -w 1 #{@hostname} #{port+1} &>/dev/null" + return $?.success? + else + STDERR.write "unknown protocol '#{protocol}'\n" + end + end + + def check + ret = {} + ret["up"] = up? @hostname + return ret if not ret["up"] + @services_and_ports.each_key { |k| + ret[k] = service_up? k, @services_and_ports[k][0], @services_and_ports[k][1] + } + return ret + end +end + +def main + while line = STDIN.gets + h = Host.new line + puts h.check.to_s + end +end + +if __FILE__ == $0 + main +end |