Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A custom Nagios plugin is an executable check: it evaluates one condition, prints a concise result to standard output, and exits with Nagios’s status code. On a Linux VPS, Bash is a practical choice for checks that combine local files, processes, sockets, command output, or simple API calls. This guide shows how to design the script, implement warning and critical thresholds, emit performance data, install it safely, connect it to a service definition, and troubleshoot the common failure modes.

The Nagios plugin contract

Nagios Core does not require a plugin to be written in a particular language. It requires two things: a status exit code and at least one line of text on standard output. The official Nagios Core Plugin API describes this contract. Nagios uses the exit code as the machine-readable state and displays the first output line as the explanation for operators.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Exit code State Use it when
0 OK The measured condition is inside the acceptable range.
1 WARNING A warning threshold has been crossed, but the service is not yet considered a failure.
2 CRITICAL A critical threshold has been crossed or the service cannot perform its required check.
3 UNKNOWN Arguments are invalid, data cannot be interpreted, or the plugin cannot determine a reliable state.

Always make the status and message agree. Returning 0 while printing “CRITICAL” creates contradictory information for the scheduler, notifications, and dashboards. Conversely, a useful message with no output at all leaves an operator without context even when the exit code is correct.

Plan the check before writing Bash

Keep one plugin focused on one service condition. Define the value being measured, its unit, the source of the value, acceptable limits, and the behavior when the source is unavailable. For example, a root-filesystem check can measure used space as a percentage, warn at 80, and become critical at 90. A process check might count matching processes; a queue check might read a local command or API; a certificate check might measure days until expiry.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application:Upgraded attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Warranty & Support: Our Electric air duster comes with 5 years warranty and 24/7 customer service. During this period, if you have any questions,pls kindly feel free to contact us.
  • Input: command-line options such as -w for warning, -c for critical, -t for timeout, and a target path or service name.
  • Measurement: one command or a small, deterministic pipeline that produces a value.
  • Evaluation: threshold comparisons with clearly documented units and boundary behavior.
  • Output: a short first line for the Nagios UI, optionally followed by performance data after a pipe character.
  • Failure policy: a predictable choice between UNKNOWN and CRITICAL when collection fails or times out.

Write down whether equality triggers a state. In the example below, a value equal to the critical limit is CRITICAL, and a value equal to the warning limit is WARNING only when it has not already met the critical limit.

A complete Bash example: root filesystem usage

The following illustrative plugin checks the filesystem containing a supplied mount point. It accepts integer percentage thresholds, uses absolute paths for external commands, applies an internal timeout, prints performance data, and exits with the matching Nagios code. It is an example pattern rather than a tested, universal script; verify command locations and adapt the collection logic to your VPS distribution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#!/usr/bin/env bash

OK=0
WARNING=1
CRITICAL=2
UNKNOWN=3

usage() {
  echo "Usage: $0 -w PERCENT -c PERCENT [-t SECONDS] [-m MOUNTPOINT]"
}

warning=""
critical=""
timeout_seconds=10
mountpoint="/"

while getopts ":w:c:t:m:h" opt; do
  case "$opt" in
    w) warning="$OPTARG" ;;
    c) critical="$OPTARG" ;;
    t) timeout_seconds="$OPTARG" ;;
    m) mountpoint="$OPTARG" ;;
    h) usage; exit "$OK" ;;
    :) echo "UNKNOWN - option -$OPTARG requires a value"; exit "$UNKNOWN" ;;
    ?) echo "UNKNOWN - invalid option: -$OPTARG"; usage; exit "$UNKNOWN" ;;
  esac
done

if [[ -z "$warning" || -z "$critical" ]]; then
  echo "UNKNOWN - both warning and critical thresholds are required"
  exit "$UNKNOWN"
fi

if [[ ! "$warning" =~ ^[0-9]+$ || ! "$critical" =~ ^[0-9]+$ || ! "$timeout_seconds" =~ ^[1-9][0-9]*$ ]]; then
  echo "UNKNOWN - thresholds and timeout must be positive integers"
  exit "$UNKNOWN"
fi

if (( warning >= critical || warning > 100 || critical > 100 )); then
  echo "UNKNOWN - use 0-100 with warning lower than critical"
  exit "$UNKNOWN"
fi

if [[ ! -d "$mountpoint" ]]; then
  echo "UNKNOWN - mount point does not exist: $mountpoint"
  exit "$UNKNOWN"
fi

# Verify these paths with command -v on the target VPS before deployment.
df_output=$(/usr/bin/timeout "${timeout_seconds}s" /bin/df -P "$mountpoint" 2>/dev/null) || {
  echo "UNKNOWN - df failed or exceeded ${timeout_seconds}s"
  exit "$UNKNOWN"
}

used_percent=$(printf '%sn' "$df_output" | /usr/bin/awk 'NR == 2 { gsub(/%/, "", $5); print $5 }')
if [[ ! "$used_percent" =~ ^[0-9]+$ ]]; then
  echo "UNKNOWN - could not parse filesystem usage"
  exit "$UNKNOWN"
fi

if (( used_percent >= critical )); then
  echo "CRITICAL - ${mountpoint} is ${used_percent}% used | usage=${used_percent}%;${warning};${critical};0;100"
  exit "$CRITICAL"
elif (( used_percent >= warning )); then
  echo "WARNING - ${mountpoint} is ${used_percent}% used | usage=${used_percent}%;${warning};${critical};0;100"
  exit "$WARNING"
else
  echo "OK - ${mountpoint} is ${used_percent}% used | usage=${used_percent}%;${warning};${critical};0;100"
  exit "$OK"
fi

The script deliberately validates all user-supplied values before invoking a command. The /usr/bin/timeout wrapper prevents a blocked filesystem operation from holding a Nagios worker indefinitely. If your system stores df, awk, or timeout elsewhere, replace those paths after checking them on the VPS; do not rely on the scheduler’s inherited PATH.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Understanding warning and critical thresholds

The example uses a simple upper-bound policy: values at or above the warning limit produce WARNING, and values at or above the critical limit produce CRITICAL. That is appropriate for usage, latency, queue depth, and similar “higher is worse” measurements. For “lower is worse” metrics such as free space or available workers, reverse the comparison or measure the inverse quantity.

Nagios plugins also support a range notation documented in the Nagios Plugins Development Guidelines. Common forms include:

Range Meaning Typical interpretation
10 Alert outside 0 through 10. Warn when a value is greater than 10.
10: Alert below 10. Useful when a minimum acceptable value is required.
~:10 Alert above 10 while allowing any value below 0. Useful for metrics that can legitimately be negative.
10:20 Alert outside 10 through 20. Require a value to stay within a bounded interval.
@10:20 Alert inside 10 through 20. Use when the middle of the range is the failure condition.

Range syntax is a contract between the plugin and its users. Document the unit and whether the range is inclusive, then test boundary values such as exactly 10 and exactly 20. If you need arbitrary ranges, decimals, negative values, or different warning and critical semantics, implement and test a dedicated range parser rather than silently treating every argument as an integer upper limit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Plugin output and performance data

The first output line should identify the state, the target, and the measured value without a long diagnostic. The guidelines require a status message on standard output and define performance data after a pipe character. The documented format is label=value[UOM];[warn];[crit];[min];[max].

  • label identifies the metric; use a stable, graph-friendly name without spaces.
  • value is the measured number.
  • UOM may be omitted or may identify units such as %, s, B, or c.
  • warn and crit repeat the thresholds used by the check when that makes graphs self-describing.
  • min and max are optional bounds for the metric.

For the filesystem plugin, usage=87%;80;90;0;100 tells a graphing consumer that the value is a percentage with warning at 80, critical at 90, and a natural range from 0 to 100. Keep labels stable over time; changing a label creates a new series in many monitoring systems. If you emit multiple metrics, separate them with spaces after the pipe and keep the human message before the pipe concise.

Make Bash plugins safe and reliable

Use absolute command paths

Nagios may run as a restricted service account with a minimal or unexpected environment. An attacker who can influence PATH could cause an unqualified command name to resolve to a malicious executable. Use absolute paths for utilities, verify them during installation, and avoid evaluating arguments as shell code.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Validate every argument

Reject missing options, non-numeric limits, impossible relationships, unknown flags, and targets that do not exist. Quote variables whenever they are expanded. Do not concatenate untrusted input into an eval expression, a shell command string, or a temporary filename.

Bound every potentially blocking operation

A plugin that waits forever can consume a worker slot and delay unrelated checks. Apply an internal timeout to network requests, DNS lookups, API calls, and commands that read remote mounts. Decide in advance whether timeout means UNKNOWN (the state cannot be determined) or CRITICAL (the monitored service is considered failed), and use that policy consistently.

Handle temporary files carefully

Prefer pipelines and command substitution that do not require a temporary file. If a file is unavoidable, create it in a directory with appropriate permissions, use a unique name, clean it with a trap, and protect against symlink replacement. Never write predictable filenames in a world-writable directory.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Keep output and side effects limited

Plugins should inspect a service, not repair it. Avoid restarting daemons, deleting data, changing permissions, or making configuration changes from a routine check. Send diagnostics to standard output in the expected format; unexpected logging to standard output can corrupt the status line.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Install the plugin on a Linux VPS

Plugin directories and configuration locations depend on the Linux distribution and how Nagios was packaged. Common layouts include /usr/lib/nagios/plugins for distribution packages and /usr/local/nagios/libexec for source installations. Treat these as examples: identify the directory configured as Nagios’s plugin path on your VPS before copying the file.

  1. Find the active plugin directory. Inspect the Nagios configuration for the $USER1$ macro or the package documentation. The command definition normally uses that macro as the plugin directory.
  2. Copy and protect the script. For example, after selecting the correct directory, run sudo install -o root -g nagios -m 0755 check_root_fs /usr/lib/nagios/plugins/check_root_fs. Replace the directory and group with the values used by your installation.
  3. Run it manually as the Nagios account. Use sudo -u nagios /usr/lib/nagios/plugins/check_root_fs -w 80 -c 90 -m /. Confirm the message, performance data, and numeric exit code with echo $?.
  4. Define a command object. Add a command definition to the configuration file included by your installation:
define command {
    command_name    check_root_fs_custom
    command_line    $USER1$/check_root_fs -w $ARG1$ -c $ARG2$ -m $ARG3$
}
  1. Attach the command to a service. A service definition can pass the thresholds and mount point as arguments:
define service {
    host_name                  my-vps
    service_description        Root filesystem usage
    check_command              check_root_fs_custom!80!90!/
    check_interval              5
    retry_interval               1
    max_check_attempts          3
    notification_interval       60
}
  1. Validate before reloading. Run the validator appropriate to your installation, such as sudo nagios -v /etc/nagios4/nagios.cfg for a distribution layout or the Nagios binary’s -v option for a source installation. Fix every error reported before applying a reload.
  2. Reload and schedule an immediate check. Use the service manager command supplied by your package, commonly sudo systemctl reload nagios or a distribution-specific service name. In the Nagios interface, schedule an immediate check and confirm that the service output matches the manual run.

Do not assume that the web interface, daemon user, configuration filename, or service unit has the same name on every VPS. Packaging choices change those details; the command definition and service attachment are the portable concepts.

Test the plugin before enabling notifications

  • Run the script with valid warning and critical values and verify all three normal states by temporarily changing the thresholds or test fixture.
  • Test missing options, an invalid number, an inverted warning/critical pair, an unknown option, and a nonexistent mount point. Each should return UNKNOWN with a useful explanation.
  • Run as the actual Nagios account, not only as root. Check read permissions, executable permissions, environment variables, and access to any sockets or files.
  • Force a timeout with a deliberately slow test command and confirm that the plugin exits within the configured limit.
  • Check that performance data remains parseable when the value is 0, 100, or at either threshold.
  • Use the Nagios configuration validator after every command or service definition change, then inspect the scheduled check’s stored output.

Troubleshoot common failures

Symptom Likely cause Correction
“No output” or an empty service result The script exits before printing, writes diagnostics only to stderr, or is not executable. Run it as the Nagios user, print a status line on every path, and verify mode 0755 and the shebang.
UNKNOWN: command not found The daemon’s PATH does not contain a utility used by the script. Use an absolute path and verify it on the VPS.
Works in a shell but fails in Nagios Different user permissions, working directory, environment, or mount visibility. Reproduce with sudo -u nagios and use absolute paths and explicit file locations.
Every result is CRITICAL Threshold units do not match the measured value, or a percentage sign was not removed. Print the parsed value temporarily, document the unit, and compare like-for-like numbers.
Checks hang or arrive late A network or filesystem command has no internal timeout. Wrap the operation with a timeout and return the documented UNKNOWN or CRITICAL state.
Configuration reload fails A typo in a command, host, service, macro, or include file. Run the Nagios validator and correct the first reported error before checking later messages.
Graphs show separate or missing series Performance-data labels changed, units changed, or output contains malformed separators. Keep labels stable and follow the label=value[UOM];[warn];[crit];[min];[max] format.

When Bash is the right implementation

Requirement Bash is a good fit when Consider another language when
Data source The check reads local files, process listings, sockets, or standard Unix command output. You need a complex client library, deeply nested JSON, or several concurrent requests.
Numeric logic Values are simple integers or straightforward comparisons. You need precise decimal arithmetic, date calculations, or a complete range grammar.
Portability Bash and the required utilities are already installed on the VPS. The check must run across systems with very different command implementations.
Error handling A few explicit failure paths are easy to validate. You need typed exceptions, structured retries, extensive parsing, or a large test suite.
Maintenance The script remains short, single-purpose, and reviewed like configuration. It has grown into a multi-module application with shared state or concurrency.

Bash’s advantage is availability and easy composition of existing tools, not sophisticated application structure. Once quoting, parsing, retries, and concurrent calls dominate the code, a language with stronger libraries and testing support generally reduces operational risk.

Operational checklist

  • Use #!/usr/bin/env bash or the absolute Bash path installed on the VPS.
  • Define and use the four standard constants: OK 0, WARNING 1, CRITICAL 2, UNKNOWN 3.
  • Validate options, thresholds, units, and target paths before collecting data.
  • Call external programs by absolute path and quote variable expansions.
  • Print one concise status line to standard output on every exit path.
  • Place performance data after | using stable labels and documented units.
  • Enforce an internal timeout for every operation that can block.
  • Install with least-privilege ownership and execute it as the Nagios account.
  • Validate Nagios configuration before reload, then schedule and inspect a real check.
  • Keep the plugin observational; do not hide remediation actions inside a health check.

Final implementation perspective

A dependable custom plugin is small, explicit, and predictable: it measures one condition, applies thresholds whose units are clear, emits parseable output, and terminates within a known time. Bash is well suited to that shape on a Linux VPS. The quality of the result depends less on clever shell syntax than on honoring Nagios’s exit-code and output contract, validating inputs, using safe command paths, and testing under the same account and environment that executes scheduled checks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.