Zabbix: monitor a TCP port with the Zabbix Agent

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.