Python for disk monitoring processing and alerting

Source: Internet
Author: User

#coding: Utf-8
Import threading
From datetime import datetime
Import time
Import OS
Import Smtplib
#from Email.mime.text Import Mimetext
From email. Mimetext Import Mimetext
#from email. Header Import Header
#from Log Import Logger
Import Logging,os,time,atexit,sys
From signal import SIGTERM
Import subprocess
Import Socket,fcntl,struct
def write_log (local_logs):
If not os.path.exists ("Disklogs"):
Try
Os.mkdir ("Disklogs")
Except
print ' Can not mkdir '
Cur_time = Time.strftime ("%y%m%d")
logs = "[" +time.strftime ("%y-%m-%d-%h-%m-%s") + "]:" +local_logs+ "\ n"
File = Open ("disklogs/" +cur_time+ ". txt", "a")
File.write (Logs)
File.close ()
Def disk_stat ():
HD = {}
Disk = Os.statvfs ("/data")
Free = (Disk.f_bavail * disk.f_frsize)
Total = (Disk.f_blocks * disk.f_frsize)
used = (disk.f_blocks-disk.f_bfree) * disk.f_frsize*1.024
Try
Percent = (float (used)/total) * 100
Except error:
# Get_log (). info (' calucate error ')
Pass
return percent
Def get_log ():
Logging.basicconfig (level=logging. DEBUG,
format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ',
Datefmt= '%a,%d%b%Y%h:%m:%s ',
Filename= ' Myapp.log ',
Filemode= ' W ')
Logger = Logging.getlogger (' root ')
return Logger
Def backup_time ():
now = Time.mktime (DateTime.Now (). Timetuple ()) -60*2
result = Time.strftime ('%y%m%d ', Time.localtime (now))
Backupresult = str (result)
Return Backupresult
def send_email (content):

sender = "[Email protected]"
receiver = ["[Email protected]"]
Host = ' smtp.163.com '
Port = 465
msg = Mimetext (content)
Msg[' from '] = "[Email protected]"
msg[' to ' = "[email protected]"
msg[' Subject ' = "harddisk check"

Try
SMTP = Smtplib. SMTP ()
Smtp.connect (' smtp.163.com:25 ')
# Smtp.ehlo ()
# SMTP.STARTTLS ()
# Smtp.ehlo ()

# SMTP = Smtplib. Smtp_ssl (host, Port)
Smtp.login (sender, ' aaaaaa ')
Smtp.sendmail (sender, receiver, msg.as_string ())
# Getlog (). info ("Send email success")
Except Exception, E:
# Get_log (). Error (E)
Pass
File.close ()
def get_ip (ifname):
s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)
Return Socket.inet_ntoa (Fcntl.ioctl (S.fileno (), 0x8915,struct.pack (' 256s ', ifname[:15])) [20:24])

def check ():
Percent = Disk_stat ()
Write_log (str (percent))
# Get_log (). info (percent)
ip = get_ip (' eth0 ')
if int (percent) > 70:
result = IP + "disusage:" + str (percent)
Write_log (Result)
Os.popen (' Find/data/back-mtime +0-exec rm-rf {} \; >/dev/null 2>&1 ')

elif int (percent) > 85:
result = IP + "disusage:" + str (percent) + "dangerous"
Write_log (Result)
Os.popen (' Rm-f/data/back/* ')
Else
result = "false"
return result
Def task ():
While True:
result = Check ()
if result = = "false":
Pass
Else
Try
Send_email (Result)
Except
Pass
# break
Time.sleep (1*60)
#def Run_monitor ():
# monitor = Threading. Thread (Target=task)
# Monitor.start ()
# def Createdaemon ():
# #脱离父进程
# try:
# PID = Os.fork ()
# if PID > 0:
# os._exit (0)
# except Oserror,error:
# print "Fork #1 failed:%d (%s)"% (Error.errno, error.strerror)
# os._exit (1)
# #修改当前的工作目录
# Os.chdir ('/')
# #脱离终端
# Os.setsid ()
# #重设文件创建权限
# os.umask (0)
# #第二次创建进程, disable process reopen terminal file
# try:
# PID = Os.fork ()
# if PID > 0:
# print ' Daemon pid%d '% pid
# os._exit (0)
# except Oserror,error:
# print "Fork #1 failed:%d (%s)"% (Error.errno, error.strerror)
# os._exit (1)
# Run_monitor ()
Class Daemon:
def __init__ (self,pidfile,homedir,stderr= '/dev/null ', stdout= '/dev/null ', stdin= '/dev/null '):
Self.stdin = stdin
Self.stdout = stdout
Self.stderr = stderr
Self.pidfile = Pidfile
Self.homedir = Homedir
def _daemonize (self):
Try
PID = Os.fork ()
If PID > 0:
Sys.exit (0)
Except Oserror,e:
Sys.stderr.write ("Fork #1 failed:%d (%s) \ n"% (E.errno,e.strerror))
Sys.exit (1)
Os.setsid ()
Os.chdir ('/')
Os.umask (0)
Try
PID = Os.fork ()
If PID > 0:
Sys.exit (0)
Except Oserror,e:
Sys.stderr.write ("Fork #1 failed:%d (%s) \ n"% (E.errno,e.strerror))
Sys.exit (1)
Sys.stdout.flush ()
Sys.stderr.flush ()
Si = File (Self.stdin, ' R ')
so = File (Self.stdout, ' A + ')
SE = File (self.stderr, ' A + ', 0)
Os.dup2 (Si.fileno (), Sys.stdin.fileno ())
Os.dup2 (So.fileno (), Sys.stdout.fileno ())
Os.dup2 (Se.fileno (), Sys.stderr.fileno ())
Atexit.register (Self.delpid)
PID = str (Os.getpid ())
File (self.pidfile, ' w+ '). Write ("%s\n"% pid)
def delpid (self):
Os.remove (Self.pidfile)
def start (self):
Try
PF = file (self.pidfile, ' R ')
PID = Int (Pf.read (). Strip ())
Pf.close ()
Except IOError:
PID = None
If PID:
Message = "Pidfile%s already exist. Daemon already running?\n "
Sys.stderr.write (Message)
Sys.exit (1)
Self._daemonize ()
Self._run ()
def stop (self):
Try
PF = file (self.pidfile, ' R ')
PID = Int (Pf.read (). Strip ())
Pf.close ()
Except IOError:
PID = None
If not PID:
message = "Pidfile% does not Exist,daemon not running?\n"
Sys.stderr.write (Message)
Return
Try
While 1:
Os.kill (Pid,sigterm)
Time.sleep (0.1)
Except Oserror,err:
Err = str (ERR)
If Err.find ("No such process") > 0:
If Os.path.exists (self.pidfile):
Os.remove (Self.pidfile)
Else
Print str (ERR)
Sys.exit (1)
def restart (self):
Self.stop ()
Self.start ()
def _run (self):
Pass
Class Mydaemon (Daemon):
def _run (self):
Task ()
def main ():
Homedir = OS.GETCWD ()
For I in (' Log ', ' Run '):
Path = Homedir + '/' + I
If not os.path.exists (path):
Os.makedirs (path,0755)
stdout = homedir + '/log ' + '/server.log '
stderr = homedir + '/log ' + '/server.err '
Pidfile = homedir + '/run ' + '/server.pid '
Daemon = Mydaemon (Pidfile,homedir,stdout=stdout,stderr=stderr)
If Len (sys.argv) = = 2:
If ' start ' = = Sys.argv[1]:
print ' Start daemon '
Daemon.start ()
Elif ' stop ' = = Sys.argv[1]:
print ' Stop daemon '
Daemon.stop ()
Elif ' restart ' = = Sys.argv[1]:
print ' Restart daemon '
Daemon.restart ()
Else
print ' Unknown command '
Sys.exit (2)
Sys.exit (0)
Else
Print "Usage:%s start|stop|restart"% sys.argv[0]
Sys.exit (2)
if __name__ = = "__main__":
Main ()
# if __name__ = = "__main__":
# Run_monitor ()




This article is from the "Automation Rolin" blog, so be sure to keep this source http://luoguoling.blog.51cto.com/1568501/1616619

Python for disk monitoring processing and alerting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.