Ruby で VNC サーバの死活確認

Ruby の TCPSocket と timeout をつかいます.
timeout は,指定秒数内に処理が終わらなければ 例外 Timeout::Error を投げてくれる超便利モジュールです.

begin
  timeout (秒数) {
    do_something()
  }
rescue Timeout::Error
  print "時間切れ"
end

みたいな感じで使えます.
これを利用して,VNC サーバの死活確認をしてみます.
おおざっぱですが,VNC サーバが開けてるポートに TCPSocket で1秒以内につながらなかったら死んでると判断,っていうロジックでやってみました.だいたいいい感じで動いてくれます.

require 'net/http'
require 'timeout'
require 'uri'
require 'json'

WAIT_TIME = 30
TARGET_PORT = 7070 # VNC サーバのポート
TIMEOUT = 1

def print_res (mes)
  print "#{Time.now.strftime("%H:%M:%S")} #{mes}\n"
end

loop {

  print_res "[--] Starting scan..."

  # json で対象ホストの一覧があるっていう感じで
  # {"hoge1": "192.0.2.3", "mayuge2": "192.0.2.4"} みたいな
  hosts = JSON.parse(hoge)

  down_hosts = 0;

  hosts.each { |k, v|
    if v=="" then
      print_res "[!!] No IP Addr: #{k}"
      down_hosts += 1
    else
      begin
        timeout (TIMEOUT) {
          mayuge = TCPSocket.open(v, TARGET_PORT)
        }
      rescue Timeout::Error
        print_res "[!!] Connection Failed: #{v}"
        down_hosts += 1
      end
    end
  }

  print_res "[--] Scan finished."
  if down_hosts == 0 then
    print_res "[OO] No down hosts!"
  else
    print_res "[XX] Down hosts: #{down_hosts} / #{hosts.length}"
  end
  print_res "[--] Waiting for #{WAIT_TIME} seconds...\n"
  sleep WAIT_TIME
}