Determine if the process exists
defisrunning (process_name):Try: Process= Len (Os.popen ('PS aux | grep "'+ Process_name +'" | Grep-v grep'). ReadLines ())ifProcess >= 1: returnTrueElse: returnFalseexcept: Print("Check process ERROR!!!") returnFalse
Start a process that is hung out
defstartprocess (process_script):Try: Result_code=Os.system (process_script)ifResult_code = =0:returnTrueElse: returnFalseexcept: Print("Process start Error!!!") returnFalse
Because the script layer is called, if you want to find exceptions, be sure to check the various logs .....
Crontab and shell commands are subject to inconsistent environment variables .....
Tripped over n times .... It's been tripped up again today ....
Example: implementation monitors a process and starts a process if the process is hung out.
And then send an e-mail notification ...
#!/bin/env Python3#-*-coding:utf-8-*- fromExchangelibImportDELEGATE, account, Credentials, Message, Mailbox, HTMLBodyImportSys, timeImportOSdeflog (logfile, content): F= Open (logfile,'a') F.write (Time.strftime ("\n%y-%m-%d%h:%m:%s") +content) F.flush () f.close ()defEmail (to, subject, body): Creds=Credentials (username=' xxxxxx', Password=' xxxxxx') Account=Account (primary_smtp_address=' xxxxxx', Credentials=creds, Autodiscover=True, Access_type=DELEGATE) M=Message ( account=Account , subject=subject, Body=HTMLBody (body), to_recipients= [Mailbox (email_address=To )] ) M.send ()defisrunning (process_name):Try: Process= Len (Os.popen ('PS aux | grep "'+ Process_name +'" | Grep-v grep'). ReadLines ())ifProcess >= 1: returnTrueElse: returnFalseexcept: Print("Check process ERROR!!!") returnFalsedefstartprocess (process_script):Try: Result_code=Os.system (process_script)ifResult_code = =0:returnTrueElse: returnFalseexcept: Print("Process start Error!!!") returnFalseif __name__=='__main__': Process_name="spark-streaming"Process_script="/bin/bash/home/admin/agent/spark/streaming_start.sh"subject="datacollect-1 spark-streaming ERROR"logfile="/home/admin/bin/logfile.log"content=""wrong_to="[email protected]"Sleep= 1content="There is%d arguments, they is%s"%(Len (SYS.ARGV), str (SYS.ARGV)) log (logfile, content)ifLen (sys.argv) = = 3: User= Sys.argv[1] to= Sys.argv[2] Log (logfile, content) time.sleep (sleep) isrunning=isrunning (process_name)ifIsRunning = =false:content="spark-streaming running ERROR \ n"log (logfile, content) Email (to, subject, content) Isstart=startprocess (Process_script) time.sleep (sleep)ifIsstart = =true:content+="spark-streaming start SUCCESS \ n"log (logfile, content) Email (to, subject+"&& start SUCCESS", content)Else: Log (logfile,"running ERROR")
Script Execution methods:
/usr/local/bin/python3/home/admin/bin/sparkstreamingemail.py [email protected] [email protected]
Not to be continued ...
Python3 determine if the process exists in the shell && start && Email notifications