Python automation script to monitor web website to send email reminders and restart the server
This article mainly explains "python automation script to monitor web sites to send email alerts and restart the server", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "python automation script to monitor web sites, send email alerts and restart servers"!
The idea goes like this: we use requests to request a web address to monitor, and depending on the status value returned is not 200 or something unusual, we send an email and restart the server. Next, look at the code section (this code script uses a web service running on a linux server as an example):
#!/ usr/bin/env pythonimport osimport smtplibimport requests
#Email account password EMAIL_ADDRESS = os.environ.get ('EMAIL_USER')EMAIL_PASSWORD = os.environ.get ('EMAIL_PASS')#Get recipient's email address EMAIL_RECEVIER = os.environ.get ('EMAIL_RECEVIER')#Define alert user to send email def notify_user(): with smtplib.SMTP('smtp.qq.com', 25) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
subject = 'Your site crashed! ' body = 'Make sure the server has been restarted to completion. ' msg = f'Subject: {subject}\n\n{body}' smtp.sendmail(EMAIL_ADDRESS, EMAIL_RECEVIER, msg)
#define the method def reboot_server(): #Restart Linux web server directly os.system("reboot")
try: #For example, monitor a URL here: World in the game r = requests.get('https://www.liuluanyi.cn', timeout=5) if r.status_code != 200: notify_user() reboot_server() else: # opexcept Exception as e: notify_user() reboot_server()
We save the script as py3_monitor.py, place it on the web server and give it executable permissions:
chmod u+x py3_monitor.py
We create a timed task to execute this script every 5 minutes by typing crontab -e
*/5 * * * * ./ path/to/py3_monitor.py
At this point a simple automated monitoring script is complete, which we'll see in the next section.
At this point, I believe that everyone has a deeper understanding of "python automation script to monitor web sites to send email alerts and restart servers", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!