How to monitor disk usage and send alert in Perl?
Question
How to monitor disk usage and send alert in Perl?
Monitoring disk usage and sending alerts with Perl is a common task in system administration. Perl's text-processing strengths and the availability of built-in file and system interaction features make it well suited for this. The general approach involves checking disk usage via df command or Perl's system calls, parsing the results, and then triggering an alert (for example, printing a warning or emailing) if usage exceeds a threshold.
Key Concepts
- Executing system commands: Use backticks
``orqx//to capture command output. - Parsing output: Split and regex match lines to extract relevant info.
- Threshold comparison: Typical disk usage is measured as a percentage; numeric comparison drives alerting logic.
- Alerts: Could be as simple as printing warnings or can integrate with email via
system("mail ...")or core modules likeNet::SMTP(not shown here to keep example simple and portable). - Sigils: Scalars
$for single values like usage percent, arrays@to hold lines, hashes%for keyed info. - Context: Scalar vs list context is important when capturing command output. Backticks in list context return array lines; in scalar context return whole string.
Common Pitfalls
- Parsing
dfoutput can vary by platform; fields might differ or mount points with spaces may break naïve parsing. - Always validate numeric extraction and be careful with system locales affecting decimal/comma formatting.
- Use explicit paths for system commands (
/bin/df) on production scripts for security and reliability. - Beware of running the script without sufficient privileges to check all mount points.
Example: Simple Disk Usage Monitor in Perl
This script runs df -h, parses the output, and prints alerts if usage exceeds 80% (customize as needed). It demonstrates capturing command output, parsing it, and conditional logic for alerting.
#!/usr/bin/env perl
use strict;
use warnings;
# Threshold percentage for alert
my $threshold = 80;
# Run df -h and capture output (human-readable sizes)
my @df_output = qx(df -h);
# Skip header line and parse remaining lines
# Typical df -h output columns: Filesystem Size Used Avail Use% MountedOn
shift @df_output;
foreach my $line (@df_output) {
chomp $line;
# Split line by whitespace; mount points with spaces can be tricky
# So, a safer approach is to capture last column separately
# Here, we split into at most 6 parts
my @fields = split /\s+/, $line, 6;
next unless @fields == 6; # Skip malformed line
my ($filesystem, $size, $used, $avail, $use_perc, $mount) = @fields;
# Remove trailing % and convert to integer
if ($use_perc =~ /^(\d+)%$/) {
my $used_percent = $1;
if ($used_percent >= $threshold) {
print "ALERT: Disk usage on '$mount' is ${used_percent}% (threshold $threshold%)\n";
} else {
print "OK: Disk usage on '$mount' is ${used_percent}%\n";
}
} else {
print "WARNING: Could not parse usage for '$mount' from '$use_perc'\n";
}
}
How this works: The script executes the df -h command, captures the multi-line output, skips the header, and then parses each line into components. The key field is Use%, from which the numeric percent is extracted. If usage exceeds the threshold, an alert line is printed.
Extending This Example
- Send Email Alerts: Use core
Net::SMTPor system mail commands to email the alert. - Log to a file: Append alerts to a rotating log file for auditing.
- Better Parsing: Use
Filesys::DiskUsage(CPAN) for cross-platform disk stats, though this example sticks to core modules and commands. - Run as Cron Job: Schedule this script via cron to run periodically and notify proactively.
By taking advantage of Perl’s flexible string parsing and system interaction features, writing your own disk usage monitor and alert system is straightforward and customizable to your environment.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 19ms
OK: Disk usage on '426k 761M 0% /' is 16%
ALERT: Disk usage on '742 0 100% /dev' is 100% (threshold 80%)
OK: Disk usage on '5 761M 0% /System/Volumes/VM' is 7%
OK: Disk usage on '2.4k 761M 0% /System/Volumes/Preboot' is 16%
OK: Disk usage on '304 761M 0% /System/Volumes/Update' is 1%
OK: Disk usage on '1 4.9M 0% /System/Volumes/xarts' is 2%
OK: Disk usage on '34 4.9M 0% /System/Volumes/iSCPreboot' is 2%
OK: Disk usage on '80 4.9M 0% /System/Volumes/Hardware' is 1%
OK: Disk usage on '2.4M 761M 0% /System/Volumes/Data' is 63%
WARNING: Could not parse usage for '100% 0 0 - /System/Volumes/Data/home' from '0Bi'
OK: Disk usage on '8.9M 17G 0% /Volumes/SSD' is 12%
OK: Disk usage on '2.3M 830M 0% /private/var/folders/bk/m6c3msl54cv7160sw1thfxm40000gn/X/67A0887E-74D0-507D-9B06-E669766991C2' is 61%
OK: Disk usage on '2.3M 830M 0% /private/var/folders/bk/m6c3msl54cv7160sw1thfxm40000gn/X/9CB5E8F2-2EE7-5CDF-9095-F2A0F9435C4A' is 61%
OK: Disk usage on '427k 761M 0% /System/Volumes/Update/mnt1' is 16%
ALERT: Disk usage on '17k 4.3G 0% /Volumes/Antigravity' is 100% (threshold 80%)
(empty)