Skip to content

Instantly share code, notes, and snippets.

@dgrant
Last active December 14, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgrant/5156399 to your computer and use it in GitHub Desktop.
Save dgrant/5156399 to your computer and use it in GitHub Desktop.
I run this file in a cron job every 5 minutes. It checks whether your drives' usage has exceeded a configurable threashold, and if so, it sends an email to a configurable e-mail address.
#!/usr/bin/env python3
"""
A simple program that sends warnings when disk space on one or more hard
drives has reached a critical level
"""
from subprocess import Popen, PIPE
##############################################################
#CHANGE SETTINGS BELOW
##############################################################
EMAIL_ADDRESS = 'davidgrant@gmail.com'
THRESHOLD = 90
#DRIVE_NAMES = ['/dev/hde1', '/dev/hde2']
DRIVE_NAMES = []
EXCEPTIONS = ['sr0', 'sr1', 'none', 'udev']
#EXCEPTIONS = []
#if SEND_EMAIL=True, email will be sent, else, just stdout
SEND_EMAIL = True
USE_SUDO = True
##############################################################
#DON'T TOUCH ANYTHING BELOW UNLESS YOU KNOW WHAT YOU ARE DOING
##############################################################
def main():
""" Main method """
msg = []
cmd = ['/bin/df',
'--exclude-type=udf',
'--exclude-type=fuse.gvfs-fuse-daemon',
'--exclude-type=tmpfs',
'--exclude-type=devtmpfs',
'--local']
if USE_SUDO:
cmd = ['sudo'] + cmd
output = Popen(cmd,
stdout=PIPE, shell=False).communicate()[0].decode()
lines = output.split('\n')[1:-1]
drives_map = dict([(line.split()[0], int(line.split()[4][:-1]))
for line in lines])
# Get included drives or all
drives = [drive for drive in drives_map if (drive in
DRIVE_NAMES or len(DRIVE_NAMES) == 0)]
# Exclude some drives
for exception in EXCEPTIONS:
drives = [drive for drive in drives if not exception in
drive]
# Check which drives exceed the percentage
drives_exceed = [drive for drive in drives if drives_map[drive] >
THRESHOLD]
# Make an email message
for drive in drives_exceed:
msg.append("drive " + drive + " is too full.")
if len(msg) > 0 :
msg = "\n".join(msg)
if SEND_EMAIL:
mail_command = 'echo "%s" |mail -s "[disk space full]" %s'
Popen(mail_command % (msg, EMAIL_ADDRESS), shell=True)
else:
print(msg)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment