sysadmin intermediate

How to monitor disk usage and send alerts

Question

How can I write a Perl script to check disk usage and send an email alert if it exceeds a threshold?

Use the df command output and parse it with Perl:

#!/usr/bin/perl
use strict;
use warnings;
use Email::Simple;
use Email::Sender::Simple qw(sendmail);

my $threshold = 80;
my @lines = `df -h`;

foreach my $line (@lines) {
    next if $line =~ /^Filesystem/;
    if ($line =~ /(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)%\s+(\S+)/) {
        my ($filesystem, $usage_pct, $mount) = ($1, $5, $6);
        if ($usage_pct >= $threshold) {
            my $email = Email::Simple->create(
                header => [
                    To      => 'admin@example.com',
                    From    => 'monitor@example.com',
                    Subject => "Disk Alert: $mount at $usage_pct%",
                ],
                body => "$filesystem mounted on $mount is at $usage_pct% capacity.\n",
            );
            sendmail($email);
        }
    }
}

This script parses df output and sends email alerts when disk usage exceeds the threshold.

Was this helpful?

Related Questions