Exemplo n.º 1
0
def show_ip_in_monitoring(ip_in_monitoring_dict: dict) -> None:
    if not len(ip_in_monitoring_dict) == 0:
        ip_list_in_db = database_op.extract_ips_from_ipsessions_table()
        for ip in ip_in_monitoring_dict.keys():
            address, interval, host = database_op.extract_parameters_of_ip_session_ipsessions_table(ip)
            print("{} {} {}".format(address, interval, host))
    else:
        print("There is no ip in monitoring now.\n")
Exemplo n.º 2
0
def import_ip_from_ip_file_list_menu(popen_list: dict,
                                     command: list) -> None:  #!!!!!!!!
    if len(command) == 1:
        ipexportlist = cli_menu.import_ip_from_file()
        if len(ipexportlist) > 0:
            for ip in ipexportlist:
                ip, interval, hostname = database_op.extract_parameters_of_ip_session_ipsessions_table(
                    ip)
                session = database_op.IpSession(ip, interval, hostname)
                cli_menu.add_ip_to_monitoring(session, popen_list)
        else:
            print(
                "No ips was extracted from database, nothing will be added to monitoring."
            )
    else:
        print("You should not put any words after import.")
        print("Print help and press Enter for more information.\n")
Exemplo n.º 3
0
def notificator(pingFailedLetterWasSent, negativePingsInRow,
                positivePingsInRow, email_sender_box, email_recepient_list,
                error_mail_message, recovery_mail_message,
                email_sender_password, smtp_settings, smtp_port, mode):

    ipaddress, interval, hostname = database_op.extract_parameters_of_ip_session_ipsessions_table(
        ip)
    if negativePingsInRow == 4 and not pingFailedLetterWasSent:
        pingFailedLetterWasSent = True
        sys.stderr.write("{} {} is not reachable.\n{}\n\n".format(
            ip, hostname, MyTime(MyTimeMode.full)))
        sys.stderr.flush()

        if mode == "short":
            ping_op.write_ping_result_to_file_short_version(
                pingFailedLetterWasSent, ip)

        negativeLetterThread = threading.Thread(
            target=mail_activity.send_negative_mail,
            args=("{}".format(ip), email_sender_box, email_recepient_list,
                  error_mail_message, email_sender_password, smtp_settings,
                  smtp_port),
        )
        negativeLetterThread.start()
        negativeLetterThread.join()

    if positivePingsInRow == 10 and pingFailedLetterWasSent:
        pingFailedLetterWasSent = False
        sys.stderr.write("{} {} is  reachable again now.\n{}\n\n".format(
            ip, hostname, MyTime(MyTimeMode.full)))
        sys.stderr.flush()

        if mode == "short":
            ping_op.write_ping_result_to_file_short_version(
                pingFailedLetterWasSent, ip)

        positiveLetterThread = threading.Thread(
            target=mail_activity.send_positive_mail,
            args=("{}".format(ip), email_sender_box, email_recepient_list,
                  recovery_mail_message, email_sender_password, smtp_settings,
                  smtp_port),
        )
        positiveLetterThread.start()
        positiveLetterThread.join()
    return pingFailedLetterWasSent
Exemplo n.º 4
0
def upload_smtp_settings():
    settings = []
    file_name = os.path.join(os.getcwd(), "settings", "settings.py")
    try:
        ipaddress, interval, hostname = database_op.extract_parameters_of_ip_session_ipsessions_table(
            ip)
        with open(file=file_name, mode="r") as f:
            for i in f:
                settings.append(i.strip("\\\n"))
    except FileNotFoundError:
        sys.stderr.write("Settings file does not exist or corrupted.\n\n")
        sys.stderr.write(
            "Delete the file if it exists and do setup command\n\n")
        sys.stderr.write("{} {} session crushed.\n{}\n\n".format(
            ip, hostname, MyTime(MyTimeMode.full)))
        sys.stderr.write("To restore session to the ip, add it again!\n")
        sys.stderr.flush()
        sys.exit()
    return settings
Exemplo n.º 5
0
def write_ping_result_to_file(pingresult, ip):
    '''Is used to write ping results to file, return path to the file'''
    ipaddress, interval, hostname = database_op.extract_parameters_of_ip_session_ipsessions_table(
        ip)
    currentDirectory = os.getcwd()
    folderToSavePingResultsUpper = ip
    folderToSavePingResultsMiddle = "Year_" + str(time.localtime().tm_year) + "Month_"\
                                    + str(time.localtime().tm_mon).rjust(2, '0')
    folderToSavePingResultsLower = ip + str(MyTime(MyTimeMode.short))
    folderToSavePingResults = os.path.join(currentDirectory,
                                           folderToSavePingResultsUpper,
                                           folderToSavePingResultsMiddle,
                                           folderToSavePingResultsLower)
    if not os.path.exists(
            folderToSavePingResults):  # if the path do not exist then
        os.makedirs(folderToSavePingResults)  # create it now!
    with open(os.path.join(
            folderToSavePingResults,
            "ping_{}_{}.txt".format(str(MyTime(MyTimeMode.middle)), ip)),
              mode="a") as f:
        try:
            if pingresult == (1, 0):
                f.write("The remote destination {} is reachable.{} \n".format(
                    ip, str(MyTime(MyTimeMode.full))))
            elif pingresult == (0, 1):
                f.write("Ping {} failed! {} \n".format(
                    ip, str(MyTime(MyTimeMode.full))))
            elif pingresult is None:  # it is so to allow first ping, see pingsubprocess.py file to understand
                pass
            else:
                raise PingResultError(pingresult)
        except PingResultError as ex:
            sys.stderr.write("{}\n\n".format(ex.ping_result_value))
            sys.stderr.write("{} {} session crushed.".format(ip, hostname))
            sys.stderr.flush()
            sys.exit()
    FilePath = os.path.join(
        folderToSavePingResults,
        "ping_{}_{}.txt".format(str(MyTime(MyTimeMode.middle)), ip))
    return FilePath
Exemplo n.º 6
0
def ping(ip, pinginterval=3):
    pinginterval = int(pinginterval)
    try:
        ipaddress, interval, hostname = database_op.extract_parameters_of_ip_session_ipsessions_table(
            ip)
        if sys.platform == 'win32':
            pingresult = os.system("ping -n 1 {}".format(ip))
            if pingresult == 0:
                time.sleep(pinginterval)
                pingresult = (1, 0)  # successfull attempt
                return pingresult
            elif pingresult == 1:
                pingresult = (0, 1)  # failed attempt
                return pingresult
            else:
                raise PingResultError(pingresult)
        elif sys.platform == 'linux':
            pingresult = os.system("ping -c 1 {}".format(ip))
            if pingresult == 0:
                time.sleep(pinginterval)
                pingresult = (1, 0)  # successfull attempt
                return pingresult
            elif pingresult == 256:
                pingresult = (0, 1)  # failed attempt
                return pingresult
            else:
                raise PingResultError(pingresult)
        else:

            sys.stderr.write(
                "The program is not designed to work in your OS {}".format(
                    sys.platform))
            sys.stderr.write("{} {} session crushed.".format(ip, hostname))
            sys.stderr.flush()
            sys.exit()
    except PingResultError as ex:
        sys.stderr.write("{}\n\n".format(ex.ping_result_value))
        sys.stderr.write("{} {} session crushed.".format(ip, hostname))
        sys.stderr.flush()
        sys.exit()
def send_positive_mail(ipAddress, email_sender, email_receiver, message_body,
                       email_sender_password, smtp_settings, smtp_port):
    '''The method sends positive mail if ip is reachable again'''
    ipAddress = str(ipAddress)
    ip, interval, hostname = database_op.extract_parameters_of_ip_session_ipsessions_table(
        ipAddress)
    subject = "{} {} recovery notification {}".format(
        ip, hostname, str(MyTime(MyTimeMode.full)))
    msg = MIMEMultipart()
    msg['From'] = email_sender
    msg['To'] = ", ".join(email_receiver)
    msg['Subject'] = subject
    msg.attach(
        MIMEText(
            message_body.format(ip, hostname, str(MyTime(MyTimeMode.full))),
            'plain'))
    text = msg.as_string()
    try:
        connection = smtplib.SMTP(
            smtp_settings,
            smtp_port)  # Attention! This should be settings of you smtp server
        connection.starttls()
        connection.login(email_sender, email_sender_password)
        # Attention! Put password of your mailbox to send mails about alarms from
        connection.sendmail(email_sender, email_receiver, text)
        connection.quit()
    except Exception as ex:
        with open(file="ErrorLog.txt", mode="a") as f:
            f.write(str(MyTime(MyTimeMode.full)))
            f.write(
                "Connection to SMTP server failed.\nLetter was not sent. Session with {}.\n"
                .format(ipAddress))
            sys.stderr.write(
                "Connection to SMTP server failed.\nLetter was not sent. Session with {}.\n\n"
                .format(ipAddress))
            f.write("{} is reachable again.\n".format(ipAddress))
            f.write("Error info: {} \n\n".format(ex))
            sys.stderr.flush()
Exemplo n.º 8
0
def main(ip, interval):
    ipaddress, interval_l, hostname = database_op.extract_parameters_of_ip_session_ipsessions_table(
        ip)
    error_mail_message = upload_error_notification_msg()
    recovery_mail_message = upload_recovery_notification_msg()
    if error_mail_message is None or recovery_mail_message is None:
        sys.stderr.write("{} {} session crushed.\n{}\n".format(
            ip, hostname, MyTime(MyTimeMode.full)))
        sys.stderr.flush()
        sys.exit()

    settings = upload_smtp_settings()

    email_recepient_list = upload_recipients_list()

    email_sender_box = settings[0]
    email_sender_password = settings[1]
    smtp_settings = settings[2]
    smtp_port = settings[3]
    log_mode = settings[4]

    pingFailedLetterWasSent = False
    positivePingsInRow = 0
    negativePingsInRow = 0
    if log_mode == "long":
        positivePingsThisHourCounterC = 0
        negativePingsThisHourCounterC = 0
        lastAttemptTime = MyTime()
        previousFilePath = ping_op.write_ping_result_to_file(ip=ip,
                                                             pingresult=None)
    while True:
        if not pingFailedLetterWasSent:
            pingResult = ping_op.ping(ip, interval)
        else:
            pingResult = ping_op.ping(ip, 2)
        if log_mode == "long":
            CurrentFilePath = ping_op.write_ping_result_to_file(pingResult, ip)
            currentTime = MyTime()

            if currentTime.compare_dates(lastAttemptTime):
                ping_op.write_ping_stats_to_file(
                    ip, positivePingsThisHourCounterC,
                    negativePingsThisHourCounterC, previousFilePath)
                previousFilePath = CurrentFilePath
                lastAttemptTime = currentTime
                positivePingsThisHourCounterC = 0
                negativePingsThisHourCounterC = 0

            positivePingsThisHourCounterC = positivePingsThisHourCounterC + pingResult[
                0]
            negativePingsThisHourCounterC = negativePingsThisHourCounterC + pingResult[
                1]

        if positivePingsInRow < positivePingsInRow + pingResult[0]:
            positivePingsInRow = positivePingsInRow + pingResult[0]
            negativePingsInRow = 0
        if negativePingsInRow < negativePingsInRow + pingResult[1]:
            positivePingsInRow = 0
            negativePingsInRow = negativePingsInRow + pingResult[1]

        pingFailedLetterWasSent = notificator(
            pingFailedLetterWasSent, negativePingsInRow, positivePingsInRow,
            email_sender_box, email_recepient_list, error_mail_message,
            recovery_mail_message, email_sender_password, smtp_settings,
            smtp_port, log_mode)