system-admin intermediate
How to check disk space and send email alert in Perl?
Question
How to check disk space and send email alert in Perl?
Checking disk space and sending email alerts in Perl is a common system administration task. Perl's flexibility lets you do this easily using built-in functions and core modules, without needing extra dependencies.
Approach
- Check disk space: Use
dfcommand output or Perl'sstatvfs(if available) to retrieve disk usage statistics. - Parse usage: Extract total, used, and available space, and calculate percentage used.
- Send email alert: Use Perl's core
opencommand to pipe to a system mailer (e.g.sendmailormail). Alternatively, construct an email and print it to STDOUT for testing. - Threshold-based alert: Only send the email if disk usage exceeds a defined threshold.
Key Perl concepts involved
qx//- Array and string splitting to parse CLI output.
- Conditional tests to check threshold.
- Opening a pipe with
opento send mail. - Use of sigils -
$for scalars,@for arrays. - Context awareness: scalar vs list context (e.g., split in list context returns array).
Example: Check root filesystem disk space and email alert
#!/usr/bin/perl
use strict;
use warnings;
# Configuration
my $threshold_percent = 80; # Alert if usage exceeds 80%
my $filesystem = '/'; # Filesystem to check, usually root '/'
my $recipient = 'admin@example.com'; # Email recipient
# Get disk space via 'df -P' for portability
my @df_output = qx(df -P $filesystem);
# Example df -P output line:
# Filesystem 1024-blocks Used Available Capacity Mounted on
# /dev/sda1 20511356 12345678 7135678 64% /
# Skip header, parse next line
my $line = $df_output[1] or die "No df output for $filesystem";
my @fields = split /\s+/, $line;
# df -P format: Filesystem, blocks, Used, Available, Use%, Mounted on
# Indexes: 0 1 2 3 4 5
my $used_percent = $fields[4];
$used_percent =~ s/%//; # remove trailing % sign
print "Disk Usage for $filesystem: $used_percent%\n";
if ($used_percent >= $threshold_percent) {
# Send email alert
my $subject = "Disk space alert: $filesystem usage is $used_percent%";
my $message = <<"END_MSG";
Warning: Disk usage on filesystem $filesystem has reached $used_percent% which exceeds the threshold of $threshold_percent%.
Please check the system and free up space as needed.
-- System Monitor
END_MSG
# Try using sendmail directly
open(my $mail, '|-', '/usr/sbin/sendmail -t') or die "Could not open sendmail: $!";
print $mail "To: $recipient\n";
print $mail "Subject: $subject\n";
print $mail "\n"; # header/body separator
print $mail $message;
close($mail);
print "Alert email sent to $recipient.\n";
} else {
print "Disk usage is within limits.\n";
}
Explanation
This script:
- Runs
df -P /to get disk usage for root filesystem. - Parses the output line for used percentage.
- Checks if usage exceeds 80% threshold.
- If exceeded, formats a simple plain-text email.
- Opens a pipe to
/usr/sbin/sendmail -t(common on Linux/Unix systems) and writes the email headers and body. - If usage is below threshold, just prints status to STDOUT.
Common Pitfalls and Gotchas
- Different
dfoutput formats: Use-P(POSIX) to avoid issues with locale or long device names splitting into multiple fields. - Sendmail path: On some systems,
sendmailmay be at a different path (e.g., /usr/bin/sendmail). Adjust accordingly. - Email sending: This example assumes a local mail transfer agent (MTA) like Sendmail or Postfix is installed and configured.
- Permissions: Running this might require permissions to read disk info or send email.
- Threshold tuning: Set your alert threshold appropriately for your system needs.
Enhancements
- Parse multiple filesystems by looping over
dfoutput lines. - Use the core module
File::Statvfs(from Perl 5.12+) for a pure Perl solution without parsingdf. - Use Email::Sender or MIME::Lite for richer HTML emails (requires CPAN modules).
- Integrate logging or retry sends for more robust monitoring.
This approach demonstrates Perl's “There's more than one way to do it” (TMTOWTDI) philosophy — using simple OS commands versus dedicated modules to suit your environment.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 26ms
Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Disk Usage for /: 16%
Disk usage is within limits.
STDERR
(empty)