## pip3 install irc## from irc import client, connection from time import time from socket import socket from configparser import ConfigParser from time import sleep from threading import Thread from os import chdir, path chdir(path.dirname(path.abspath(__file__))) config = ConfigParser() # Defaults config['Global'] = {'check_delay': '5 * 60', # every 5 min 'IRC_host': '127.1', 'IRC_port': '6667', 'IRC_bot_nickname': 'bot', 'IRC_admin_nickname': '', 'IRC_chat_name': '#main', 'attempts': '', 'attempts_delay': '', } config.read('monitor.conf') def on_connect(connection, event): connection.mode(config['Global']['IRC_bot_nickname'], '+B') connection.join(config['Global']['IRC_chat_name']) def on_join(connection, event): connection.privmsg(config['Global']['IRC_chat_name'], 'Bot started') def on_disconnect(connection, event): exit(1) def check_port(host, port): s = socket() s.settimeout(1) for _ in range(int(config['Global']['attempts'])): if not s.connect_ex((host, int(port))): return True sleep(int(config['Global']['attempts_delay'])) return False def check_service(host, services): for service_name, service_port in services.items(): result = check_port(host, service_port) if connection_states[host][service_name] != result: if result: irc.privmsg(config['Global']['IRC_chat_name'], '{} on {} is up' .format(service_name, host)) else: irc.privmsg(config['Global']['IRC_chat_name'], '{}:{} on {} is down!' .format(config['Global']['IRC_admin_nickname'], service_name, host)) connection_states[host][service_name] = result ## reactor = client.Reactor() irc = reactor.server() irc.connect(config['Global']['IRC_host'], int(config['Global']['IRC_port']), config['Global']['IRC_bot_nickname']) irc.add_global_handler("welcome", on_connect) irc.add_global_handler("join", on_join) irc.add_global_handler('disconnect', on_disconnect) Thread(target=reactor.process_forever).start() #start irc client in other thread ## hosts = config._sections check_delay = eval(config['Global']['check_delay']) last_check = 0 connection_states = {} for host, services in hosts.items(): connection_states[host] = {} for service in services: connection_states[host][service] = True try: while True: if time() - last_check >= check_delay: #print('Checking') for host, services in hosts.items(): if host == 'Global': continue Thread(target=check_service, args=(host, services)).start() last_check = time() reactor.process_once(timeout=1) except KeyboardInterrupt: irc.disconnect()