Process monitoring with Python and Telegram
Keeping Watch

© Photo by David Taffet on Unsplash
A simple Python script checks to see if a process is running and, if not, notifies the user via Telegram.
Reliability is a crucial aspect of a computer system, especially for servers. Because continuous active monitoring isn't feasible, implementing mechanisms to alert the system administrator in case of a malfunction can be very useful. This article explores how to develop a simple tool that monitors the status of a process and sends a Telegram message in the event of a crash.
Prerequisites
To follow the development of this project, you'll need an integrated development environment enabled for Python programming and some basic knowledge of the Python language. On Ubuntu, it is possible to download VS Code from the App Center by simply finding the VS Code page in the App Center and clicking the Install button. If you prefer to proceed with the installation via the command line, the VS Code documentation provides all the necessary details for completing the procedure on various distributions [1]. I recommend installing the Pylance, Python, and Python Debugger extensions to make development easier. Simply click on the extensions button (on the left side), select the extension, and proceed with the installation.
In addition, you will need a Telegram account and the Telegram messaging application [2] installed on a smartphone or PC. For Ubuntu users, the application is available on the Snapstore. From the command line, you can install it with apt using the command
sudo apt install telegram-desktop
See the box entitled "Why Telegram?" for more on why I chose it for this task.
Why Telegram?
The choice to use Telegram for notifications comes from considering the available options, each with its strengths and disadvantages. The desirable characteristics of a notification system include freedom from third-party constraints, especially when it comes to for-profit companies; ease of use and implementation; and flexibility, meaning the ability to send notifications to both smartphones and desktop environments. A simple system involves sending a text string to a listening port on a device using an application such as Ncat [3], which is also available on smartphones. However, mobile devices often have dynamic IP addresses, which is inconvenient for this kind of implementation. Additionally, receiving a string does not automatically notify the user. Finally, for security reasons, you should set up a firewall to accept connections only from trusted sources, increasing the complexity of this approach. The Slack [4] platform is effective and quite easy to use. However, Slack requires registration for its various usage plans, only one of which is free. Additionally, with a tool like Slack, I would face the risk of future changes in the company's plans regarding service pricing and feature availability.
Email is widely supported by all kinds of devices and is free from third-party interference. However, to send emails requires a complex initial setup to support various formats and the different security standards adopted by servers. Alternatively, I could install an SMTP server on my own PC. A good candidate is Postfix [5], which is relatively simple to configure, free, and open source. However, installing an SMTP server for sending notifications seems inappropriate and too resource-intensive. The best compromise is therefore provided by Telegram, an application managed by a private company but currently free. A scenario in which Telegram becomes a paid service seems unlikely. Its configuration for our purpose requires just two instructions and a few lines of Python code. Moreover, Telegram works on various platforms, including Android and iPhone smartphones, as well as desktop environments.
Setting up a Telegram Bot
The first step is to create a Telegram bot, which you can control using a Python script to send notifications. After launching Telegram, access the search function by clicking on the appropriate icon at the top of the main screen. Search for the string BotFather
and select the corresponding entry. Then type the following commands:
/start /new bot
BotFather will guide you through the process of creating a new bot, prompting you to choose a name and a username for your bot. You will receive a token that you can use to interact with the bot via a script. At this point, I need to retrieve the user ID of the person to whom I will send the messages. I can use the Get Chat ID bot for this purpose. Just click on the User button and select the desired contact from the list. Make a note of the token and the user ID, which you will need to specify as parameters when running the script from the console.
Developing the Script
The monitoring script will check whether a process is running at user-defined intervals. If the application is running, the script prints a log string on the screen; otherwise, a warning message is sent to a specified user on Telegram.
The first step is to handle the application arguments, which include the token provided by Telegram, the user ID, the name of the process to monitor, and the time interval expressed in minutes (Listing 1).
Listing 1
Arguments
01 import requests 02 import time 03 from datetime import datetime 04 import psutil 05 import argparse 06 07 try: 08 parser=argparse.ArgumentParser() 09 parser.add_argument("token", help="Token assigned by Telegram when creating your Bot", type=str) 10 parser.add_argument("user_id",help="User ID on Telegram", type=str) 11 parser.add_argument("process_name",help="Name of the process to check for",type=str) 12 parser.add_argument("interval",help="Minutes of interval between checks",type=int) 13 args=parser.parse_args()
The essential part of the script consists of a loop that repeats as long as the process under examination is running (Listing 2). The boolean variable found
is set to False
at the beginning of the iteration. Then the script retrieves the list of active processes. If the process specified by the args.process_name
parameter is present in this list, the script prints an informative note to the screen with the current date and time. It then sets the variable found
to True
. At the end of each iteration, if the process is not active, the script outputs an alert string then sends the same message to the user specified by the args_user_id
parameter using the Telegram REST API. The application is then closed. The main function is enclosed in a try-except
block, and in case of an error, an informative message is displayed (Figure 1).
Listing 2
The Loop
01 while True: 02 found=False 03 for process in psutil.process_iter(): 04 if(process.name()==args.process_name): 05 print(args.process_name +" up and running at " +str(datetime.now())) 06 found=True 07 08 if(found==False): 09 message = "Process " +args.process_name + " is currently down" 10 print(message) 11 url = f"https://api.telegram.org/bot{args.token}/sendMessage?chat_id={args.user_id}&text={message}" 12 requests.get(url).json() 13 quit() 14 15 time.sleep(args.interval * 60) 16 17 except Exception as e: 18 print(f"Error {type(e)}")
Practical Example
Launch the script from the terminal with the following syntax:
python crashinspector.py token:user_id process_name interval
where token
is the token provided by BotFather, user_ID
is the Telegram user ID provided by the Get Chat ID bot, process_name
is the name of the process you are monitoring, and interval
is the time interval for performing the checks (in minutes). For example, run the following command to check the status of the filezilla
process every 30 minutes:
python crashinspector.py 7237372881:AAEA-ZPF9WMRX5aNSa0PoJDCiUePoNqu0Uk 17130319 filezilla 30
Assuming that filezilla
is terminated after about two and a half hours, the output will be similar to Listing 3.
Listing 3
Output
filezilla up and running at 2024-07-21 16:49:13.559405 filezilla up and running at 2024-07-21 17:19:13.616971 filezilla up and running at 2024-07-21 17:49:13.621785 filezilla up and running at 2024-07-21 18:19:13.624988 filezilla up and running at 2024-07-21 18:49:13.628092 Process filezilla is currently down
Conclusion
When launched from the console, the script described in this article obtains the list of running processes and checks for an instance of the process. If an instance of the process is active, a string indicating the date and time of the check is printed. The cycle continues in the same manner for the specified time interval. If the process is not running during an iteration of the cycle, the application prints a warning on the console and sends an alert message via Telegram.
Infos
- Visual Studio Code on Linux: https://code.visualstudio.com/docs/setup/linux
- Telegram Messenger: https://telegram.org/
- Ncat: https://nmap.org/ncat/
- Slack: http://www.slack.com
- Postfix: http://www.postfix.org