Zabbix: monitor a TCP port with the Zabbix Agent

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, December 03, 2011

Follow me on Twitter as @mattiasgeniar

If you want to monitor a remote host from the Zabbix Agent (so not via a Zabbix Distributed monitoring setup or Zabbix Proxy), you can use the following simple script. This is useful if you have services that are only bound on localhost/127.0.0.1 and thus cannot be checked from the outside.

Custom script for testing local ports

For that, you need a workaround via the Zabbix Agent to check locally if the port is available and accepting connections.

#!/bin/bash
# Attempt to open a connection on a particular port (1234)
/usr/bin/nc -z 10.0.1.1 1234 > /dev/null

# See if it worked
if [ $? -eq 0 ]; then
  # It worked, return value is 0
  echo 1
else
  # Return value is not 0, command failed
  echo 0
fi

That will need netcat (yum install nc) to test if the connection on that port succeeded. If it doesn’t, it’ll return a 0 value. If it did succeed, it will return 1.

Custom UserParameter in Zabbix Agent

You can then add a custom parameter to call that script and return the values to Zabbix.

UserParameter=custom.monitor_port,/etc/zabbix/externalscripts/custom_check_port_1234.sh

If you want, it’s easily extended to allow the script to be given parameters that can be given via Zabbix.

UserParameter=custom.monitor_port[*],/etc/zabbix/externalscripts/custom_check_port.sh $1

And the script should be something like this.

#!/bin/bash
# Attempt to open a connection on a particular port (1234)
/usr/bin/nc -z 10.0.1.1 $@ > /dev/null

# See if it worked
if [ $? -eq 0 ]; then
  # It worked, return value is 0
  echo 1
else
  # Return value is not 0, command failed
  echo 0
fi

Now you only have to add that item in Zabbix to retrieve the values.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.