Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk12 min

How to Create Custom Nagios Plugins with Bash on a Linux VPS

Build a reliable Nagios Bash plugin on a Linux VPS: implement the four exit states, parse warning and critical ranges, return performance data, test as the Nagios user, and connect the script to a command and service definition.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a Bash script as an executable Nagios check: read the condition you care about, print a concise status line (optionally followed by performance data), and exit with Nagios status 0, 1, 2, or 3. Install the executable where your Nagios package keeps plugins, run it as the Nagios user, then connect it to a command and service definition. The exact directories and reload commands depend on your Linux distribution and Nagios packaging.

What a custom Nagios plugin must do

A Nagios plugin is not a daemon or a special binary format. It is an executable check that Nagios runs on a schedule. The check can inspect a local file, process, listening port, queue, API response, disk measurement, or any other condition that can be evaluated on the VPS. Nagios consumes two outputs from every run: the process exit status for the machine-readable state and at least one line on standard output for the operator-readable explanation. The official Plugin API states that scripts and executables must exit with one of the possible return values and return at least one line of text to STDOUT (Nagios Core Plugin API).

As an Amazon Associate I earn from qualifying purchases.

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.

Keep the first output line short enough for the Nagios interface, notifications, and a pager. Put the reason for the state first, then add performance data after a pipe character when the value should be graphed or retained for historical analysis. A plugin that silently exits, writes only to STDERR, or returns a state that does not match its message is difficult to operate and can produce misleading alerts.

The four standard return codes

Exit code State Use it when
0 OK The measured condition is within the acceptable range.
1 WARNING A warning threshold has been reached, but the service is not yet in the critical condition.
2 CRITICAL The critical threshold has been reached or the service is failing.
3 UNKNOWN The plugin cannot determine a trustworthy state, for example because an argument is invalid or a required command failed.

Define these values in the script instead of scattering literal numbers through conditionals. That makes later changes and reviews less error-prone.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Plan the check before writing Bash

Choose one focused question for each plugin. Examples include whether a file is present, how old a queue is, whether a process is running, how much space a filesystem consumes, or whether an HTTP endpoint responds. A single-purpose check gives Nagios one clear state and one clear remediation path. If a script checks unrelated services and returns one combined result, an alert will not tell you which component needs attention.

Define the measured value and units

Write down exactly what the script measures and in which units. A percentage, seconds, bytes, count, and load value require different thresholds and performance-data units. Decide whether a larger value is worse or whether a smaller value is worse. Record the sampling method as well: a one-second process count, a file age in seconds, and a cumulative counter do not have interchangeable threshold meanings.

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

Define failure modes

  • Return UNKNOWN when arguments are missing, malformed, or outside the range your check can interpret.
  • Return CRITICAL when the service-specific failure itself is confirmed.
  • Decide what a missing file, permission error, empty API response, or unavailable local command means, and document that policy in the output message.
  • Set an internal timeout for commands that can block. A hung child process can consume a Nagios worker and prevent other checks from running.

Use a predictable interface

Accept warning, critical, and timeout options such as -w/--warning, -c/--critical, and -t/--timeout. Reject an omitted value, a non-numeric value where a number is required, and a critical threshold that contradicts the check’s documented ordering. Provide -h/--help so an administrator can discover the interface without opening the source.

Implement the Bash skeleton safely

Start with an explicit interpreter path. #!/usr/bin/env bash is portable when env can locate Bash; an absolute Bash path used by your VPS is even more deterministic. Define the four Nagios states, parse and validate arguments, run one measurement, classify it, print the result, and exit with the matching constant.

Use absolute paths for external programs. Nagios may run with a restricted or unexpected PATH, and relying on an administrator’s interactive shell can make a script work manually but fail under the scheduler. The plugin guidelines also warn against unsafe command lookup through PATH. Use paths such as /usr/bin/awk, /bin/cat, or the paths confirmed on your distribution; do not assume that every VPS places a utility in the same directory.

Minimal illustrative check

The following pattern reads the first field of /proc/loadavg, converts it to an integer, compares it with warning and critical values, and emits performance data. It is an illustrative pattern rather than a universal load policy: adapt the metric, units, thresholds, and command paths to your VPS.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
#!/usr/bin/env bash
OK=0; WARNING=1; CRITICAL=2; UNKNOWN=3
warning=80; critical=90
value=$(/usr/bin/awk '{print int($1)}' /proc/loadavg) || {
  echo "UNKNOWN - cannot read load average"
  exit "$UNKNOWN"
}
if (( value >= critical )); then
  echo "CRITICAL - load value=${value} | load=${value};${warning};${critical};0"
  exit "$CRITICAL"
elif (( value >= warning )); then
  echo "WARNING - load value=${value} | load=${value};${warning};${critical};0"
  exit "$WARNING"
else
  echo "OK - load value=${value} | load=${value};${warning};${critical};0"
  exit "$OK"
fi

Because int($1) truncates the load value, this example deliberately demonstrates the mechanics rather than a production-ready load monitor. A real implementation should choose a meaningful sampling and precision policy, use thresholds appropriate to the VPS, and explain the chosen policy in its help text.

Add option parsing and validation

For a reusable plugin, replace hard-coded thresholds with parsed arguments. A conventional Bash approach is to process short options with getopts and handle long options in a small case loop. Whichever method you choose, validate before running the check:

  • Require both warning and critical values when the check needs them.
  • Accept only the numeric format your comparison code handles; do not let an empty string become zero through implicit arithmetic conversion.
  • Check that the timeout is a positive number and that it is applied to every potentially blocking operation.
  • Print a usage line and exit UNKNOWN for malformed input, rather than silently selecting defaults.

Keep argument errors distinguishable from service failures. An operator who sees UNKNOWN - invalid critical threshold can correct configuration; an unexplained CRITICAL result may trigger unnecessary incident work.

Apply Nagios threshold ranges correctly

Nagios thresholds are ranges, not merely two numbers. The plugin guidelines define the syntax as an optional @ followed by a start and end separated by a colon. An alert occurs when the measured value falls outside the specified acceptable range; the @ prefix reverses that test so the alert occurs inside the range. A bare number is shorthand for a range whose lower bound is zero and whose upper bound is that number for the usual non-negative check.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Form Interpretation for a non-negative measurement Typical use
10 Alert above 10. Warn or fail when a count exceeds a limit.
10:20 Alert below 10 or above 20. Keep a value within a band.
10: Alert below 10; there is no upper bound. Require a minimum level.
~:10 Alert above 10; the lower bound is negative infinity. Express an upper limit when negative values are possible.
@10:20 Alert at values from 10 through 20, inclusive. Flag an unsafe interval rather than values outside it.

Use the same range parser for warning and critical values, then evaluate critical first. If both thresholds can match, returning CRITICAL before WARNING ensures the most severe state wins. Performance data should carry the exact warning and critical strings when possible so graphing and operators can see the limits that produced the state.

Return performance data for graphs and history

Append performance data to the first output line after |. The documented form is label=value[UOM];[warn];[crit];[min];[max]. Labels are separated by spaces, and units may include %, s, B, or c. For example:

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
OK - queue depth 3 | queue=3c;10;20;0

Use a stable label such as queue, latency, or disk_used; changing labels between runs creates fragmented graphs. Include minimum and maximum values only when they are meaningful. A percentage should carry %, a duration should carry s, and a byte measurement should carry B. Do not put diagnostic prose after the pipe where a monitoring system expects metric syntax.

Test the plugin outside Nagios first

Save the script with a descriptive name, for example check_queue_age.sh, and make it executable with chmod 755 check_queue_age.sh or a tighter mode that still permits the Nagios execution user to run it. Test all state paths from a shell before adding configuration.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Run the help option and confirm that missing or malformed arguments produce a useful usage message and UNKNOWN status.
  2. Run a normal case and inspect both the text and echo $? for exit code 0.
  3. Force the warning condition with a temporary test value and verify code 1, the word WARNING, and the expected performance data.
  4. Force the critical condition and verify code 2.
  5. Remove or deny access to an input and verify that the documented UNKNOWN or CRITICAL policy is followed.
  6. Run the command as the Nagios user, not only as root or your login account. This catches permission, working-directory, environment, and PATH assumptions.
  7. Run it repeatedly while observing elapsed time. A command that can hang needs an internal timeout before it is scheduled frequently.

Keep temporary files in a directory with appropriate ownership and permissions. Avoid predictable names in shared locations, clean up files on every exit path, and do not follow an unexpected symlink when writing state. These practices are part of the Nagios plugin development guidance alongside concise STDOUT, input validation, full command paths, and timeout handling (Nagios Plugin Development Guidelines).

Install a custom plugin on a Linux VPS

Nagios packages use distribution- and installation-dependent directories. Find the plugin directory from your Nagios configuration or package documentation rather than copying a path from another VPS. Common layouts include a directory under the Nagios installation prefix or a distribution-managed libexec directory, but neither should be treated as universal.

  1. Choose a root-owned directory already used for Nagios plugins, or create an installation-specific custom directory with controlled ownership.
  2. Copy the script there, preserve the shebang, and set executable permissions.
  3. Ensure the Nagios execution user can read the script and every input it needs. Grant only the minimum access required; do not make sensitive files world-readable merely to satisfy a check.
  4. Run the complete command manually as that user, including warning, critical, and timeout arguments.
  5. Record the final path and arguments before writing the Nagios command definition.

Do not rely on the script’s current working directory. Nagios can invoke it from a different directory, so use absolute paths for files, helper programs, and any configuration the check reads. If the check needs environment variables, define them explicitly in the Nagios execution context or pass configuration through arguments and a protected file.

Connect the script to Nagios configuration

A Nagios command definition gives the executable a stable name and maps positional macros to its arguments. The following is an installation-dependent example; adapt the plugin directory, macro names, and configuration file location to your package.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
define command{
  command_name    check_custom_load
  command_line    /path/to/plugins/check_custom_load.sh -w $ARG1$ -c $ARG2$
}

Attach that command to a service definition and supply values for the macros:

define service{
  host_name              your-vps-host
  service_description    Custom load check
  check_command          check_custom_load!80!90
  check_interval         5
  retry_interval          1
}

The interval values above are examples, not a recommendation for every VPS. Choose a schedule that matches the failure you are detecting and the script’s runtime. A check that launches an expensive API request should not run as frequently as a cheap local file test.

Validate before reloading

  1. Run Nagios’s configuration verification command with the configuration file used by your installation, commonly in the form nagios -v /path/to/nagios.cfg. Use the binary and path supplied by your package if they differ.
  2. Fix every syntax error, unknown command, missing macro, and permission warning before reloading.
  3. Reload the Nagios service using the service manager and command provided by your distribution.
  4. In the Nagios interface, schedule or wait for the service check and inspect the exact plugin output, status, and performance data.

If the configuration validates but the service is UNKNOWN, compare the command line shown by Nagios with the command that succeeded in your shell as the Nagios user. Differences in quoting, macro expansion, environment, and file permissions are common causes.

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

Make checks reliable and secure

Protect command execution

Use fixed paths and avoid constructing shell commands from untrusted macro values. If an argument is intended to be a number, validate it as a number and use arithmetic comparison rather than interpolating it into an eval expression. Quote variable expansions when they represent paths or text. Never allow a host or service argument to become an arbitrary command fragment.

Bound every external operation

Network clients, filesystem operations on remote mounts, and subprocesses can block. Apply an internal timeout using the timeout utility available on your VPS or the relevant API’s own timeout option, then translate a timeout into the policy you documented. Ensure the timeout covers the actual child process and does not leave a background child running after the plugin exits.

Keep output deterministic

Send the one-line status to STDOUT. Send verbose debugging to a controlled log or enable it only through an explicit debug option; unsolicited lines can interfere with parsers and obscure the first status line. Avoid locale-dependent decimal separators and date formats when parsing command output. If a helper returns unexpected text, fail as UNKNOWN rather than classifying a guessed value.

Handle files and privileges carefully

Use private temporary directories or securely created temporary files, set restrictive permissions, and remove them on normal and error exits. Check ownership and mode before consuming a file that could be replaced by another user. The plugin should run with the least privilege needed for its measurement; escalating to root to read a value is usually a sign that permissions or the monitoring design need review.

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

Troubleshoot common failures

Nagios reports UNKNOWN immediately

  • Run the exact command as the Nagios user and inspect the expanded arguments.
  • Check that the script is executable and its interpreter exists at the shebang path.
  • Confirm every helper uses an absolute path and that the Nagios user can read the target files.
  • Look for an empty macro caused by a missing !argument in the service definition.

The text says OK but Nagios shows CRITICAL

Check the final exit statement and capture the status with echo $?. A command substitution or pipeline can mask a failing command unless its status is handled explicitly. Verify that the branch printing the message exits with the same state constant.

Thresholds never trigger

Print the parsed value temporarily, confirm its unit and precision, and test each boundary value. A value in bytes compared with a threshold intended for megabytes, or an integer truncated from a decimal, can make a correct comparison appear broken. Recheck whether the range is meant to alert inside or outside the interval and whether the @ prefix was intended.

Performance data is missing or ungraphable

Ensure the pipe is on the first output line, the metric label contains no spaces, and the value follows label=value[UOM];[warn];[crit];[min];[max]. Keep the label stable and use the correct unit. Diagnostic sentences belong before the pipe, not among metric fields.

When Bash is the right choice

Bash is convenient for small, local checks that compose standard Unix tools already present on a Linux VPS. It has little deployment overhead, is easy to inspect on the host, and works well for files, processes, simple counters, and command exit statuses. Its weak points are complex numeric parsing, structured API responses, concurrency, extensive error handling, and long-term testability. When a check needs robust JSON parsing, many branches, parallel operations, or substantial unit tests, another language may be easier to maintain and less ambiguous. The Nagios contract remains the same regardless of language: valid exit status, useful STDOUT, correctly defined thresholds, and bounded runtime.

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

Pre-deployment checklist

  • The script starts with the Bash interpreter used by the VPS.
  • OK, WARNING, CRITICAL, and UNKNOWN are defined and returned consistently.
  • Warning, critical, timeout, and help options are parsed and malformed values are rejected.
  • Every external command and important file uses an installation-appropriate absolute path.
  • The check measures one condition in documented units and applies the intended Nagios range semantics.
  • The first STDOUT line is concise, and performance data follows the pipe in the documented format.
  • Blocked operations have an internal timeout.
  • The file, temporary-file handling, and privileges are safe for the Nagios execution user.
  • All four state paths were tested manually as that user.
  • Nagios configuration validation passed before reload, and the live service output was inspected afterward.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.