def write_ping_result_to_file_short_version(event, ip): folder_to_save_ping_results = os.path.join(os.getcwd(), ip) if not os.path.exists( folder_to_save_ping_results): # if the path do not exist then os.makedirs(folder_to_save_ping_results) # create it now! file_name = "Year_" + str(time.localtime().tm_year) + "Month_"\ + str(time.localtime().tm_mon).rjust(2, '0') with open(os.path.join(folder_to_save_ping_results, "{}.txt".format(file_name)), mode="a") as f: if event: f.write("The address {} is not reachable! {} \n".format( ip, str(MyTime(MyTimeMode.full)))) else: f.write("The address {} is reachable again, {} \n".format( ip, str(MyTime(MyTimeMode.full))))
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
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
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()
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
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)