Skip to content

Instantly share code, notes, and snippets.

@absolutejam
Created December 14, 2017 19:08
Show Gist options
  • Save absolutejam/20314e86f1c9c18cc8e5196e323796f5 to your computer and use it in GitHub Desktop.
Save absolutejam/20314e86f1c9c18cc8e5196e323796f5 to your computer and use it in GitHub Desktop.
check-windows-port-listening.rb
#! /usr/bin/env ruby
#
# check-windows-port-listening.rb
#
# DESCRIPTION:
# Check to see which ports are listening, using netstat.
# First draft.
#
# OUTPUT:
# plain text
#
# PLATFORMS:
# Windows
#
# DEPENDENCIES:
# gem: sensu-plugin
#
# USAGE:
# check-windows-port-listening.rb -ports 80,443,3389
#
# NOTES:
# Uses netstat binary.
#
# LICENSE:
# Copyright 2017 <james@absolutejam.co.uk>
# Released under the same terms as Sensu (the MIT license); see LICENSE for details.
#
require 'sensu-plugin/check/cli'
class CheckListeningPorts < Sensu::Plugin::Check::CLI
option :ports,
short: '-p PORT',
long: '--port PORT',
:required => true,
proc: proc { |a| a.split(',') }
def initialize
super
@listening_ports = []
@missing_ports = []
end
def listening_ports
`netstat -afo`.split("\n").drop(4).each do |line|
begin
protocol, local, foreign, state, pid = line.chomp.lstrip.split(/\s+/)
# Match ipv4 with port (0.0.0.0:0)
localip, localport = local.match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:(\d+)/).to_a
next if /\S/ !~ line
next if !localport
next if config[:ports] && !config[:ports].include?(localport)
next if state != 'LISTENING'
next if @listening_ports.include?(localport)
rescue
unknown "malformed line from netstat: #{line}"
end
@listening_ports << localport
end
config[:ports].each do |p|
@missing_ports << p if !@listening_ports.include?(p)
end
end
def usage_summary
missing = (@missing_ports).join(', ')
"The following ports are NOT listening: #{missing}"
end
def run
listening_ports
critical usage_summary unless @missing_ports.empty?
ok "All specified ports are listening"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment