Guest User

Untitled

a guest
Feb 21st, 2018
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.68 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import os, smtplib
  4. from sys import exit
  5. from time import sleep, gmtime, strftime
  6.  
  7. ########## Configuration here ##############
  8. processname = 'init'
  9. checkseconds = 5
  10. maxalerts = 2
  11. sender = 'notify@domain.com'
  12. receivers = ['myemail@mymail.com']
  13. emailpassword = 'myemailpass'
  14. smtpserver = 'smtp.server.net'
  15. logfilename = 'monitor.log'
  16. ########## End configuration ###########
  17.  
  18. message = ("From: Monitor <%s>\r\nTo: Warning <%s>\r\nSubject: e-mail Alert Monitor\r\nProcess is down!" % (sender, ", ".join(receivers)))
  19. fail = 0
  20.  
  21. #Crazy logger
  22.  
  23. def writelog (message):
  24.  
  25. global logfile
  26.  
  27. try:
  28. # This tries to open an existing file but creates a new file if necessary.
  29. logfile = open(logfilename, "a")
  30. try:
  31. logfile.write(message)
  32. finally:
  33. logfile.close()
  34. except IOError:
  35. pass
  36.  
  37.  
  38.  
  39. # Notifying via Email
  40. def advice():
  41.  
  42. try:
  43. smtpObj = smtplib.SMTP(smtpserver, 25)
  44. smtpObj.login (sender,emailpassword)
  45. smtpObj.sendmail(sender, receivers, message)
  46. writelog ("%s Successfully sent email\n" % (strftime("%d %b %Y %H:%M:%S", gmtime())))
  47. smtpObj.quit()
  48. except SMTPException:
  49. writelog ("%s Error: unable to send email\n" % (strftime("%d %b %Y %H:%M:%S", gmtime())))
  50. # print ("exiting...")
  51. # exit (1)
  52.  
  53. # Vicente trick of the hell
  54. def monitor():
  55. global fail
  56. tmp = os.popen("ps -Af").read()
  57. proccount = tmp.count(processname)
  58. if proccount < 1:
  59. fail = fail + 1
  60. writelog ('%s %s **STOPPED** (alert %d)\n' % (strftime("%d %b %Y %H:%M:%S", gmtime()), processname, fail))
  61. if fail == maxalerts:
  62. advice()
  63. else:
  64. fail = 0
  65. sleep(checkseconds)
  66.  
  67.  
  68. def main():
  69.  
  70. while 1:
  71. monitor()
  72.  
  73. # Dual fork hack to make process run as a daemon thanks to Active Programmer Network
  74. if __name__ == "__main__":
  75. try:
  76. pid = os.fork()
  77. if pid > 0:
  78. exit(0)
  79. except OSError, e:
  80. exit(1)
  81.  
  82. os.chdir("/tmp")
  83. os.setsid()
  84. os.umask(0)
  85.  
  86. try:
  87. pid = os.fork()
  88. if pid > 0:
  89. exit(0)
  90. except OSError, e:
  91. exit(1)
  92.  
  93. main()
Add Comment
Please, Sign In to add comment