def main(): message = MESSAGE divider = "\n" divider += "-" * 80 divider += "\n" test_passed = True for test_name, napalm_test in NAPALM_TESTS.items(): print("{}: {}".format(test_name, napalm_test)) proc = subprocess.Popen(napalm_test, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (std_out, std_err) = proc.communicate() return_code = proc.returncode if int(return_code) != 0: test_passed = False message = divider message += "TESTS FAILED\n" message += "TEST NAME: {}".format(test_name) message += divider message += divider message += std_out.decode() message += std_err.decode() message += divider break for recipient in RECIPIENTS: send_mail(recipient=recipient, subject=SUBJECT, message=message, sender=SENDER)
def main(): run_last_changed = '1.3.6.1.4.1.9.9.43.1.1.1.0' uptime = get_snmp_uptime(a_device, snmp_user) device_name = get_snmp_system_name(a_device, snmp_user) last_changed = int( snmp_extract(snmp_get_oid_v3(a_device, snmp_user, oid=run_last_changed))) get_snmp_system_name(a_device, snmp_user) get_snmp_uptime(a_device, snmp_user) create_new_device(device_name, uptime, last_changed) current_time = datetime.now() recipient = '*****@*****.**' subject = 'Device {} was modified'.format(device_name) message = ''' The running configuration of {} was modified. This change was detected at: {} Regards, Bouchaib '''.format(device_name, current_time) sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender)
def compare_device_info(hostname,device_info): f = open("device_info.pkl", "rb") prev_rtr1_info = pickle.load(f) prev_rtr2_info = pickle.load(f) f.close() if hostname == "pynet-rtr1": if device_info[3] > prev_rtr1_info[3]: print("Device configuration has been changed. See e-mail for more details.") f = open(device_file, "wb") pickle.dump(device_info,f) pickle.dump(prev_rtr2_info,f) f.close() message = "A change was detected in %s at %s." % (device_info[0], time) email_helper.send_mail(recipient, subject, message, sender) else: print("No changes have been made to this device.") elif hostname == "pynet-rtr2": if device_info[3] > prev_rtr2_info[3]: print("Device configuration has been changed. See e-mail for more details.") f = open(device_file, "wb") pickle.dump(prev_rtr1_info,f) pickle.dump(device_info,f) f.close() message = "A change was detected in %s at %s." % (device_info[0], time) email_helper.send_mail(recipient, subject, message, sender) else: print("No changes have been made to this device.")
def send(): while True: mongo = db.connect_mongo() collection = mongo.raw.exc_info items = list(collection.find({'check': 'N'})) mongo.close() if len(items) == 0: return for item in items: # "from_alias, reply_alias, reply_email, to, subject, content" collection.update( { 'type': item['type'], 'value': item['value'], 'file': item['file'], 'check': 'N' }, { '$set': { 'check': 'Y', 'modifytime': datetime.datetime.now() } }) from_alias = 'Hush' reply_alias = 'Hush' reply_email = "*****@*****.**" to = '[email protected];[email protected];[email protected]' subject = item['type'] content = item['msg'] email_helper.send_mail(from_alias, reply_alias, reply_email, to, subject, content)
def detect_config_change(): net_devices = NetworkDevice.objects.all() config_changed = False for a_device in net_devices: if 'cisco' in a_device.device_class: # check if config file exists if not a_device.cfg_file: print "Initial device backup: {}".format(a_device.device_name) backup_config(a_device) config_changed = True continue # Check if the configuration changed last_changed = int(snmp_wrapper(a_device, oid=global_params.OID_RUNNING_LAST_CHANGED)) if last_changed > a_device.cfg_last_changed: print ">>>Running configuration changed: {}".format(a_device.device_name) config_diffs = backup_config(a_device) config_changed = True if config_diffs: print "Sending email notification regarding changes\n" subject = "Network Device Changed: {}".format(a_device.device_name) send_mail(global_params.EMAIL_RECIPIENT, subject, config_diffs, global_params.EMAIL_SENDER) else: # Update last_changed field to handle reboot case a_device.cfg_last_changed = last_changed a_device.save() if config_changed: print "Checking configuration changes into git" git_handling()
def email_change(dev_change): ''' Takes the dev_change dict, which includes device_name: time_of_change key/value pairs, and send email to the recipient of these device changes. ''' recipient = "*****@*****.**" subject = "Device Config Change" sender = "*****@*****.**" device_time = "" for i in dev_change: device_time += i + " on " + dev_change[i] + " GMT" + "\n" message = ''' Config changes took place on the device(s) listed below. {0} Regards, Erdem '''.format(device_time) email_helper.send_mail(recipient, subject, message, sender) print message
def main(): srx1 = { 'device_type': 'junos', 'hostname': 'srx1.twb-tech.com', 'username': '******', 'password': '******', 'optional_args': {}, } for net_device in (srx1,): device_type = net_device.pop('device_type') driver = get_network_driver(device_type) device = driver(**net_device) device.open() lldp_neighbors = device.get_lldp_neighbors() for local_intf, lldp_list in lldp_neighbors.items(): remote_lldp = lldp_list[0] remote_host = remote_lldp['hostname'] remote_port = remote_lldp['port'] break msg = """ SRX1 is connected on local intf: {local_intf} To remote host: {remote_host} On remote port: {remote_port} """.format(local_intf=local_intf, remote_host=remote_host, remote_port=remote_port) recipient = '*****@*****.**' sender = '*****@*****.**' subject = 'Bonus lesson LLDP exercise' send_mail(recipient, subject, message=msg, sender=sender) print("message sent")
def send_email(): ''' this is how we send email ''' sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'Router Config Has Changed' message = 'the device you are testing has registered a config change' email_helper.send_mail(recipient, subject, message, sender)
def notify(subject): """Takes a router-ID as argument and notify its config is not saved""" recipient = '*****@*****.**' sender = '*****@*****.**' message = '\nWarning, running-config on device %s not saved!!!' % subject print message print 'Sending notification to %s.' % recipient send_mail(recipient, subject, message, sender)
def __send_email_alert(self, router_name, lastChangedTime): for email_recipient in self.email_recipients: subject = str(EMAIL_SUBJECT % router_name) message = str(EMAIL_MESSAGE_BODY % (router_name, time.ctime(lastChangedTime))) print( "Sending mail to %s with subject \"%s\" and message \"%s\" from %s" % (email_recipient, subject, message, self.email_sender)) email_helper.send_mail(email_recipient, subject, message, self.email_sender)
def send_email(change_time): ''' Uses snmplib and the Kirk Byers email_helper library to send an email. Requires an SMTP server. ''' import email_helper recipient = E_ADDR subject = "Config has changed" message = "The configuration changed today at: %s" % change_time sender = "*****@*****.**" email_helper.send_mail(recipient, subject, message, sender)
def send_alert_mail(dev_name, run_last_changed): recipient = '*****@*****.**' subject = "Running config of %s was changed at %s" % (dev_name, run_last_changed) message = '''You better look at this. ''' sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender) return True
def RenameLayers(layertype,gisserver,gisservice,email_list,cc_list,logfile,start_time): logstr('3. Deleting existing features and renaming...') ReplaceFC(layertype) logstr('4. Starting ArcGIS SOM...') StartService(gisserver,gisservice) logstr('5. Renamed layers successfully..') logstr('Script ended at ' + datetime.now().strftime('%H:%M')) script_time = str(time.time() - start_time) logstr('Time to execute script ' + script_time + " seconds") os.chdir(current_dir) send_mail('*****@*****.**',email_list,cc_list,'Layer Load for ' + datetime.now().strftime('%m-%d-%Y'),'The layer load has replaced the layers successfully. Please review the attached log file for additional details.',[logfile])
def keep_informed(self): global logger_alarm for msg in self.consumer_alarm: logger_alarm.info("%s:%d:%d: key=%s value=%s" % (msg.topic, msg.partition, msg.offset, msg.key, msg.value)) self.reload_circle -= 1 if self.reload_circle == 0: self.__reload() msg = json.loads(msg.value) receiver = self.configs.get(msg.get('source')) if receiver: send_mail(u'烯牛数据', u'烯牛数据', u'*****@*****.**', receiver, u'报错', msg.get('comments')) logger_alarm.info('Mail sent')
def process_user(user_id): user_industries_data = [] message_count = 0 user = conn.get("select * from user where id=%s", user_id) if user is None: return if user["active"] == 'D': return if user["email"] is None or user["email"].strip() == "": return if user["emailVerify"] != 'Y' and user["emailVerify"] != 'O': return logger.info("userId: %s, name: %s, phone: %s, email: %s", user["id"], user["username"], user["phone"], user["email"]) ss = conn.query( "select * from user_industry_subscription " "where (active is null or active='Y') and " "userId=%s " "order by id desc", user_id) for s in ss: industry_id = s["industryId"] industry = conn.get("select * from industry where id=%s", industry_id) if industry["active"] == 'N': continue data = industries_data[industry_id] message_count += data["message_count"] user_industries_data.append(data) # logger.info("message count: %s", message_count) # logger.info("data: %s", user_industries_data) str_start = start.strftime("%m月%d日%H:%M") str_end = end.strftime("%m月%d日%H:%M") data = { "start": str_start, "end": str_end, "user": user, "message_count": message_count, "user_industries_data": user_industries_data } t = Template(filename='template/user_industry_track.html', input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace') content = t.render(data=data) logger.info(content.decode('UTF-8')) title = "行业追踪日报(%s ~ %s)" % (str_start, str_end) email_helper.send_mail("烯牛数据", "烯牛数据", "*****@*****.**", user["email"], title, content)
def main(): STATEFILE = '/home/dlopez/pynet/week3/config-change.txt' IP = '50.76.53.27' auth_user = '******' auth_key = 'galileo1' encrypt_key = 'galileo1' py_r1 = (IP,7961) py_r2 = (IP,8061) recipient = '*****@*****.**' subject = 'RTR2 Config Change Monitor' sender = '*****@*****.**' run_time_oid = ('ccmHistoryRunningLastChanged','1.3.6.1.4.1.9.9.43.1.1.1.0') snmp_user = (auth_user,auth_key,encrypt_key) my_output = [] my_input = [] if (StateCheck(STATEFILE) is False): print "File %s does not exist." % STATEFILE file = CreateFile(STATEFILE) #grab the snmp data my_output = CollectData(py_r2,snmp_user,run_time_oid[1]) #print output #save it to file #file.write(my_output) json.dump(my_output,file) #close the file file.close() #exit the program else: print "File %s was found." % STATEFILE #load data with open(STATEFILE) as j: my_input = json.load(j) #grab new data my_output = CollectData(py_r2,snmp_user,run_time_oid[1]) if (my_output != my_input): #either data from input is empty or is newer so write data to the state output j.close() file = CreateFile(STATEFILE) json.dump(my_output,file) file.close() my_output2 = ConvertTicksToTime(my_output) print "Converted time: %s" % my_output2 message = "Previous config time %s. Config was changed at %s" % (my_input,my_output) print message #send email notification email_helper.send_mail(recipient, subject, message, sender)
def CopyLayers(layertype,url,user,pw,directory,convert,emails,cc_email,logfile,db,dbuser,dbpw): logstr('1. Downloading and unzipping files...') check_process,zipfiles = DownloadLayers(layertype,url,user,pw,directory,db,dbuser,dbpw) #check_process = True if check_process: logstr('2. Checking if layers need to be converted from 10.0 to 9.3.1...') Convert10(layertype,zipfiles,convert) os.chdir(directory) logstr('Updating layer load table...') CopyTrue(db,dbuser,dbpw,layertype) logstr('Sending emails...') send_mail('*****@*****.**',emails,cc_email,layertype + ' Layer download for ' + datetime.now().strftime('%m-%d-%Y'),'The layer have been downloaded and unzipped successfully. Please review the attached log file for additional details.',[logfile])
def email_alert(alert_obj): ''' E-mail alert message that running_config has changed Include uptime seconds that config change occurred ''' recipient = '*****@*****.**' subject = '{0}: Running_config has changed'.format(alert_obj.machine_name) message = ''' Machine: {0} running-config changed at uptime: {1} '''.format(alert_obj.machine_name, int(alert_obj.machine_lastchange) / 100) sender = '*****@*****.**' send_mail(recipient, subject, message, sender)
def send_email(change_time): minutes, seconds = uptime(change_time) recipient = '*****@*****.**' subject = 'Config Changed!' message = ''' The routers running configuration has changed %s minutes and %s seconds ago. Thanks, Config-change-automailer ''' % (minutes, seconds) sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender)
def detect_config_change(): ''' Use SNMP to detect configuration changes. If configuration has changed, then: 1. Perform backup 2. Email diff 3. Check change into Git ''' net_devices = NetworkDevice.objects.all() config_changed = False for a_device in net_devices: if 'cisco' in a_device.device_class: # check if config file exists if not a_device.cfg_file: print "Initial device backup: {}".format(a_device.device_name) backup_config(a_device) config_changed = True continue # Check if the configuration changed last_changed = int( snmp_wrapper(a_device, oid=global_params.OID_RUNNING_LAST_CHANGED)) if last_changed > a_device.cfg_last_changed: print ">>>Running configuration changed: {}".format( a_device.device_name) config_diffs = backup_config(a_device) config_changed = True if config_diffs: print "Sending email notification regarding changes\n" subject = "Network Device Changed: {}".format( a_device.device_name) send_mail(global_params.EMAIL_RECIPIENT, subject, config_diffs, global_params.EMAIL_SENDER) else: # Update last_changed field to handle reboot case a_device.cfg_last_changed = last_changed a_device.save() if config_changed: print "Checking configuration changes into git" git_handling()
def write_email(device_name, changes): recpt = '*****@*****.**' sender = '*****@*****.**' subject = 'Changes to router ' + device_name message_body = 'There were changes made to ' + device_name + '.\n\n' if changes[0]: message_body += 'The running configuration was changed.\n' if changes[1]: message_body += 'The running configurtion was saved.\n' if changes[2]: message_body += 'The startup configuration was changed.\n' email_helper.send_mail(recpt, subject, message_body, sender)
def send_email(datetimestr, hostname): """ Sends an Email to my gmail account """ recipient = '*****@*****.**' subject = 'Router Config change alert' message = ''' Router Running Configuration change - ALERT Change: %r Router Name: %s ''' % (datetimestr, hostname) sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender)
def send_email(change_time): minutes,seconds = uptime(change_time) recipient = '*****@*****.**' subject = 'Config Changed!' message = ''' The routers running configuration has changed %s minutes and %s seconds ago. Thanks, Config-change-automailer ''' % (minutes, seconds) sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender)
def main(): snmp_device = (ip_addr, snmp_port_rtr2) snmp_user = (user, auth_key, encrypt_key) # Check whether time file already exists. try: with open('time.pkl') as file: pass except: # If time file does not exist, create first time entry. snmp_data = snmp_get_oid_v3(snmp_device, snmp_user, oid=runningLastChanged) output = snmp_extract(snmp_data) # Store time in a pickle file. d = open("time.pkl", "wb") pickle.dump(output, d) d.close() # Get last time stored. d = open("time.pkl", "rb") last_time = pickle.load(d) print "Last time: " + last_time # Check time of last running config change. snmp_data = snmp_get_oid_v3(snmp_device, snmp_user, oid=runningLastChanged) output = snmp_extract(snmp_data) print "New time: " + output # If time of last change greater than stored time, # store the new change time and send email. if output > last_time: s = float(output) t = Decimal(s/100.0) time = round(t,2) print "Time is now Greater: " + str(time) # Store time of latest change in a pickle file. d = open("time.pkl", "wb") pickle.dump(output, d) d.close() print "New stored value: " + output # Send me an email with the time of last change. message = "Running config changed at: " + str(time) + "sec" email_helper.send_mail(recipient, subject, message, sender) else: print "Running config has not changed."
def process(): items = [] conn = db.connect_torndb() cs = conn.query( "select id, corporateId, code, name, createTime, modifyTime from company " "where companyStatus=2015 and (active='Y' or active is null)") for c in cs: fa = conn.get( "select * from company_fa f join dictionary d on f.source=d.value " "where d.subTypeValue=1301 and (active is null or active='Y') and " "companyId=%s order by publishDate desc limit 1", c["id"]) if fa is not None: continue funding = conn.get( "select * from funding where (active is null or active='Y') and " "corporateId=%s order by fundingDate desc limit 1", c["corporateId"]) if funding is None: continue status_time = c["modifyTime"] if status_time is None: status_time = c["createTime"] if status_time is None: continue if status_time > funding["fundingDate"] + timedelta(days=7): continue # logger.info("companyId: %s, code: %s, name: %s, may finish raising money", c["id"], c["code"], c["name"]) items.append((c["id"], c["code"], c["name"])) conn.close() # send email t = Template(filename='template/check_company_status.html', input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace') content = t.render(data={"items": items}) # logger.info(content) d = datetime.now() for email in emails: email_helper.send_mail( "烯牛数据", "烯牛数据", "*****@*****.**", email, "疑似融资结束的公司清单-%s/%s/%s" % (d.year, d.month, d.day), content)
def main(): today = datetime.datetime.now() today = datetime.datetime(year=today.year, month=today.month, day=today.day) - datetime.timedelta(hours=8) yesterday = today - datetime.timedelta(days=1) logger.info("today: %s, yesterday: %s", today, yesterday) mongo = db.connect_mongo() items = list(mongo.company.funding.find( { "companyFullyVerify":"N", "fundingCreateTime": {"$gte": yesterday, "$lt": today} } )) all_items = list(mongo.company.funding.find( { "fundingCreateTime": {"$gte": yesterday, "$lt": today} } )) mongo.close() # logger.info(items) companies = [] all_companies = [] conn = db.connect_torndb() for item in items: company = get_detail(conn, item) companies.append(company) for item in all_items: company = get_detail(conn, item) all_companies.append(company) conn.close() companies.sort(key=lambda k:(k.get('fundingCreator', ''))) all_companies.sort(key=lambda k: (k.get('fundingCreator', ''))) # send email t = Template(filename='template/not_fully_verified_company.html', input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace') content = t.render(data={"items": companies, "allItems": all_companies}) logger.info(content) d = datetime.datetime.now() for email in emails: email_helper.send_mail("烯牛数据", "烯牛数据", "*****@*****.**", email, "有融资但内容未完全确认的公司清单-%s/%s/%s" % (d.year, d.month, d.day), content)
def restart(server_name,service_name,email_list,cc_list): start_time = 0 close_status = 'sc \\\\'+ server_name +' query '+ service_name +' | find "STOPPED"' start_status = 'sc \\\\'+ server_name +' query '+ service_name +' | find "RUNNING"' pending_start_status = 'sc \\\\'+ server_name +' query '+ service_name +' | find "START_PENDING"' pending_close_status = 'sc \\\\'+ server_name +' query '+ service_name +' | find "STOP_PENDING"' close = "sc \\\\"+server_name+' stop '+service_name start = "sc \\\\"+server_name+' start '+service_name running = Popen(start_status,shell=True).wait() if running==0: print ('Oracle Service is closing') Popen(close,shell=True).wait() #time.sleep(60) close_pending = Popen(pending_close_status,shell=True).wait() print close_pending while close_pending == 0: time.sleep(15) #Give the process time to close before checking the status closed = Popen(close_status,shell=True).wait() start_time += 15 if closed == 0: print ('Oracle service has been stopped. Restarting...') Popen(start,shell=True).wait() close_pending = Popen(pending_close_status,shell=True).wait() # This should stop the outside loop start_pending = Popen(pending_start_status,shell=True).wait() # Make sure Oracle has restarted before doing anything else print start_pending while start_pending == 0: time.sleep(15) start = Popen(start_status,shell=True).wait() if start ==0: time.sleep(30) start_pending = Popen(pending_start_status,shell=True).wait() elif start_time > 600: #Service has not closed after 10 minutes... Check the status and send an email notification close_pending = 1 #Force quit the loop and send an email notification send_mail('*****@*****.**',email_list,cc_list,'Layer Load Error for ' + datetime.now().strftime('%m-%d-%Y'),'The layer load has experienced an error restarting ' +service_name+'. This error has occurred on '+server_name+'.',[])
def main(): password = getpass() srx1 = { 'device_type': 'junos', 'hostname': 'srx1.twb-tech.com', 'username': '******', 'password': password, 'optional_args': {}, } for net_device in (srx1, ): device_type = net_device.pop('device_type') driver = get_network_driver(device_type) # Establish a NAPALM connection device = driver(**net_device) device.open() lldp_neighbors = device.get_lldp_neighbors() # Should only be one entry for local_intf, lldp_list in lldp_neighbors.items(): remote_lldp = lldp_list[0] remote_host = remote_lldp['hostname'] remote_port = remote_lldp['port'] break # Send email msg = """ SRX1 is connected on local intf: {local_intf} To remote host: {remote_host} On remote port: {remote_port} """.format(local_intf=local_intf, remote_host=remote_host, remote_port=remote_port) recipient = '*****@*****.**' sender = '*****@*****.**' subject = 'Bonus lesson LLDP exercise' send_mail(recipient, subject, message=msg, sender=sender) print() print("Message sent...check your inbox.") print()
def main(): # pynet-rtr2 (Cisco 881) device = ('184.105.247.71', 161) snmp_user = ('pysnmp', 'galileo1', 'galileo1') ssh_user = ('pyclass', '88newclass') recipient = '*****@*****.**' sender = '*****@*****.**' device_name = snmp_helper.snmp_extract( snmp_helper.snmp_get_oid_v3(device, snmp_user, oid=OID_SYSNAME)) yaml_filename = device_name + '.yml' # get running config change timestamp (last_changed_net) last_changed_net = snmp_helper.snmp_extract( snmp_helper.snmp_get_oid_v3(device, snmp_user, oid=OID_RUN_CHANGED)) # Load last checked running config timestamp (last_changed_yaml) from YAML file, default to epoc try: with open(yaml_filename) as f: yaml_data = yaml.load(f) except EnvironmentError: #Yaml file doesn't exist, load some defaults yaml_data = {'last_changed': 0, 'config': ''} # if last_changed_net > last_changed_yaml, then: get config_net, compare to config_yaml, email diff, store config_net and last_changed_net in yaml file if last_changed_net > yaml_data['last_changed']: print("Change detected. Getting config from " + device_name + "...") config_net = get_ios_config().split('\n') config_yaml = yaml_data['config'] config_diff = list( set(config_net).symmetric_difference(set(config_yaml))) #Email the difference print("Notifying " + recipient + "...") subj = 'CHANGE DETECTED: Config on ' + device_name + ' detected at ' + datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S') message = 'Previous Config Timestamp: ' + str( yaml_data['last_changed']) + '\n' message += 'Current Config Timestamp: ' + last_changed_net + '\n' message += '\nNewly Detected Config: \n' message += '\n'.join(config_diff) email_helper.send_mail(recipient, subj, message, sender) #store the current config and time stamp in yaml file print("Storing the current config in " + yaml_filename) yaml_data = {'last_changed': last_changed_net, 'config': config_net} with open(yaml_filename, 'w') as f: f.write(yaml.safe_dump(yaml_data, default_flow_style=False)) else: print("No change detected")
def main(): conn = db.connect_torndb() mongo = db.connect_mongo() orgs = conn.query("select * from org_openapi_conf where (active is null or active='Y') and trial='Y'") for org in orgs: accesskeyid = org["accesskeyid"] cnt = mongo.log.openapi_log.find({"accesskeyid": accesskeyid, "code":0}).count() logger.info("orgId: %s, cnt: %s", org["organizationId"], cnt) conn.update("update org_openapi_conf set usedCnt=%s where id=%s", cnt, org["id"]) if cnt + 1000 > org["maxTest"]: w = mongo.log.openapi_warning.find_one({"orgId": org["organizationId"]}, sort=[('time', -1)]) if w is None or (datetime.datetime.utcnow() - w["time"]).days >= 1: o = conn.get("select * from organization where id=%s", org["organizationId"]) title = "%s-api访问次数即将耗尽" % o["name"] logger.info(title) content = title + "。\n" content += "可访问次数: %s, 已使用次数: %s。\n" % (org["maxTest"], cnt) content += "请尽快联系客户!" mongo.log.openapi_warning.insert_one( {"orgId": org["organizationId"], "time": datetime.datetime.utcnow(), "description": title}) for email in emails: email_helper.send_mail("烯牛数据", "烯牛数据", "*****@*****.**", email, title, content) if cnt > org["maxTest"]: conn.update("update org_openapi_conf set active='N' where id=%s", org["id"]) o = conn.get("select * from organization where id=%s", org["organizationId"]) title = "%s-api访问次数已耗尽" % o["name"] logger.info(title) content = title + "。\n" content += "可访问次数: %s, 已使用次数: %s。\n" % (org["maxTest"], cnt) content += "请尽快联系客户!" mongo.log.openapi_warning.insert_one( {"orgId": org["organizationId"], "time": datetime.datetime.utcnow(), "description": title}) for email in emails: email_helper.send_mail("烯牛数据", "烯牛数据", "*****@*****.**", email, title, content) mongo.close() conn.close()
def email_notification(router, time): ''' this function send an email notification to receptient indicating that an equipement has a configuration cahnge. ''' sender = '*****@*****.**' recepient = '*****@*****.**' subject = router + ' has a configuration change at ' + str(datetime.timedelta(seconds=time/100)) message = ''' Hi, this is to inform you that {0} had a configuration change at {1}. Best regards, Hassan HBAR. '''.format(router, str(datetime.timedelta(seconds=time/100))) email_helper.send_mail(recepient, subject, message, sender)
def notifications(device_name): current_time = datetime.now() sender = '*****@*****.**' recipient = '*****@*****.**' subject = '{} was modified'.format(device_name) message = '''{} was modified at: {}'''.format(device_name, current_time) if send_mail(recipient, subject, message, sender): print('Email notification sent to {}'.format(recipient)) return True
def CheckConfig(): global timestamp snmp_device = (snmpaddr, snmpport) snmp_user = (v3uname, v3authkey, v3encrkey) snmp_data = snmp_helper.snmp_get_oid_v3(snmp_device, snmp_user, oid1, v3authtype, v3encrtype) output = snmp_helper.snmp_extract(snmp_data) if bool(timestamp) == False: timestamp.append(output) print '\nWe have begun monitoring this device for configuration changes.' print '%s %s' % ('The timestamp for the device is currently: ', output) print 'We will check the device again in 5 minutes.\n' elif timestamp[0] != '': if output == timestamp[0]: print 'The configuration has not changed in the last 5 minutes.' print '%s %s' % ('The timestamp for the device is currnetly: ', output) print 'We will check the device again in 5 minutes.\n' elif output != timestamp[0]: timestamp[0] = output print 'The configuation has changed.' print 'Sending email alert and checking device again in 5 minutes.\n' email_helper.send_mail(recipient, subject, message, sender)
def main(): ip_addr = '50.76.53.27' port = 8061 pynet_rtr2 = (ip_addr, port) a_user = '******' auth_key = 'galileo1' encrypt_key = 'galileo1' snmp_user = (a_user, auth_key, encrypt_key) oids = {'sysUptime' : '1.3.6.1.2.1.1.3.0', 'ccmHistoryRunningLastChanged' : '1.3.6.1.4.1.9.9.43.1.1.1.0', 'ccmHistoryRunningLastSaved' : '1.3.6.1.4.1.9.9.43.1.1.2.0', 'ccmHistoryStartupLastChanged' : '1.3.6.1.4.1.9.9.43.1.1.3.0'} change_times = {} for oid, num in oids.items(): output = get_snmp_v3_data(pynet_rtr2, snmp_user, oid=num) change_times[oid] = output # get the old timestamps old_change_times = {} if os.path.exists(FILE): f = open(FILE, "r") old_change_times = pickle.load(f) f.close() else: for oid in oids.keys(): old_change_times[oid] = change_times[oid] if int(old_change_times['ccmHistoryRunningLastChanged']) < int(change_times['ccmHistoryRunningLastChanged']): print "Running config has changed" send_mail("*****@*****.**", "config changes", "config has changed", "*****@*****.**") else: print "Running config has NOT changed" # save latest timestamps as a reference f = open(FILE, "w") pickle.dump(change_times, f) f.close()
def main(): '''Connect to rtr1 and rtr2 and print snmp stuff''' snmp_username = '******' snmp_auth_key = 'galileo1' snmp_encrypt_key = 'galileo1' snmp_user = (snmp_username, snmp_auth_key, snmp_encrypt_key) #email details sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'Test message' message = '' rtr1 = device('50.76.53.27','7961') rtr1.snmp_user = snmp_user rtr2 = device('50.76.53.27','8061') rtr2.snmp_user = snmp_user devices = [rtr1, rtr2] # rtr1.oid = rtr1.query_get('.1.3.6.1.2.1.1.1.0') # rtr1.sysDescr = rtr1.extract(rtr1.oid) # rtr1.oid = rtr1.query_get('.1.3.6.1.2.1.1.5.0') # rtr1.sysName = rtr1.extract(rtr1.oid) # print rtr1.oid # print rtr1 while True: for item in devices: item.get_sysinfo() if item.RunningLastChangedDelta/6000 < 5: print item.RunningLastChangedDelta print item.sysName + " changed at %s" % (datetime.now() - timedelta(seconds=item.RunningLastChangedDelta/100)) print "now is %s" % datetime.now() message += item.sysName + " changed at %s \n" % (datetime.now() - timedelta(seconds=item.RunningLastChangedDelta/100)) if len(message) > 0: email_helper.send_mail(recipient, subject, message, sender) message = "" time.sleep(300)
def send_notification(device_name): current_time = datetime.now() sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'Device {} as modified'.format(device_name) msg = ''' The running configuration of {} was modified. This Change was detected at: {} '''.format(device_name, current_time) if send_mail(recipient, subject, msg, sender): print('Email notification send to {}'.format(recipient)) return True
def main(): sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'This is a test message.' message = ''' Whatever Whatever ''' if send_mail(recipient, subject, message, sender): print 'Email notification sent to {}'.format(recipient) return True
def email(olddata, newdata): ''' email function to send an alert ''' recipient = '*****@*****.**' subject = 'Configuration Changed for %s' % newdata[0] message = ''' A configuration change was detected. See event details below: Device name: %s IP: %s Change detected at: %s UTC Last poll: %s UTC ''' % (newdata[0], newdata[1], newdata[2], olddata.poll_time) sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender) return None
def send_notification(device_name): ''' Send email notification regarding modified device ''' current_time = datetime.now() sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'Device {0} was modified'.format(device_name) message = ''' The running configuration of {0} was modified. This change was detected at: {1} '''.format(device_name, current_time) if send_mail(recipient, subject, message, sender): print 'Email notification sent to {}'.format(recipient) return True
def send_notification(net_device): current_time = datetime.now() sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'Device {0} was modified'.format(net_device.device_name) message = ''' The running configuration of {0} was modified. This change was detected at: {1} '''.format(net_device.device_name, current_time) if send_mail(recipient, subject, message, sender): print 'Email notification sent to {}'.format(recipient) return True
def send_notification(device): current_time = datetime.now() name_of_device = str(device[device_name]) sender = '*****@*****.**' recipient = 'stelica.dragnia@gmail' subject = 'Device {0} was modified' .format(name_of_device) message = ''' The running configuration of {0} was modified at: {1} '''.format(name_of_device, current_time) if send_mail(recipient, subject, message, sender): print 'Email notification sent to %s ' %recipient return True
def send_notification(net_device): ''' Send email notification regarding modified device ''' current_time = datetime.now() sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'Device {0} was modified'.format(net_device.device_name) message = ''' The running configuration of {0} was modified. This change was detected at: {1} '''.format(net_device.device_name, current_time) if send_mail(recipient, subject, message, sender): print 'Email notification sent to {}'.format(recipient) return True
def main(): """Checks device and then sends alert if device configuration has changed.""" did_it_change = check_for_change(LAB_USER, PYNET_RTR2, CCM_HISTORY_RUNNING_LAST_CHANGED, 'run-conf-check.json') if did_it_change: email_helper.send_mail('*****@*****.**', "It's changed!!!", "It's changed!!!", '*****@*****.**') print did_it_change did_it_change = check_for_change(LAB_USER, PYNET_RTR2, CCM_HISTORY_RUNNING_LAST_SAVED, 'run-conf-saved-check.json') if did_it_change: email_helper.send_mail('*****@*****.**', "It's changed!!!", "It's changed!!!", '*****@*****.**') print did_it_change did_it_change = check_for_change(LAB_USER, PYNET_RTR2, CCM_HISTORY_STARTUP_LAST_CHANGED, 'start-conf-check.json') if did_it_change: email_helper.send_mail('*****@*****.**', "It's changed!!!", "It's changed!!!", '*****@*****.**') print did_it_change
#!/usr/bin/env python from email_helper import send_mail sender = '*****@*****.**' recipient = '*****@*****.**' subject = 'Test email for Interop Python course' message = ''' This is a test email for Interop Python course ''' print "Sending email mesage to {}".format(recipient) send_mail(recipient, subject, message, sender)
def poll_device(routers, router_cfg_times, verbose=False, quiet=False): '''Poll router(s) for specified data.''' for router in routers: # Start time of poll sequence for router now = str(datetime.datetime.today()) router_config_changed = False change_output = '' if not quiet: print 'Router {} - Poll start time {}:'.format(router['HOSTNAME'], now) if router['HOSTNAME'] not in router_cfg_times: router_cfg_times[router['HOSTNAME']] = OrderedDict([('LAST_POLLTIME', now), ('CHECK_TIMES', False)]) else: router_cfg_times[router['HOSTNAME']]['LAST_POLLTIME'] = now router_cfg_times[router['HOSTNAME']]['CHECK_TIMES'] = True for snmp_target in SNMP_TARGETS: snmp_result = get_snmp_data((router['ADDRESS'], router['SNMP_PORT']), (router['SNMP_USER'], router['SNMP_AUTH'], router['SNMP_KEY']), SNMP_TARGETS[snmp_target]) # If check_times then need to compare new and old... if router_cfg_times[router['HOSTNAME']]['CHECK_TIMES']: # Only track changes that start with SNMP_TRACK if SNMP_TRACK in snmp_target: if router_cfg_times[router['HOSTNAME']][snmp_target] < snmp_result: router_config_changed = True router_cfg_times[router['HOSTNAME']][snmp_target+'_CHANGED'] = True diff_uptime = int( router_cfg_times[router['HOSTNAME']][SNMP_MARK]) - int(snmp_result) # diff_uptime is in ticks, convert to seconds systime = time.time() - (diff_uptime/100) systimestr = time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime( systime)) router_cfg_times[router['HOSTNAME']][snmp_target] = snmp_result diff_datetime = timeticks_to_datetime(diff_uptime) change_output += '{} ({}) changed {} ({}) ago\n'.format( CONFIG_CHANGES[snmp_target], snmp_target, diff_datetime, diff_uptime) change_output += 'Change occurred at {} local system time'.format( systimestr) elif router_cfg_times[router['HOSTNAME']][snmp_target] > snmp_result: sys.exit( 'Error: {} on {} decreased in value, something went wrong.'.format( snmp_target, router['HOSTNAME'])) else: router_cfg_times[router['HOSTNAME']][snmp_target+'_CHANGED'] = False else: router_cfg_times[router['HOSTNAME']][snmp_target] = snmp_result else: router_cfg_times[router['HOSTNAME']][snmp_target] = snmp_result # Output data - should put this into a class with a print/string method if verbose: snmp_result_formatted = timeticks_to_datetime(snmp_result) print '{} ({}): {} ({})'.format(snmp_target, SNMP_TARGETS[snmp_target], snmp_result_formatted, router_cfg_times[router['HOSTNAME']][snmp_target]) # Was there a config change in the router? if router_config_changed: message = '\nChanges detected on {}:\n{}'.format(router['HOSTNAME'], change_output) if not quiet: if os.name == 'posix': termcolor.cprint(message, 'yellow', attrs=['blink']) else: # termcolor doesn't work on Windows, at least not from PowerShell print message print 'Sending notification to {}'.format(RECIPIENT) subject_add = ' on {}'.format(router['HOSTNAME']) send_mail(RECIPIENT, SUBJECT+subject_add, message, SENDER) else: if not quiet: print 'No changes detected on {}.'.format(router['HOSTNAME']) if not quiet: print '' return router_cfg_times
def main(): requests.packages.urllib3.disable_warnings(InsecureRequestWarning) password = getpass() cisco_rtr1 = { 'hostname': '184.105.247.70', 'device_type': 'ios', 'password': password, 'username': '******', 'optional_args': {} } cisco_rtr2 = { 'hostname': '184.105.247.71', 'device_type': 'ios', 'password': password, 'username': '******', 'optional_args': {} } arista_sw1 = { 'hostname': '184.105.247.72', 'device_type': 'eos', 'password': password, 'username': '******', 'optional_args': {} } arista_sw2 = { 'hostname': '184.105.247.73', 'device_type': 'eos', 'password': password, 'username': '******', 'optional_args': {} } jnpr_srx1 = { 'hostname': '184.105.247.76', 'device_type': 'junos', 'password': password, 'username': '******', 'optional_args': {} } cisco_nxos = { 'hostname': 'nxos1.twb-tech.com', 'device_type': 'nxos', 'password': password, 'username': '******', 'optional_args': { 'port': '8443', 'nxos_protocol': 'https' } } # devices = (cisco_rtr1, cisco_rtr2, arista_sw1, arista_sw2, jnpr_srx1, cisco_nxos) devices = (jnpr_srx1, ) napalm_conns = [] neighbor_list = [] port_list = [] for a_device in devices: # print("\n") # pprint(a_device) print("\n") device_type = a_device.pop('device_type') driver = get_network_driver(device_type) device = driver(**a_device) napalm_conns.append(device) print(" ******************** DEVICE START **********************") print("\nDevice created! Host: {}".format(a_device['hostname'])) device.open() print("\nDevice connection opened! Type: {}".format(device_type)) lldp = device.get_lldp_neighbors() print("\n{}\n".format(lldp)) for key in lldp.keys(): local_int = key remote_device = lldp[key][0]['hostname'] remote_port = lldp[key][0]['port'] print( "local interface {} has a neighbor {} connected on remote port {}" .format(local_int, remote_device, remote_port)) # for key in lldp.keys(): # neighbor_list.append(lldp[key][0]['hostname']) # port_list.append(lldp[key][0]['port']) # print(" --------------------- DEVICE END -----------------------") # print("\n") # print("\nThe neighbors are: {}".format(neighbor_list)) # print("\nThe ports are: {}".format(port_list)) ### EMAIL CODE ### recipient = '*****@*****.**' subject = 'Test message' message = ''' local interface {} has a neighbor {} connected on remote port {} Regards, Tim '''.format(local_int, remote_device, remote_port) sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender) print("email has been sent with the following message: {}".format( message))
#DB connection EXT_VENDOR_BSM_QGIS510_sde = "Database Connections\\"+SDE_CONNECTION+".sde" if args.proctype[0] == 'COPY': GDB_VERSION =args.gdbversion[0] logstr('1. Deleting any temporary features...') DelTemp(LAYER_TYPE) logstr('2. Copying '+ LAYER_TYPE +' temp features to EXT_VENDOR...') LayerCopy(LAYER_TYPE,GDB_VERSION) script_time = str(time.time() - start_time) logstr('3. Script Complete..') logstr('Script ended at ' + datetime.now().strftime('%H:%M')) logstr('Time to execute script ' + script_time + " seconds") send_mail('*****@*****.**',args.e,args.cc,'Layer Load for ' + datetime.now().strftime('%m-%d-%Y'),'The layer load has copied the layers into the EXT_VENDOR schema. Please review the attached log file for additional details.',[LOGFILE]) CopyComplete(DB,DBUSER,DBPW,LAYER_TYPE) if renamerun: LAYER_TYPE = args.layertype[0] LOGFILE = datetime.now().strftime(LAYER_TYPE+'_LayerLoad_%d_%m_%Y.log') logging.basicConfig(filename=LOGFILE,level=logging.INFO) #print args.proctype[0] start_time = time.time() #modify this to check the text file for COPY COMPLETE if args.proctype[0] == 'CLOSE': print 'Closing connections' ORACLE_SERVER = args.oraserver[0] ORACLE_SERVICE = args.oraservice[0] GIS_SERVER = args.gisserver[0]
def send_email_to_sham(self,sender,recepient,message,subject): email_helper.send_mail(recepient,subject,message,sender)
def send_email_change(has_changed): recipient = '*****@*****.**' subject = 'Device Configuration Change' message = has_changed + "\n Regards, \nAngel" sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender)
except: print 'something went horribly wrong' if check_runningchanged >= runninglastchanged: runninglastchanged = check_runningchanged timestamp = convert_to_time(uptime) - convert_to_time(runninglastchanged) recipient = '*****@*****.**' subject = 'Pynet status change' #could use some logic to enter device name here if we rewrote some of the above message = ''' Something changed on the configuration of rtr2 %s minutes ago! ''' % timestamp sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender) if check_runningsaved >= runninglastsaved: runninglastsaved = check_runningsaved timestamp = convert_to_time(uptime) - convert_to_time(runninglastsaved) recipient = '*****@*****.**' subject = 'Pynet status change' #could use some logic to enter device name here if we rewrote some of the above message = ''' Something changed on the configuration of rtr2 %s minutes ago! ''' % timestamp sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender)
smtp_server = 'mail1.eircom.net' message = ''' It looks like the Running Config on {} has been changed. You should look into that. It happened more less {} second(s) ago. '''.format ( router, time_since_running_changed ) if running_last_changed_ticks > running_last_saved_ticks: print "Running Config has been changed" # this test is very arbitrary: if running_last_changed_ticks < 10: # maybe just booted? message += ''' There is a slight chance that the router was just rebooted. ''' from email_helper import send_mail send_mail ( recipient, subject, message, sender, smtp_server) else: print "Running Config has not been changed since last Running Config save" if startup_last_changed_ticks > running_last_changed_ticks: print "Startup Config has been saved since last Running Config change" else: print "Startup Config has not been saved since last Running Config change" print
# Create SMTP connection object to localhost smtp_conn = smtplib.SMTP('localhost') # Send the email smtp_conn.sendmail(sender, recipient, message.as_string()) # Close SMTP connection smtp_conn.quit() return True import email_helper recipient = '*****@*****.**' subject = 'Test message' message = ''' This is a fictional test message. Regards, Bouchaib ''' sender = '*****@*****.**' email_helper.send_mail(recipient, subject, message, sender)
} update_data(save_file,data,config_status) exit(0) else: f.seek(0,0) data = json.load(f) old_uptime = data["uptime"] old_run_last_change = data["running_last_changed"] old_run_last_save = data["running_last_saved"] old_start_last_change = data["startup_last_changed"] update_data(save_file,data,config_status) if (data["running_last_saved"] == "0") and (data["running_last_changed"] != old_run_last_change): #reboot print "Reboot" send_mail(smtp_recipient,smtp_subject,"Reboot detected",smtp_sender) #exit(0) try: time.sleep(900) main() except KeyboardInterrupt: print "Exiting" exit(0) if (data["running_last_saved"] != old_run_last_save) and (data["startup_last_changed"] != old_start_last_change): print "write mem" send_mail(smtp_recipient,smtp_subject,"Wr mem",smtp_sender) #exit(0) try: time.sleep(900) main() except KeyboardInterrupt:
def email(message): recepient = '*****@*****.**' subject = 'configuration has changed' sender = '*****@*****.**' email_helper.send_mail(recepient,subject,message,sender) return()