User Tools

Site Tools


email_alerts_on_low_free_space

Email alerts on low free space

Create /root/free-space-alerts.py:

#!/usr/bin/python
 
import sys,os,socket,subprocess
 
def get_free_GB(path):
	st = os.statvfs(dir)
	avail = st.f_bavail * st.f_bsize / (1024.0**3) # free space in GB
	total = st.f_blocks * st.f_bsize / (1024.0**3) # free space in GB
	used = total - avail
	return (avail,used,total)
 
def send_email(to,subject,message):
 	fp_mail = subprocess.Popen(['/usr/bin/mail',to,'-s',subject], stdin=subprocess.PIPE).stdin
	fp_mail.write(message)
	fp_mail.close()
 
 
if len(sys.argv) != 4:
	print "Syntax: %s <email_address> <path> <min_space_GB>" % sys.argv[0]
	sys.exit(1)
 
(_,to,dir,min_space_GB) = sys.argv
min_space_GB = float(min_space_GB)
 
hostname = socket.gethostname()
 
(avail,used,total) = get_free_GB(dir)
 
pct = avail/total*100
 
if avail < min_space_GB:
	subject = "%s: Low disk space on %s" % (hostname, dir)
	message = """WARNING from '%s'.
 
Low disk space on $dir: %.1fGB / %.1fGB free (%.1f%%).  Threshold is %.1fGB.
""" % (hostname, avail, total, pct, min_space_GB)
	send_email(to,subject,message)

Then create /etc/cron.hourly/free-space-alerts with one line per mountpoint to monitor:

/root/free-space-alerts.py <YOUR_EMAIL_ADDRESS> <DIRECTORY> <MINIMUM_SPACE_IN_GIGABYTES>
...
email_alerts_on_low_free_space.txt · Last modified: 2017/05/28 15:34 by tkbletsc