• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Automate Website Monitoring with Python and Crontab on Linux

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

Is your website or online service always available?
Downtime can lead to lost revenue, frustrated users, and damage to your brand’s reputation. Instead of manually checking your site’s status, why not automate the process using Python and Cron?

In this article, you’ll learn how to build a simple monitoring script that checks a website’s availability every minute, logs the result, and lets you watch everything in real time with tail -f.

Step 1: Create the Python Monitoring Script

To begin, we need a Python script that uses curl to check if Google.com is reachable and logs the result with a timestamp. Open your terminal and create a new Python file using your preferred text editor.

This script does the following:


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


Then, paste the following Python code into the file


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Sends a simple HTTP request to

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

using curl.
Captures the response and determines whether the request was successful.
Logs the result (either SUCCES, FAILURE, or an error message) along with the current date and time to a log file located in your home directory.
Before automating the script, it’s important to test that it works as expected. Open your terminal and run the Python script manually using the following command:


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



This command executes the script and attempts to reach

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

using curl . The result of this operation, along with a timestamp, is logged in a file named google_monitor.log located in your home directory.

This confirms that the script ran successfully and recorded the result. If the status is FAILURE or ERROR, double-check your internet connection or the script's permissions.

Once everything works as intended, you’re ready to move on to automating the script with cron.

Step 3: Automate the Script with Crontab

Now that your script is working correctly, the next step is to schedule it to run automatically every minute using curl, the time-based job scheduler on Unix-like systems.

To edit your personal crontab file, run the following command in terminal:


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Step 4: Monitor Log Output in Real Time

Once your script is scheduled to run every minute, you might want to verify that it’s actually working and see the results as they come in. You can do this using the tail command, which displays the most recent lines of a file and updates in real time.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



This command will show you the last lines of the google_monitor.log file and continuously update the output as new entries are added every minute by your cron job. This real-time feedback is especially useful for monitoring uptime or debugging automation issues. If you stop seeing new lines appear every minute, it might mean your cron job isn’t running or there’s an error in the script.

By combining Python, curl, and cron, you’ve created a simple yet powerful monitoring system that checks website availability every minute and logs the results automatically. This lightweight solution is ideal for developers, system administrators, or anyone who wants to keep track of uptime without relying on third-party services.

With just a few lines of code and built-in Linux tools, you’ve taken the first step toward proactive system monitoring a crucial practice for maintaining reliability and performance over time.

Now that you’ve mastered the basics, you can expand this script to monitor other services, send email alerts, or track performance metrics. Automation is no longer optional it’s essential.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу