def Generator(filereports): COLUMN_NAMES = ['AppName', 'TCID', 'STATUS', 'EXEDATE', 'PASSED'] temp = pd.DataFrame(columns=COLUMN_NAMES) temp1 = pd.DataFrame(columns=COLUMN_NAMES) count = 0 for i in filereports: data1 = pd.read_csv(i) passc = data1.STATUS == "Pass" if (count == 0): tempf = data1[passc] temp['AppName'] = tempf['AppName'] temp['TCID'] = tempf['TCID'] temp['STATUS'] = tempf['STATUS'] temp['EXEDATE'] = tempf['EXEDATE'] temp['PASSED'] = 2.0 count = 1 else: temp1['AppName'] = data1[passc]['AppName'] temp1['TCID'] = data1[passc]['TCID'] temp1['STATUS'] = data1[passc]['STATUS'] temp1['EXEDATE'] = data1[passc]['EXEDATE'] temp1['PASSED'] = data1[passc][data1.columns[-1]] temp = pd.concat([temp, temp1]) temp = temp.dropna() temp.to_csv("pass_data.csv", index=False) zi.zip() mail.sender() su.suggester("pass_data.csv")
def doSGT(args): global info stage = args[0] stages = ["preCVM", "vMeshGen", "vMeshMerge", "sgtGenXY", "sgtMergeXY"] subject = "Status - Run %d (%s) %s Workflow" % \ (info.run_id, info.site, info.workflow) msg = "Workflow is currently on this stage:\r\n\r\n" if (not stage in stages): print "Stage " + stage + " not found" return 1 numstage = len(stages) istage = stages.index(stage) for i in range(0, numstage): if (i <= istage): msg = msg + stages[i] + ": Complete\r\n" else: msg = msg + stages[i] + ": Scheduled\r\n" # Send the email m = Mailer() m.send(info.notify_to, subject, msg) return 0
def main(): """ This is the main function. This performs the data gathering and sends the emails using the Wireless.py, SchoolCore.py and Mailer.py modules """ # Core runtime is used to time the work performed by the health audit functions. core_run_time = datetime.now() core_message = '' weekno = datetime.today().weekday() if weekno == 0: rawdate = datetime.today() - timedelta(hours=72) searchstartdate = rawdate.strftime("%m/%d/%Y") elif weekno >= 5: exit(0) else: rawdate = datetime.today() - timedelta(hours=24) searchstartdate = rawdate.strftime("%m/%d/%Y") print('Run 9900 Health Scan') health_9900 = SchoolCore.health_audit_9900(schoolcores_9900) if health_9900: core_message += health_9900 print('Run 9900 loop Scan') switch_loops = SchoolCore.loop_finder_9900(schoolcores_9900, searchstartdate) if switch_loops: core_message += switch_loops print('Run 9900 WAN Health Scan') wanhealth = SchoolCore.wan_health_9900(schoolcores_9900, searchstartdate) if wanhealth: core_message += wanhealth print('Run 9900 blade Scan') bladehealth = SchoolCore.blade_audit_9900(schoolcores_9900, searchstartdate) if bladehealth: core_message += bladehealth # Append text to the core message which is used in the email. core_message += '\n\n' + 'Please create a ticket for any anomalies discovered\n\n' core_message += 'VISION STATEMENT: Our vision is to provide the highest' \ ' network availability through top tier expert support and fast resolutions.' final_core_run_time = datetime.now() total_core_run_time = final_core_run_time - core_run_time core_message += '\n\n\nThis took {time} to run'.format( time=total_core_run_time) # AP runtime is used to time the work performed by the AP scan functions. ap_run_time = datetime.now() print('run ap scan') ap_message = Wireless.ap_status(wireless_controllers, username, password) # Append text to the AP message which is used as the body in the email. ap_message += 'Please create a ticket for any anomalies discovered\n\n' ap_message += 'VISION STATEMENT: Our vision is to provide the' \ ' highest network availability through top tier expert' \ ' support and fast resolutions.' final_ap_run_time = datetime.now() total_ap_run_time = final_ap_run_time - ap_run_time ap_message += '\n\n\nThis took {time} to run'.format( time=total_ap_run_time) # Send all mail Mailer.send_apstatus_mail(email_target, ap_message) Mailer.send_9900_mail(email_target, core_message)
def request_password_change(self): self.restore_id = str(uuid4()) self.restore_valid = datetime.now() + timedelta(days=1) Mailer.send_password_restore(self) db.session.add(self) db.session.commit()
def shutdown_handler(signum, frame): # is there enough time to save the script state, do we even have to? print ("Script terminating with signal %d" % signum) if config.mailTo: Mailer.sendEmail(config.mailTo, "Script was terminated with signal %d" % signum, "Ingester Error") # we might also have to remove the last object as it may be corrupt # need to look into how an interrupt can interfere with shutil.copy, os.chown, and ffmpeg sys.exit(1)
def main(): print "-- Starting up at %s --" % (time.strftime("%Y-%m-%d %H:%M:%S")) rm = RunManager(readonly=False) rm.useHTML(False) m = Mailer() # Look for workflow execution errors checkExecErrors(rm, m) # Checks to perform only on the master RunManager host if (info.master == True): # Perform verification checks on completed runs checkVerifyErrors(rm, m) # Generate new maps if needed if (info.update_maps == True): if (createMaps() != 0): print "Warning: Failed to produce maps." # Generate comparison curves if needed createCompCurves(rm, m) print "-- Shutting down at %s --" % (time.strftime("%Y-%m-%d %H:%M:%S")) return 0
def Run(self, tasks, logfile, mailto, dbweb, dbname): for task in tasks: task.append(re.compile(task[0])) # magic table name here... tablename = "mailbox" setting = {} setting['senderip'] = socket.gethostbyname(socket.gethostname()) setting['mailto'] = mailto tools = {} self.tools = tools self.last_flush_time = time.time() tools['setting'] = setting tools['mailer'] = Mailer.Mailer(mailto) tools['mysql'] = HttpMysql.HttpMysql(dbweb, dbname) tools['warn_box'] = MailboxClient.MailboxClient( dbweb, dbname, tablename) child = Popen(["tail", "--follow=name", "--retry", logfile], stdout=PIPE, close_fds=True, bufsize=1024) while 1: self.check_flush_mails() line = child.stdout.readline() if not line: break try: self.on_each_line(line.strip(), tasks, tools) except Exception, e: msg = "[WARN]:log-monitor cannot handle msg:[%s],with error %s" % ( line, e) tools['mailer'].CacheSendMail( msg, "[DSTREAM]log-monitor meet an error", "my_cache_key")
def scenario_phishing_simulation(): # This scenario shows how to run a phishing simulation, like commonly applied in course of security awareness # campaigns. # It starts again with defining sender and server information. In this scenario actual and apparent sender match. server_info = ServerInfo.ServerInfo() from_addr = server_info.username from_name = "Basil Sattler" # Using the specified server information we create a session mailer = Mailer.Mailer(server_info) mailer.connect_to_server() mailer.login_to_server() # We load the target adresses from the file stored in the data directory. Please note that the file should have # the format it has in the example file adress_manager = AddressManager.AdressManager("../data/examples.xls") # We instantiate an object of the MailCreator class mail_creator = MailCreator.MailCreator(from_name, from_addr) # Typically phishing mails point to some external resources where the actual phishing happens. Such a link can be # embedded into the mail while creation. This can be used, for example, to track whether the recipient has # clicked on the link. link = "https://daten-analysieren.de/" # We iterate over the adresses the adress_manager provides, create dynamically a e-mail and send it. for to_adr in adress_manager.get_adresses(): bequest_message = mail_creator.create_html_mail_bequest(to_adr, link) mailer.send_mail(bequest_message) # And finally shut down the server. mailer.shutdown_server()
def scenario_spoof_mail(): # This scenario shows how to send a spoof-mail, i.e. we create and send an email with a forged sender address # First, we specify sender the e-mail should show from_addr = "*****@*****.**" from_name = "Darth Vader" # Here we specify the receiver, please change this as you would like to see the outcome to_addr = "*****@*****.**" # Then we specify our server information # With the server info comes the real sender, while the email will look like it is from darth vader, # it will actually be from the user specified in ServerInfo class. server_info = ServerInfo.ServerInfo() # Using the specified server information we create a session mailer = Mailer.Mailer(server_info) mailer.connect_to_server() mailer.login_to_server() # We use the mail_creator class to generate Vaders' message mail_creator = MailCreator.MailCreator(from_name, from_addr) vaders_message = mail_creator.create_mail_darthvader(to_addr) # And finally send it. After that we shutdown the mail server again. mailer.send_mail(vaders_message) mailer.shutdown_server()
def test_init05(self): Mailer.Mailer( auth='login', host='localhost', port=25, password='******', )
def test_init06(self): Mailer.Mailer( auth='login', host='localhost', port=25, username='******', )
def setUp(self) -> None: self.mailer = Mailer.Mailer( auth='login', host='127.0.0.2', port=4242 ) self.mailer.add_to('*****@*****.**') self.mailer.add_from('*****@*****.**')
def __init__(self): self.config = Helper.Config() self.mailer = Mailer.Mailer() # Stav spojení. self.emergencystate = False # Hranice chybějících candlesticků pro vypnutí bota. self.missingoffset = int(self.config.missingCandlesLength) # Počítadlo chybějících candlesticků. self.missingcandlescounter = 0
def __init__(self): """ Inicializace proměnných třídy. :return: """ self.config = Helper.Config() self.lt = LoadTables() self.subproc1_pid = None self.subproc2_pid = None self.subproc3a_pid = None self.logger = Logger.AplicationLogging() self.printer = Printer.AplicationPrinter() self.mailer = Mailer.Mailer() self.checkconsistence = DataConsistence.CheckConsistence()
def doPP(args): global info stage = args[0] daxnum = int(args[1]) maxdax = int(args[2]) stages = ["CheckSgt", "DAX", "DBWrite"] subject = "Status - Run %d (%s) %s Workflow" % \ (info.run_id, info.site, info.workflow) msg = "Workflow is currently on this stage:\r\n\r\n" if (not stage in stages): print "Stage " + stage + " not found" return 1 if (daxnum > maxdax): print "DAX number %d is greater than max DAX %d" % (daxnum, maxdax) return 1 numstage = len(stages) istage = stages.index(stage) for i in range(0, numstage): if (i <= istage): if (i == istage) and (i == 1): msg = msg + stages[i] + ": Number " + str(daxnum) + \ " of approx " + str(maxdax) + " completed successfully\r\n" else: msg = msg + stages[i] + ": Complete\r\n" else: msg = msg + stages[i] + ": Scheduled\r\n" # Send the email m = Mailer() m.send(info.notify_to, subject, msg) return 0
def __init__(self, db): ''' General description : This function initializes the database variables and \ index to refer in functions. ''' self.configdb = Config.Config(db) self.toolDb = Tool.Tool(db) self.versionsDb = Versions.Versions(db) self.contributionGitPushLogsDb = \ ContributionGitPushLogs.ContributionGitPushLogs(db) self.mailer = Mailer.Mailer() self.systemDetailsDb = SystemDetails.SystemDetails(db) self.config_id = 14 self.load_configuration() self.schedulerService = SchedulerService.SchedulerService()
def send_email_fun(self, df1, df2): ''' ''' send_str = self.get_str_from_dataframe(df1, df2) email = Mailer.Mailer(self.email_config_file) email.send_mail(self.email_title, send_str)
def test_init06(self): Mailer.Mailer(auth='login', host=None, port=25)
action='store_true', default=False) args = parser.parse_args() logfile = '%s/%s.log' % (Constants.LOGGING_DIR, os.path.basename(__file__)) log_format = '%(levelname)s:%(module)s.%(lineno)d:%(asctime)s: %(message)s' logging.basicConfig(filename=logfile, format=log_format, level=logging.INFO) logging.info('============') logging.info('Invoked command: %s' % ' '.join(sys.argv)) script_dir = os.path.dirname(os.path.realpath(__file__)) cmd = "%s/purge_old_foscam_files.sh" % script_dir alert = False try: msg = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT, shell=True, universal_newlines=True, timeout=600) except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: msg = e.output alert = True finally: logging.info(msg) Mailer.sendmail(topic="[PurgeFoscam]", alert=alert, \ message=msg, always_email=args.always_email) print("Done!")
def test_init01(self): Mailer.Mailer(auth='login', host='localhost', port=25, password=None)
# are OK. We'll log in only when we will update the wiki after the long (!) # metrics collection printColor("-- 0. Login on cryptolux wiki: ", 'NOTE') user = input( "Cryptolux wiki user [default = '{0}']:".format(DEFAULT_WIKI_USER)) if len(user) == 0: user = DEFAULT_WIKI_USER printColor("User: {0}".format(user)) wiki = cryptolux.CryptoluxWiki() passwd = getpass.getpass() wiki.login(user, passwd) wiki.logout() # Configure email startTime = time.time() mailer = Mailer.Mailer(SERVER_NAME, SERVER_PORT, user, passwd) try: #### 1. Measure all ciphers using the .get_results.sh script scriptPath = os.path.join(ACRYPT_SRC, "common/scripts/get_results.sh") printColor("-- 1. Update ciphers metrics", 'HEADER') try: output = subprocess.check_output([scriptPath], stderr=subprocess.STDOUT) except subprocess.CalledProcessError: printColor( "Error trying to execute {0}. Exiting...".format(scriptPath), 'ERROR') sys.exit(-1)
def test_init9(self): Mailer.Mailer(auth='gssapi', host='10.1.10.99', port=25)
def test_init03(self): Mailer.Mailer(auth='login', host='localhost', port=25, password='******', username=None)
def test_init8(self): Mailer.Mailer(auth='', host='10.1.10.99', port=25)
from werkzeug.security import generate_password_hash from werkzeug.security import check_password_hash import mysql.connector import uuid import time import Mailer import MKTransforms import numpy import pandas as pd import plotly2json import multiprocessing import modeldrone modelJobs=[] #create mailer object and go ahead and put in passwords for now . . . m=Mailer.Mailer() m.subject='How to use the No Touch Marketing Measurement WebApp' m.send_from='*****@*****.**' m.attachments =["static/downloads/Example.csv"] m.gmail_password='******' with open('templates/Email text.txt', 'r') as myfile: msg1 = myfile.read() m.message=msg1 #end mailer setup. #define flask server app = Flask(__name__) app.secret_key = 'I am the very model of a modern major general' app.config['UPLOAD_FOLDER'] = 'static/Uploads' #port for mysql in D:\home\data\mysql\MYSQLCONNSTR_localdb.txt text_file = open("D:/home/data/mysql/MYSQLCONNSTR_localdb.txt", "r")
def test_init07(self): Mailer.Mailer(auth='login', host='', port=25)
try: out = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT, shell=False, universal_newlines=True, timeout=600) payload = json.loads(out) dlW_mbps = payload.get("download", {}).get("bandwidth", 0)*8/1024/1024 ulW_mbps = payload.get("upload", {}).get("bandwidth", 0)*8/1024/1024 ext_ip = payload.get("interface", {}).get("externalIp", "UNK") if (dlW_mbps > Constants.MIN_DL_BW and ulW_mbps > Constants.MIN_UL_BW): msg += "Link good: " alert = False elif (dlW_mbps > Constants.MIN_DL_BW * 0.8 and ulW_mbps > Constants.MIN_UL_BW * 0.8): msg += "Link degraded (>80%): " else: msg += "Link bad (<80%): " msg += "[%s] DL: %.1f Mbps UL: %.1f Mbps\n" % (ext_ip, dlW_mbps, ulW_mbps) except (subprocess.CalledProcessError, subprocess.TimeoutExpired, json.decoder.JSONDecodeError) as e: msg += "%s\n\n" % (e) msg += "Got: %s\n\n" % (out) print(msg) logging.info(msg) agg_msg += msg if alert and count < args.max_retries: # Wait to retry time.sleep(120) Mailer.sendmail(topic="[SpeedTest]", message=agg_msg, \ always_email=args.always_email, alert=alert) print("Done")
def setUp(self) -> None: self.mailer = Mailer.Mailer(auth='login', host='127.0.0.2', port=25)
import os import sys import urllib.request import Constants import Mailer #### Main Routine #### if __name__ == "__main__": logfile = '%s/%s.log' % (Constants.LOGGING_DIR, os.path.basename(__file__)) log_format = '%(levelname)s:%(module)s.%(lineno)d:%(asctime)s: %(message)s' logging.basicConfig(filename=logfile, format=log_format, level=logging.INFO) logging.info('============') logging.info('Invoked command: %s' % ' '.join(sys.argv)) IP_PAGE="http://myip.dnsomatic.com/" alert=False msg="" try: page = urllib.request.urlopen(IP_PAGE) msg = page.read().decode("utf-8") logging.debug('got %s' % msg) except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: msg = e.output alert = True finally: logging.info(msg) Mailer.sendmail(topic="[Eden's IP]", message=msg, always_email=True, alert=alert)
def notifyTeam(line): Mailer.sendMicrosoftTeamsMessage(socket.gethostname().upper() + " - Error Detected in Line: " + line)
def test_init01(self): Mailer.Mailer()