SIGN IN / UP
    opened image

    There are many software solutions for monitoring servers or network devices, many of which require server resources to deploy and configuration knowledge. But if you have one or more servers or a router with a white* IP, then there is no need to deploy a complex monitoring structure just to check if the server or router is reachable. It is enough to create a simple telegram bot that will send you a telegram notification if the checked IP is not available (down) and when it is available again (up). The bot itself will work 24/7 on a virtual server running the Linux operating system, with a minimum load on resources.
    * white IP address is a unique IP address assigned to a device or server and is accessible from the Internet. This IP is public.

    What needs to be done:
    1. In Telegram, create a bot and a private channel to add the bot to. You can invite to the channel those who can also watch the monitoring
    2. Install on the python3 server. In this article, we will look at hosting a bot on a virtual server with Ubuntu 20.04 OS (can be hosted on any OS where the python3 package can be installed)
    3. Create a script file, write the IP hosts (servers or routers) in it, set the monitoring period and run it from the crypts in 24/7 mode.

    Let's get started.

    1. To register a new telegram bot, you need to find the @BotFather bot service in the Telegram application and send it a command to register a new bot
    /newbot



    Next, @BotFather will request a name for our bot. There are no restrictions in the name, we will enter, for example:
    IP monitoring



    Now you need to enter a unique bot name in the Telegram system. Bot name must end with _bot. Let's call, for example
    ip_monitoring_super_bot



    After that, @BotFather will provide us with a TOKEN with which we can control the bot. TOKEN needs to be saved as we will need it later.



    Telegram bot registered.

    Now let's create a private channel to which our new bot named @ip_monitoring_super_bot will send messages.

    To do this, in the chat window of the Telegram program, click on the icon for creating a new message and select New chanel - Create chanel - come up with a name for the channel (for example, IP monitoring chanel) - select the Private channel type and add the @ip_monitoring_super_bot bot.





    As a result, we get a private channel to which the @ip_monitoring_super_bot bot will send messages about the status of the equipment we are monitoring. You can also invite any telegram user to this channel using a special link.
    You should pay attention and check in the properties of the IP monitoring chanel if the @ip_monitoring_super_bot bot is added as a channel administrator. To go to the channel properties, just click on the channel name.




    We also need the chat_id value. For this you need:
      - go to the bot chat @ip_monitoring_super_bot and send a message /start (this will start the bot to work)
      - make a test message (any) in the IP monitoring channel
      - follow the link in the browser https://api.telegram.org/botTOKEN/getUpdates
    In our example, the link will look like this:
    https://api.telegram.org/bot5921115541:AAHltzyZpC_MBZzydhrOD_Brn8lnKNf7XXX/getUpdates
    The result on the screen will look like this:


    So, let's remember 2 important values for managing the bot:
    token= 5921115541:AAHltzyZpC_MBZzydhrOD_Brn8lnKNf7XXX
    chat_id = -100185915XXX

    2. Connect to the server via SSH (how to do it)

    Check if python3 is installed:
    python3 --version

    If python3 is not installed (error: -bash: python3: command not found), you must install with the command
    - for Ubuntu:
    apt install python3 -y
    - for CentOS
    yum install python3 -y
    Additionally, install the requests module:
    pip3 install requests

    After installation, you can check the version again. It might be something like this:



    More details about installing python3: How to Install Python 3.10 on Ubuntu 20.04

    3. Let's create a folder where the monitoring script will be placed. To do this, run the command:
    cd && mkdir pingmonitor && cd pingmonitor

    Create and open a file
    vim main.py

    and place the script in it:

    #----------------------------------------------------
    import os
    import requests
    import time
    #-------------------------
    hostname = ['8.8.8.8','1.1.1.1']
    time_pause = 30
    #-------------------------
    def SendMsgToTelegramChanel(msg):
        token="TOKEN"
        chat_id = 'CHAT_ID'
        params = {'chat_id': chat_id,'text': msg}
        response = requests.get('https://api.telegram.org/bot'+token+'/sendMessage', params=params)
    def IsHostAlive(host):
        ret = os.system('ping -c 2 {} > /dev/null'.format(host))
        if ret == 0:
            return True
        return False
    while True:
        for i in range(len(hostname)):
            file_signal = hostname[i] +'_down'
            if IsHostAlive(hostname[i]):
                if os.path.isfile(file_signal):
                   os.remove(file_signal)
                   SendMsgToTelegramChanel(hostname[i] + ' is up')
                   #print(hostname + ' is up!')
            else:
                if not os.path.isfile(file_signal):
                    open(file_signal,'tw').close()
                    SendMsgToTelegramChanel(hostname[i] + ' is down')
                    #print(hostname + ' is down!')
        time.sleep(time_pause)
    #------------------------------------------------

    - in the script, replace TOKEN and CHAT_ID with the previously saved token and chat_id values.
    - in the line hostname = ['8.8.8.8','1.1.1.1'], instead of IP 8.8.8.8 and 1.1.1.1, specify the IP (or hostname) of your server or router that you want to monitor*. IP addresses of devices should be specified in single quotes and separated by commas (if there is more than one IP)
    - the value of the variable time_pause = 30, indicates the check period (in seconds). It is not recommended to set it to less than 10-15 seconds, especially if the list of checked IPs is large.
    - do not remove line indents in the script. This may result in a syntax error.

    (*) the script uses the method of checking by sending icmp packets (ping), for this reason, you should make sure that ping requests are not blocked on the server or router (which is being monitored).

    Now everything is ready to run the script.
    Since the script must run 24/7 so that its work is not displayed on the main console screen, we will run it in a separate "window" using the screen utility (if not installed, install it. More details: Basics of working with the screen utility).
    To do this, run the command:
    screen -S pingmonitor

    and go to the folder with the script file:
    cd && cd pingmonitor

    Let's run the script with the command:
    python3 main.py

    To exit the session and leave our script running, press Ctrl+a+d. Now the SSH console can be closed.
    To connect to a session with a running script, connect to the server via SSH and run the command:
    screen -r pingmonitor

    In case the server or router becomes unavailable and after it becomes available, you will receive a message in the channel IP monitoring chanel.