Checking the status of network devices with Python and sending messages to Telegram

I wanted to quickly get information about when the power goes out in my house. Having a server on the Vultr, it would be very wrong not to use it for this.

My router has 8+ hours of backup power and also one of the cameras is not backed up (powered by the outlet). I came up with the simplest state logic:

  1. If the router and camera are online, there are all powered!
  2. If the router is online, but the camera is not available, then the router is powered by a battery and there is no power by house input.
  3. If both devices are offline, this indicates that there is no Internet or the batteries are completely dead.

Let’s add logging to the program and sending messages to Telegram. The logging and sending of the message only occurs if the state has changed. The last state is also taken from the log for comparison.

import socket
import os
from datetime import datetime
import requests

logfile = 'log.csv' #log file name
TOKEN = "52135421591:YOUR-TELEGRAM_BOT_TOKEN_HERE17DMiXCsqs"
chat_id = "11111111". #chat id

def check(host,port,timeout=2):
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #presumably 
    sock.settimeout(timeout)
    try:
       sock.connect((host,port))
    except:
       return False
    else:
       sock.close()
       return True

def findLast():
    '''Finding last line in log file for checking and conparsion with last state'''
    with open(logfile, 'rb') as f:
        try:  # if file has one line 
            f.seek(-2, os.SEEK_END)
            while f.read(1) != b'\n':
                f.seek(-2, os.SEEK_CUR)
        except OSError:
            f.seek(0)
        last_line = f.readline().decode()
        f.close()
        line = last_line.split(",")
        lastn = ((line)[1].replace('"',''))
        last = lastn.replace('\n','')
    return last


def sendTg(message):
    '''Sending message in telegram chat'''
    url = f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chat_id}&text={message}"
    print(requests.get(url).json())


def main():
    '''Main function - cheking availability of devices by creating socket by port'''
    last = findLast()
    hap = check('evgdev.com',8080,timeout=1)
    cam = check('evgdev.com',2121,timeout=1)
    state = str(hap)+str(cam)
    print(last+state)
    if state != last:
        if state == 'FalseFalse':
            sendTg('NO INTERNET OR LOW BATTERY')
        if state == 'TrueFalse':
            sendTg('ON BATTERY')
        if state == 'TrueTrue':
            sendTg('HOME POWERED!')
        timenow = datetime.now()
        with open(logfile, 'a', encoding="utf-8") as file_object1:
            file_object1.write(f'"{timenow}","{state}"\n')
            file_object1.close()

main()

Then add this script to a cron scheduler with * * * * * for every minute running. Enjoy

See also  How to create tuple from Django model for choosing in form

This is a Python program that checks the availability of devices by creating sockets for specific ports. It uses the socket library to create sockets and connect to a server at a specified IP address and port. The os and datetime libraries are also used to read and write data to files, and to obtain the current time, respectively.

The program has a function named check() which takes an IP address and port number as arguments and returns True if a socket can be created and a connection can be established to that IP address and port, otherwise it returns False.

The findLast() function reads the last line of a log file and returns the state of the last check (which is a combination of two values for two devices).

See also  How to generate xlsx file from Django model

The sendTg() function sends a message to a Telegram chat using a bot token and a chat ID.

The main() function checks the availability of two devices at specific IP addresses and ports, and compares the current state with the last state. If the state has changed, it sends a message to a Telegram chat and logs the state and the time of the check in a CSV file. The main() function uses the findLast() function to get the last state before the current check.

 

Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *