diff --git a/README.markdown b/README.markdown index b794f391..9312d1ae 100644 --- a/README.markdown +++ b/README.markdown @@ -38,7 +38,8 @@ ship with the `riemann-tools` gem, including: * riemann-consul - Monitor Consul. * riemann-fd - Linux file descriptor use. * riemann-kvminstance - Monitor KVM instances. -* riemann-ntp - Monitor NTP +* riemann-ntp - Monitor NTP. +* riemann-portcheck - Monitor open TCP ports. Also contained in the repository are a number of stand-alone monitoring tools, which are shipped as separate gems. diff --git a/bin/riemann-portcheck b/bin/riemann-portcheck new file mode 100755 index 00000000..f6dc4bfd --- /dev/null +++ b/bin/riemann-portcheck @@ -0,0 +1,41 @@ +#!/usr/bin/env ruby + +# Checks for open tcp ports. +# (c) Max Voit 2017 + +require File.expand_path('../../lib/riemann/tools', __FILE__) + +class Riemann::Tools::Portcheck + include Riemann::Tools + require 'socket' + + opt :hostname, "Host, defaults to localhost", :default => `hostname`.chomp + opt :ports, "List of ports to check, e.g. '-r 80 443'", :type => :ints + + def initialize + @hostname = opts.fetch(:hostname) + @ports = opts.fetch(:ports) + end + + def tick + for thisport in @ports + # try opening tcp connection with 5s timeout; + # if this fails, the port is considered closed + portopen = Socket.tcp(@hostname, thisport, connect_timeout: 5) { true } rescue false + if portopen + state = "ok" + else + state = "critical" + end + report( + :host => "#{@hostname}", + :service => "port #{thisport}", + :state => "#{state}", + :tags => ["portcheck"] + ) + end + end + +end + +Riemann::Tools::Portcheck.run