Home Backend Development Python Tutorial Technology to monitor website availability based on Python script in Linux environment

Technology to monitor website availability based on Python script in Linux environment

Oct 05, 2023 am 10:29 AM
website monitor Availability

Technology to monitor website availability based on Python script in Linux environment

Technology for monitoring website availability based on Python scripts in Linux environment

Abstract: This article introduces how to use Python scripts to monitor website availability in a Linux environment. Specifically, it includes detecting whether the website is accessible by sending HTTP requests and parsing responses, and how to configure the monitoring script as a scheduled task and send alarm emails.

  1. Introduction
    With the development of the Internet, website availability has become a crucial indicator. If the website cannot be accessed normally, it will cause huge inconvenience to users and even affect the company's brand image and business operations. Therefore, it is very important to monitor the availability of the website in a timely manner.
  2. Preparation
    In order to use Python to monitor website availability, we first need to install the Python environment. On Linux, you can install Python through the package manager. For example, on Debian/Ubuntu you can use the following command to install:

    $ sudo apt-get install python
    Copy after login
  3. Script to monitor website availability
    One is given below Simple Python script for monitoring website availability. The script sends an HTTP request and checks the response status code. If the status code is 200, it means the website is accessible; otherwise, it means the website is not accessible.
import requests

def check_website(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print(f"Website {url} is accessible.")
        else:
            print(f"Website {url} is not accessible. Status code: {response.status_code}")
    except Exception as e:
        print(f"An error occurred while accessing website {url}:", str(e))

def main():
    websites = [
        "http://www.example1.com",
        "http://www.example2.com",
        "http://www.example3.com"
    ]
    for website in websites:
        check_website(website)

if __name__ == "__main__":
    main()
Copy after login

In the above code, we first send an HTTP GET request through requests.get(url) and get the response. Then, we can get the response status code through response.status_code and make a judgment.

  1. Configuring scheduled tasks
    In order to monitor website availability regularly, we can configure the above script as a scheduled task. The Linux system provides the cron tool, which can help us implement the function of scheduled tasks.

You can use the following command to edit the crontab file:

$ crontab -e
Copy after login

Then, add the following content in the file:

*/5 * * * * python /path/to/monitor_script.py >> /path/to/log_file.txt 2>&1
Copy after login

The above configuration Indicates that the Python script will be executed every 5 minutes and the output will be redirected to the log file.

  1. Send alarm email
    In order to be notified of changes in website availability in a timely manner, we can modify the script to send an alarm email when the website is inaccessible.

First, we need to configure the relevant information of the SMTP server, such as server address, port number, user name and password, etc. Then, we can use the smtplib library to implement the email sending function.

The following is a modified code example:

import requests
import smtplib
from email.mime.text import MIMEText

def check_website(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print(f"Website {url} is accessible.")
        else:
            send_alert_email(url, response.status_code)
    except Exception as e:
        print(f"An error occurred while accessing website {url}:", str(e))

def send_alert_email(url, status_code):
    smtp_server = "smtp.example.com"
    smtp_port = 25
    smtp_username = "your_username"
    smtp_password = "your_password"
    sender = "sender@example.com"
    receiver = "receiver@example.com"
    subject = f"Website {url} is not accessible!"
    message = f"Status code: {status_code}"
    
    msg = MIMEText(message)
    msg["Subject"] = subject
    msg["From"] = sender
    msg["To"] = receiver
    
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.login(smtp_username, smtp_password)
        server.sendmail(sender, receiver, msg.as_string())
        
def main():
    websites = [
        "http://www.example1.com",
        "http://www.example2.com",
        "http://www.example3.com"
    ]
    for website in websites:
        check_website(website)

if __name__ == "__main__":
    main()
Copy after login

In the above code, we first define the SMTP server information, sender and recipient required to send mail. Then, we use smtplib.SMTP to log in to the SMTP server and send emails.

Summary: This article introduces how to use Python scripts to monitor website availability in a Linux environment. By sending an HTTP request and parsing the response, we are able to determine whether the website is accessible. At the same time, we also introduced how to configure the monitoring script as a scheduled task and send an alarm email when the website is inaccessible. These methods can help you understand and solve website usability problems in a timely manner, and improve user experience and business operation results.

The above is the detailed content of Technology to monitor website availability based on Python script in Linux environment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is there any website for learning C language? Is there any website for learning C language? Jan 30, 2024 pm 02:38 PM

Websites for learning C language: 1. C Language Chinese Website; 2. Rookie Tutorial; 3. C Language Forum; 4. C Language Empire; 5. Script House; 6. Tianji.com; 7. Red and Black Alliance; 8, 51 Self-study network; 9. Likou; 10. C Programming. Detailed introduction: 1. C language Chinese website, which is a website dedicated to providing C language learning materials for beginners. It is rich in content, including basic grammar, pointers, arrays, functions, structures and other modules; 2. Rookie tutorials, This is a comprehensive programming learning website and more.

How to open a website using Task Scheduler How to open a website using Task Scheduler Oct 02, 2023 pm 11:13 PM

Do you frequently visit the same website at about the same time every day? This can lead to spending a lot of time with multiple browser tabs open and cluttering the browser while performing daily tasks. Well, how about opening it without having to launch the browser manually? It's very simple and doesn't require you to download any third-party apps, as shown below. How do I set up Task Scheduler to open a website? Press the key, type Task Scheduler in the search box, and then click Open. Windows On the right sidebar, click on the Create Basic Task option. In the Name field, enter the name of the website you want to open and click Next. Next, under Triggers, click Time Frequency and click Next. Select how long you want the event to repeat and click Next. Select enable

How to convert your website into a standalone Mac app How to convert your website into a standalone Mac app Oct 12, 2023 pm 11:17 PM

In macOS Sonoma and Safari 17, you can turn websites into "web apps," which can sit in your Mac's dock and be accessed like any other app without opening a browser. Read on to learn how it works. Thanks to a new option in Apple's Safari browser, it's now possible to turn any website on the internet you frequently visit into a standalone "web app" that lives in your Mac's dock and is ready for you to access at any time. The web app works with Mission Control and Stage Manager like any app, and can also be opened via Launchpad or SpotlightSearch. How to turn any website into

C# Development Advice: Logging and Monitoring Systems C# Development Advice: Logging and Monitoring Systems Nov 22, 2023 pm 08:30 PM

C# Development Suggestions: Logging and Monitoring System Summary: In the software development process, logging and monitoring systems are crucial tools. This article will introduce the role and implementation suggestions of logging and monitoring systems in C# development. Introduction: Logging and monitoring are essential tools in large-scale software development projects. They can help us understand the running status of the program in real time and quickly discover and solve problems. This article will discuss how to use logging and monitoring systems in C# development to improve software quality and development efficiency. The role of logging system

Laravel monitoring errors: improve application stability Laravel monitoring errors: improve application stability Mar 06, 2024 pm 04:48 PM

Monitoring errors in Laravel is an important part of improving application stability. During the development process, various errors will inevitably be encountered, and how to detect and resolve these errors in a timely manner is one of the keys to ensuring the normal operation of the application. Laravel provides a wealth of tools and functions to help developers monitor and handle errors. This article will introduce some of the important methods and attach specific code examples. 1. Use logging Logging is one of the important means of monitoring errors. Laravel has a powerful logging system built-in, developers

How to use Docker for container monitoring and performance analysis How to use Docker for container monitoring and performance analysis Nov 08, 2023 am 09:54 AM

Overview of how to use Docker for container monitoring and performance analysis: Docker is a popular containerization platform that allows applications to run in independent containers by isolating applications and their dependent software packages. However, as the number of containers increases, container monitoring and performance analysis become increasingly important. In this article, we will introduce how to use Docker for container monitoring and performance analysis, and provide some specific code examples. Use Docker’s own container monitoring tool Docker provides

Will Sunflower Remote Control be monitored? Will Sunflower Remote Control reveal privacy? Will Sunflower Remote Control be monitored? Will Sunflower Remote Control reveal privacy? Mar 15, 2024 pm 05:28 PM

Will Sunflower remote control be monitored? Sunflower remote control software can help users quickly retrieve information from another computer, etc. However, there are also many users who are worried about the security of their own computers. Let the editor answer these questions for users. Question. Will Sunflower Remote Control be monitored? Answer: No. Although Sunflower Remote Control has the ability to do this, large software companies like Sunflower Remote Control that have been established for many years will not do such a thing. For office workers, perhaps a piece of software that must be installed on the computer is remote control. For many people, whether they are working from home or because they are unable to leave, operating the current computer from a distance through another computer can save a lot of time.

Golang development: Use Prometheus to monitor application performance Golang development: Use Prometheus to monitor application performance Sep 21, 2023 pm 12:39 PM

Golang development: Using Prometheus to monitor application performance requires specific code examples. Summary: This article introduces how to use the Prometheus library in Golang development to monitor application performance, and provides specific code examples to facilitate developers to get started quickly. Introduction: In modern application development, monitoring application performance is a very important step. Through monitoring, we can understand the running status of the application in real time, discover problems in time and make adjustments, thereby improving the stability and performance of the application. Pro

See all articles