Javier Valcarce's Personal Website

Diskfree

From JavierValcarce.Eu

You are at: Home > Software > Diskfree
Jump to: navigation, search

Script Ruby que muestrea periódicamente la ocupación del disco en Linux y envía un email automático cuando esta supera el umbral elegido. Lógicamente, para enviar el email el ordenador deberá tener instalado un MTA (Mail Transfer Agent) y el programa mail estándar de UNIX. Si lo ejecutas de forma remota a través de SSH entonces tienes que ejecutarlo usando GNU screen para pasarlo a segundo plano y poder cerrar la conexión SSH sin matar el proceso.

Código fuente: diskfree.rb

#! /usr/bin/env ruby
 
maxusage = 95                 # Max disk usage in percentage
Tclk     = 10                 # Sample disk usage every Tclk seconds
part     = "/home"            # Partition to check
email    = "user@domain.com"  # Email for report to
 
host     = `hostname -f`
subject  = host + " " + "DISK USAGE > " + maxusage.to_s + "%" 
 
#-------------------------------------------------------------------------------
sample1 = 0
sample2 = 0
 
while true
 
  dfout = `df -h`
 
  index = dfout.split.index(part)
  usage = dfout.split[index-1]
 
  puts Time.now.to_s + ": disk usage on partition " + part + " is " + usage
 
  # Egde detector algorithm
  sample2 = sample1 
  if usage.to_i > maxusage
    sample1 = 1
  else
    sample1 = 0
  end
 
  # positive edge, notify warning by email
  if (sample1 == 1) and (sample2 == 0)
 
    puts "Notify warning by email to #{email}"
    text = "\"Disk full.\\n\\n" + dfout + "\""
    system("echo -e #{text} | mail #{"\"" + email + "\""} -s #{"\"" + subject + "\""}")
  end
 
  sleep Tclk
end