def main(): args = args_parse() if args.pattern == 'all': filter_asg_name = get_asgname(args.region) threads = [] for asg_name in filter_asg_name: t = threading.Thread(target=exec_cmd, args=(args.module_name, args.module_args, asg_name, args.forks, args.debug, args.remote_port, args.region)) t.daemon = True threads.append(t) t.start() for t in threads: t.join(100) if alarm_disk_message: print 'alarm disk message >>> ', alarm_disk_message if send_mail("aws disk alarm", alarm_disk_message): print 'sendmail sucessful' else: print 'sendmail failed' elif alarm_processNum_message: print 'alarm process number message >>> ', alarm_processNum_message if send_mail("aws process number alarm", alarm_processNum_message): print 'sendmail sucessful' else: print 'sendmail failed' else: print 'alarm_message ok'
def sendy(uname, gID): usr = db.users.find_one({"name": uname}) print(usr) mail = usr["email"] send_mail(mail, "We are playing, come immediately!.\n Game ID is is " + str(gID)) print("sent")
def send_mail(self, commit_hash, name, email, subject, http_res, line_num, url, source_file): self.log.info(self.should_send_mail) if self.should_send_mail == 'True': msg = ('Hi %s,\n\n' 'It appears that the following http link is broken:\n' ' URL: %s\n' ' Returned response code: %s\n' ' Source page: %s\n' ' line: %s\n\n' 'According to the git repository this URL was first ' 'introduced in the following commit:\n' ' Hash Code: %s\n' ' Subject: %s\n\n' 'Please take a look and if needed provide ' 'a proper fix.\n\n Thank you') \ % (name, url, http_res, source_file, line_num, commit_hash, subject) self.log.info(msg) should_send_mail = self._should_send_mail(msg, name) if should_send_mail: sendMail.send_mail(msg, email) sys.stdout.write('Mail sent successfully\n\n') else: self.log.debug('Flag for sending mail is disabled')
def register(): form = RegisterUser() if form.validate_on_submit(): email = form.email.data password = form.password.data username = form.username.data try: form.check_mail(email) except ValidationError as error: return render_template('already_exist.html', error=repr(error)) try: form.check_username(username) except ValidationError as error: return render_template('already_exist.html', error=repr(error)) user = User(email, username, password, 'default.png') db.session.add(user) db.session.commit() user = User.query.filter_by(email=form.email.data).first() mail = user.email send_mail(mail) return redirect(url_for('login')) return render_template('register.html', form=form)
def home(): home = 1 form = Feedback() profile_pic = get_profile_pic() try: email = get_email().split("@")[0] profile = Profile() current_user_profile = profile.query.filter_by(username=email).first() except : current_user_profile = None try: if request.method == "POST": name = request.form['user_name'] current_user_profile.name = name db.session.add(current_user_profile) db.session.commit() except: pass if form.validate_on_submit(): email = form.email.data message = form.message.data send_mail(email, message) flash('Thanks for the feedback!') return redirect(url_for('home')) return render_template("home.html", form = form, home = home, profile_pic = profile_pic, current_user_profile=current_user_profile)
def sendDoneMail(log): sbj = "iGrower: Izvještaj" txt = "(" + str( datetime.datetime.now())[:-7:] + ") Snimanje Filakov je završeno." send_mail(config.mail['username'], config.mail['recipients'], sbj, txt, [log], config.mail['server'], config.mail['port'], config.mail['username'], config.mail['password'], True)
def notify(table, feild, up): print table, feild, up db_subs = c.subscriber res = db_subs.subscription.find_one({'table': table, 'feild': feild}) print res['emails'] msg = up + " on collection " + table + " on field " + feild send_mail("*****@*****.**", res['emails'], 'subscribed operation in DB', msg)
def relocateReservedTS(): global relocatedTsList global session global reservedTsList if (datetime.datetime.now().minute % 5) == 0: #check if the relcating correctly for relocatedTs in relocatedTsList: temp = TSList.query.filter_by(tsAddress = relocatedTs[0]).first() if temp.tasAddress != relocatedTs[1]: #if ts is not belongs to reserved tas, send mail wrongTAS = TASList.query.filter_by(tasAddress = temp.tasAddress).first() if wrongTAS is not None: temp_ = wrongTAS.tasName.split(' ') temp_firstName = "" if temp_firstName is not None: temp_firstName = temp_[0] temp_lastName = "" if temp_lastName is not None: temp_lastName = temp_[1] ReceiverName = User.query.filter_by(firstName = temp_firstName).filter_by(lastName = temp_lastName).first() if ReceiverName is not None: Context = "The TS : " + relocatedTs[0] + " is reserved for now.\nPlease relocate TS to TAS : " + relocatedTs[1] +"\n\nThank you" sendMail.send_mail(temp_lastName +"."+ temp_firstName +"@spirent.com", Context) relocateTSList = reservedTsList.display_list() print(relocateTSList) fromTAS = "" for element in relocateTSList: print(element[2]) if element[2] == True: relocatedTsList.append((element[0], element[1])) #ts addr, tas addr print (relocatedTsList) #locking(element[0]) else: print (relocatedTsList) #unlocking(element[0]) for reservedItem in relocatedTsList: if reservedItem[0] == element[0]: relocatedTsList.remove(reservedItem) break print (relocatedTsList) fromTAS = tsList[element[0]]['tas'] p = Process(target=modifyTs, args=(element[0], element[1])) p.start() p.join(60) #tasmodification(element[0], fromTAS, element[1]) # if (datetime.datetime.now().minute % 10) == 0: # #check if the relcating correctly # for relocatedTs in relocatedTsList: # temp = TSList.query.filter_by(tsAddress = relocatedTs[0]).first() # if temp.tasAddress != relocatedTs[1]: # #if ts is not belongs to reserved tas, relocate again # tasmodification(relocatedTs[0], temp.tasAddress, relocatedTs[1]) threading.Timer(60, relocateReservedTS).start()
def _postprocess(self, intent_tuple): """ Read in the processed message data, pass it to the model object, and make a prediction. Return the data dictionary with the prediction added to it. Returns: ------- dict """ # Return the response to the first occurrence of the pattern in user # message if self.state == 0: (intent, entities) = intent_tuple print("Entities- {}".format(entities)) response_list = self.response_dict.get(intent) if response_list: response = random.choice(response_list['messages']) if entities: response = response.format(*entities) # FIXME - assuming only 1 entity # we take the first entity to check for email id entity = entities[0] # FIXME # checking entity by '@' , ideally the connector should have list of # entities and their types if '@' in entity: self.recipient = entity self.state = 1 else: response = "Could not figure out a proper response. Please try again." else: if self.state == 1: response = "Subject entered - {}. Can you now provide the body?".format( self.subject) self.state = 2 elif self.state == 2: response = "Following are the details by you - \n Subtect - {} \n Body {} \n . \ Please confirm".format(self.subject, self.body) self.state = 3 elif self.state == 3: self.state = 0 send_mail(self.recipient, self.subject, self.body) response = "your mail has been sent" else: self.state = 0 response = "Could not figure out a proper response. Please try again." # save the message somewhere return response
def run(self): status = http_openurl(self.url) print status if status==200: print u"链接[%s]响应正常1,状态为:%s"%(self.url,status) elif status==302: print u"链接[%s]响应正常2,状态为:%s"%(self.url,status) else: print u"链接[%s]响应异常3,状态为:%s"%(self.url,status) print "strat send mail" send_mail(u"链接[%s]响应异常,状态为:%s"%(self.url,status)) print "end send mail" time.sleep(self.interval)
def run(self): status = http_openurl(self.url) print status if status == 200: print u"链接[%s]响应正常1,状态为:%s" % (self.url, status) elif status == 302: print u"链接[%s]响应正常2,状态为:%s" % (self.url, status) else: print u"链接[%s]响应异常3,状态为:%s" % (self.url, status) print "strat send mail" send_mail(u"链接[%s]响应异常,状态为:%s" % (self.url, status)) print "end send mail" time.sleep(self.interval)
def send(name,website=None,to_emails=None,verbose=False): assert to_emails != None if website != None: msg=format_msg(my_name=name,my_website=website) else: msg=format_msg(my_name=name) if verbose: print(name,website,to_emails) #send the msg try: send_mail(text=msg,to_emails=[to_emails],html=None) sent=True except: sent=False return sent
def contact_us(): if request.method == "POST": name = request.form['txtName'] email = request.form['txtEmail'] phone = request.form['txtPhone'] msg = request.form['txtMsg'] send_mail(name, email, phone, msg) if not session.get('user_id'): return render_template('contact-us.html') else: return render_template( 'contact-us.html', unique_id=Users.query.filter_by( id=session.get('user_id')).first().unique_id, is_admin=Users.query.filter_by( id=session.get('user_id')).first().is_admin)
def callback(self, request, result): print 'requestID is', request.requestID, ': fetch information is done ,I will classify these message' if result: for user in self.UserDict: userMessage = '' found = False for infomation in result.infoVar: userMessage += "tags: " for intere in user.interest: if infomation.tags.has_key(intere): found = True userMessage += intere.decode('utf-8') + ' ' userMessage += "\n" userMessage += infomation.brief + '\n' + infomation.link + '\n' userMessage += str( ' collect by 伯虎大通投行 at ' ).decode('utf-8') userMessage += str( time.strftime('%Y-%m-%d %H:%M:%S', result.updateTime)).decode('utf-8') userMessage += '\n' if found: if send_mail( user.mail.decode('utf-8'), str("伯虎大通投行:" + result.fromweb).decode('utf-8'), userMessage): print 'send to ', user.mail, 'done' else: print 'send email error' else: print 'not found userful infomation'
def train_net(solver_prototxt, db, testset_id, pretrained_model=None, max_iters=40000, width=80): # "Train Object Network" sw = SolverWrapper(solver_prototxt, db, testset_id, pretrained_model, width) print 'Solving...' sw.train_model(max_iters) print 'Done solving' send_mail("*****@*****.**", "*****@*****.**", [], "Train Finished %d" % width, "Train Finished %d" % width, None)
def check(homeworks, info): if os.path.isfile(".chomeworks") == False: f = open(".chomeworks", "w+") f.close() sendData = [] for hw in homeworks: link = hw["url"] re = open(".chomeworks", "r") lines = re.readlines() flag = False for line in lines: # print(line.rstrip("\n")) # print("link = \"" + link + "\", line = \"" + line.rstrip("\n") + "\"") if line.rstrip("\n") == link: flag = True break if flag == True: continue sendData.append(hw) re.close() wr = open(".chomeworks", "a+") wr.write(link + "\n") wr.close() if len(sendData) == 0: print("All homeworks were checked before, exiting") return main_message = "" for i in range(len(sendData)): main_message += sendData[i][ "className"] + "dersinde odevin var. " + "Odevin adi " + sendData[ i]["homeworkName"] + ". Odevin icin Kalan sure " + sendData[i][ "remTime"] + ". Odevin linki " + sendData[i]["url"] + "." main_message += "\n" sendMail.send_mail("Yeni Odevlerin Var", main_message, info['recever_mail'], info['sender_mail'], info['sender_pass'])
def check_price(URL): EMAIL = input("Type your email address and press enter: ") PASSWORD = input("Type your password and press enter: ") page = requests.get(URL) # whole html code soup = BeautifulSoup(page.content, 'html.parser') # title class title = soup.find(class_="_1sjrk").get_text() # price class price = soup.find(class_="_wtiln _bdn9q _9a071_2MEB_").get_text() print('Title: ' + title) print('Price: ' + price) # set price to send a mail if int(price[0:3]) < 300: sm.send_mail(URL, EMAIL, PASSWORD)
def sendCapture(): code_img = captureCreate.create_validate_code() fileIO=StringIO.StringIO() code_img[0].save(fileIO, "png") fileIO = base64.encodestring(fileIO.getvalue())#base64 if sendMail.send_mail(['*****@*****.**'],"长沙好工作提交验证",u"<html><body><a>验证码为%s</a></body></html>"%(code_img[1])): print u"发送成功" return ['200',fileIO,code_img[1]] else: print u"发送失败" return ['503',fileIO,code_img[1]] # return ['200',fileIO]
start_time = time.time() runner = unittest.TextTestRunner() run_case(runner) end_time = time.time() sum_time = "%.2f" % (end_time - start_time) data["test_date"] = str(sum_time) + "毫秒" data["test_sum"] = go.CASE_TOTAL data["test_failed"] = go.ERROR_NUM data["test_version"] = "v2.0.8" data["test_pl"] = "python 3" data["test_net"] = "本地连接" data["test_name"] = gm[0]["title"] data["test_success"] = go.SUCCESS_SUM workbook = xlsxwriter.Workbook('report.xlsx') worksheet = workbook.add_worksheet("测试总况") worksheet2 = workbook.add_worksheet("测试详情") # data = {"info": [{"t_id": "1001", "t_name": "登陆", "t_method": "post", "t_url": "http://XXX?login", "t_param": "{user_name:test,pwd:111111}", # "t_hope": "{code:1,msg:登陆成功}", "t_actual": "{code:0,msg:密码错误}", "t_result": "失败"}, {"t_id": "1002", "t_name": "商品列表", "t_method": "get", "t_url": "http://XXX?getFoodList", "t_param": "{}", # "t_hope": "{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png},{name:456,detal:dfadfa,img:product/1.png}]}", "t_actual": "{code:1,msg:成功,info:[{name:123,detal:dfadfa,img:product/1.png},{name:456,detal:dfadfa,img:product/1.png}]}", "t_result": "成功"}], # "test_sum": 100,"test_success": 20, "test_failed": 80, "test_name": "智商", "test_version": "v2.0.8", "test_pl": "android", "test_net": "wifi", "test_date": "2018-10-10 12:10"} bc = be.xlsxwriterBase(wd=workbook, data=data) bc.init(worksheet) bc.test_detail(worksheet2) bc.close() sd.send_mail("report.xlsx", ["*****@*****.**", "*****@*****.**"])
def send_mail(): sendMail.send_mail()
rTmp1.write(str(connectmysql.idTsindex)) rTmp1.close() print('открываем для чтение временные файлы') rTmp1 = open('tmp1.txt', 'r') rTmp2 = open('tmp2.txt', 'r') print('Ok') # print(rTmp.read()) if (rTmp1.read() == rTmp2.read()): print('Запрос') rTmp1.close() rTmp2.close() elif (rTmp1.read() != rTmp2.read()): rTmp1.close() rTmp2.close() rTmp2 = open('tmp.txt', 'w') rTmp2.write(str(connectmysql.idTsindex)) rTmp2.close() print(connectmysql.msgtoemail) sendMail.send_mail("*****@*****.**", connectmysql.msgtoemail) #f = open('tmp.txt', 'w') #f.write(str(connectmysql.idTsindex)) #f.close()
) == -1: # Yazdigimiz kodu cagriyoruz giris yapmasi icin exit() homeworks = getHomeworks.sendHomework(info, args) # print(homeworks) if '--sendAll' in args: main_message = "" main_message2 = [] for i in range(len(homeworks)): main_message2.append(homeworks[i]["className"] + " dersinde odevin var. " + "Odevin adi " + homeworks[i]["homeworkName"] + ". Odevin icin Kalan sure " + homeworks[i]["remTime"] + ". Odevin linki " + homeworks[i]["url"] + ".") main_message += homeworks[i][ "className"] + " dersinde odevin var. " + "Odevin adi " + homeworks[ i]["homeworkName"] + ". Odevin icin Kalan sure " + homeworks[i][ "remTime"] + ". Odevin linki " + homeworks[i]["url"] + "." main_message += "\n" htmlOut.out(main_message2, homeworks) sendMail.send_mail("Odevlerin var!", main_message, info['recever_mail'], info['sender_mail'], info['sender_pass']) if '--check' in args: check.check(homeworks, info) # if '--timerCheck' in args:
def imp_result_reduce(date): f = "%s/exec_results_%s"%(logDir,date) rc = re.compile(r"(### Start time .*)") f = open(f,'r') result = f.read() mlist = re.findall(rc,result) lastStart = mlist[len(mlist) - 1] f.seek(0) rlist=f.readlines() lineNum=rlist.index(lastStart+'\n') ulist = rlist[lineNum:] f.close() flist=[] noFileList=[] dataErrList=[] el1,el2,el3,el4,el5,el6,el7,el8,el9,el10,el99=[],[],[],[],[],[],[],[],[],[],[] sNum,fNum=0,0 for ln in ulist: if 'SUCCESSED' in ln: sNum += 1 elif 'FAILED' in ln: fNum += 1 exceptNo = int(p3.findall(ln)[0]) cid = re.findall(p1,ln)[0] if exceptNo == 1: el1.append(cid) elif exceptNo == 2: el2.append(cid) elif exceptNo == 3: el3.append(cid) elif exceptNo == 4: el4.append(cid) elif exceptNo == 5: el5.append(cid) elif exceptNo == 6: el6.append(cid) elif exceptNo == 7: el7.append(cid) elif exceptNo == 8: el8.append(cid) elif exceptNo == 9: el9.append(cid) elif exceptNo == 10: el10.append(cid) elif exceptNo == 99: el99.append(cid) elif 'no_sql_file' in ln: cid = re.findall(p2,ln) noFileList.append(cid[0]) elif 'local_data_not_equal_with_DX' in ln: cid = re.findall(p1,ln) dataErrList.append(cid[0]) #generate the mail content info = "总共导入: %d\n"%(sNum+fNum+len(noFileList)+len(dataErrList)) info += "成功: %d\n失败: %d\n没有SQL文件: %d\n和鼎新数据不一致的: %d\n\n"%(sNum,fNum,len(noFileList),len(dataErrList)) if dataErrList: info += "###### load data not equal with DX cids: ######\n" for cid in dataErrList: info += "%s 数据不一致,请检查确认,如果没问题请清除锁文件,以便进行下一次导入\n"%(cid) if noFileList: info += "###### No SQL file's cids: ######\n" for list in noFileList: info += "%s\n"%(list) info += "###### Import failed cid(s) and reason(s): ######\n" if el1: for cid in el1: info += "%s %s\n"%(cid,exceptDict[1]) if el2: for cid in el2: info += "%s %s\n"%(cid,exceptDict[2]) if el3: for cid in el3: info += "%s %s\n"%(cid,exceptDict[3]) if el4: for cid in el4: info += "%s %s\n"%(cid,exceptDict[4]) if el5: for cid in el5: info += "%s %s\n"%(cid,exceptDict[5]) if el6: for cid in el6: info += "%s %s\n"%(cid,exceptDict[6]) if el7: for cid in el7: info += "%s %s\n"%(cid,exceptDict[7]) if el8: for cid in el8: info += "%s %s\n"%(cid,exceptDict[8]) if el9: for cid in el9: info += "%s %s\n"%(cid,exceptDict[9]) if el10: for cid in el10: info += "%s %s\n"%(cid,exceptDict[10]) if el99: for cid in el99: info += "%s %s\n"%(cid,exceptDict[99]) info += "\n谢谢,\n孙宁\n" if send_mail("影院导入情况汇总_"+str(today),info): print "Send Successed !" else: print "Send Failed !"
currentminute = time.strftime('%M', time.localtime(time.time())) if int(currentminute) % 20 == 0: #短信延时报警diff(send_time,create_date) timestampDiffList = getTimestampDiff() content = '' t_channelResult = '' for line in timestampDiffList: print str(line) if (line.diff >= 3 and line.count >= 5): timestampList.append(str(line)) t_channelResult = t_channelResult + str(line) if len(timestampList) > 0: content = render(["模板号", "延时", "数量"], timestampList) sendMail.send_mail(to_email, '短信延时' + before + '--' + after, content) if len(t_channelResult) > 60: t_channelResult = t_channelResult[len(t_channelResult) - 60:len(t_channelResult) - 1] #通道异常报警(当前两小时内无数据入库) monitorDateStart = time.strftime( '%Y-%m-%d %H', time.localtime(time.time() - 60 * 60 * 2)) results = getMonitorData(monitorDateStart, after) #查询开始时间(当前时间提前两小时)到结束时间(当前时间)数据 if len(results) <= 0: sendSms(to_mobile, '短信无数据入库', '') sendSms(to_mobile1, '短信无数据入库', '') exit channelResult = '' for line in sorted(results.keys()):
def runRightEdge(system, name, watchlist, mode, daterun, get_prices, closeup): config = configparser.ConfigParser() config.read('C:\etc\properties.ini') password = config['yahoo']['yahoo.pass'] server = config['yahoo']['yahoo.server'] port = config['yahoo']['yahoo.port'] username = config['yahoo']['yahoo.username'] models = ('/W:' + watchlist + daterun, ) timestr = time.strftime("%d%m%y") #Main Model Loop Through for model in models: cc_list = ('*****@*****.**') systemrep = "/P:C:\\dec\\RightEdge\\Systems\\" + system + "\\" + name + ".rep" systemroot = "C:\\dec\\RightEdge\\Systems\\" + system + "\\" systemoutput = "C:\\dec\\RightEdge\\Systems\\" + system + "\\output.html" systemoutputtxt = "C:\\dec\\RightEdge\\Systems\\" + system + "\\output.txt" params = [ r"C:\Program Files (x86)\Yye Software\RightEdge 2010\RightEdge.exe", model, systemrep, mode, get_prices, closeup ] p = Popen(params) #stdout, stderr = p.communicate() print(p.pid) # After 6.5 hours shut down try: p.wait(timeout=3600 * 10) except TimeoutExpired: print('Kill') kill(p.pid) # Loop through each ticker with open(systemoutputtxt, 'r') as f: ticker_list = f.read().splitlines() #print (ticker_list) # Append Images to list image_list = [] for i in ticker_list: image_list.append(systemroot + "images\\" + i + ".png") #print (image_list) with open(systemoutput, 'r') as f: data = str(f.read()) sendMail.send_mail('*****@*****.**', cc_list, 'RE ' + system + ' Breakout Results', data, image_list, server, port, username, password) copyfile( systemoutput, 'C:\\dev\godaddy\\mech\\output\RightEdge\\Live\\' + model.replace('/W:', '').replace('/', '') + '_' + timestr + '.htm') session = ftplib.FTP('ftp.jasonrathgeber.com', '*****@*****.**', 'RcGFhn$qko2.') file = open(systemoutput, 'rb') session.storbinary('STOR /mech/output/RightEdge/Live/' + model.replace('/W:', '').replace('/', '') + '_' + timestr + '.htm', file) # send the file file.close() # close file and FTP FR.fileReading( "C:\dev\godaddy\\mech\output\RightEdge\\Live\\*.htm", 'C:\dev\godaddy\\mech\output\RightEdge\Live\RightEdgeResults.htm', 'RightEdge - Live Trading') fileSummary = open( 'C:\dev\godaddy\\mech\output\RightEdge\Live\RightEdgeResults.htm', 'rb') session.storbinary('STOR /mech/output/RightEdge/Live/RightEdgeResults.htm', fileSummary) # send the file fileSummary.close() session.quit()
# 统计当月的发送量 for index, bizCodeMonthCountPrice in enumerate(bizCodeMonthCountList): monthLimit = "70000" if monthBizCodeMaxBillCountDict.has_key( bizCodeMonthCountPrice.bizCode): monthLimit = str( monthBizCodeMaxBillCountDict[bizCodeMonthCountPrice.bizCode]) monthHasSend = str(getRedisClusterString( bizCodeMonthCountPrice.strKey)) monthSendRate = round(float(monthHasSend) / float(monthLimit) * 100, 2) if monthSendRate >= 80 and monthSendRate <= 95: # 邮箱,标题,内容 for i, bizCodeMail in enumerate(bizCodeMailList): if bizCodeMonthCountPrice.bizCode == bizCodeMail.bizCode: print 'monthCountendMail:' + sendMail.send_mail( bizCodeMail.mail, '邮件发送总量提醒', '业务:' + bizCodeMonthCountPrice.bizCode + '截止目前已发送总量为:' + str(monthSendRate) + '%') elif monthSendRate > 95: for i, bizCodeMail in enumerate(bizCodeMailList): if bizCodeMonthCountPrice.bizCode == bizCodeMail.bizCode: print 'monthCountendSMS:' + sendSms( bizCodeMail.mobile, '业务:' + bizCodeMonthCountPrice.bizCode + '截止目前已发送总量为:' + str(monthSendRate) + '%', '') # 统计当天的发送量 for index, bizCodeDayCountPrice in enumerate(bizCodeDayCountList): dayLimit = "10000" if dayBizCodeMaxBillCountDict.has_key(bizCodeDayCountPrice.bizCode): dayLimit = str( dayBizCodeMaxBillCountDict[bizCodeDayCountPrice.bizCode]) dayHasSend = str(getRedisClusterString(bizCodeDayCountPrice.strKey))
with open("C:\dec\RightEdge\Systems\\" + model + "\output.txt", 'r') as f: ticker_list = f.read().splitlines() #print (ticker_list) # Append Images to list image_list = [] for i in ticker_list: image_list.append("C:\dec\RightEdge\Systems\\" + model + "\images\\" + i + ".png") #print (image_list) with open("C:\dec\RightEdge\Systems\\" + model + "\output.html", 'r') as f: data = str(f.read()) sendMail.send_mail( '*****@*****.**', cc_list, 'RE ' + model.replace('/W:', '') + ' Breakout Results', data, image_list, server, port, username, password) copyfile( "C:\dec\RightEdge\Systems\\" + model + "\output.html", 'C:\dev\godaddy\\mech\output\RightEdge\\Close\\' + model.replace('/W:', '') + '_' + timestr + '.htm') session = ftplib.FTP(gdurl, gduser, gdpass) file = open("C:\dec\RightEdge\Systems\\" + model + "\output.html", 'rb') session.storbinary('STOR /mech/output/RightEdge/Close/' + model.replace('/W:', '') + '_' + timestr + '.htm', file) # send the file file.close() FR.fileReading(
def message_handle(signal: int, content: list, id_dict: dict): # 客户端请求登录 if signal == 1: try: db = userTable.select(None, content[0]) except: return return_json('UserNotExists') if db is None: return return_json('UserNotExists') elif len(db) == 0: return return_json('UserNotExists') else: if db[2] == content[1]: # 创建用户识别码 seed = "1234567890abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sa = [] for i in range(32): sa.append(random.choice(seed)) salt = ''.join(sa) user_db = [salt, detailTable.select(str(db[0]))] # result = ['LoginSuccess', user_db] # 此处将登陆成功信息及数据库内容放入list中再返回 return return_json('LoginSuccess', user_db) elif not db[2] == content[1]: return return_json('PasswordIncorrect') return return_json('UnknowError') # 客户端请求增加用户 elif signal == 2: result = userTable.insert(content[0], content[1]) if result == 'UserExists': return return_json(result) else: if result: return return_json('InsertSuccess') elif not result: return return_json('InsertFail') # 客户端请求删除用户 elif signal == 3: if content[0] is "": result = userTable.delete( userid=id_dict[content[1]]) and detailTable.delete( str(id_dict[content[1]])) else: result = userTable.delete(content[0]) and detailTable.delete( str(id_dict[content[1]])) if result: return return_json('DeleteSuccess') elif not result: return return_json('DeleteFail') # 客户端请求修改密码 elif signal == 4: original_password = userTable.select(str(id_dict[content[0]]), None) if original_password[2] == content[1]: result = userTable.update(str(id_dict[content[0]]), None, content[2]) if result == 'NothingToChange': return return_json(result) else: if result: return return_json('UpdateSuccess') elif not result: return return_json('UpdateFail') else: return return_json('OriginalPasswordIncorrect') # 客户端请求增加项目 elif signal == 5: result = detailTable.insert(str(id_dict[content[0]]), content[1], content[2], content[3]) if result: return return_json('InsertRecordSuccess') elif not result: return return_json('InsertRecordFail') # 客户端请求删除项目 elif signal == 6: result = detailTable.delete(str(id_dict[content[0]]), content[1], content[2]) if result == 'NothingToDelete': return return_json(result) else: if result: return return_json('DeleteRecordSuccess') elif not result: return return_json('DeleteRecordFail') # 客户端请求修改项目 elif signal == 7: result = detailTable.update(str(id_dict[content[0][0]]), content[0][1], content[0][2], content[0][3], content[1][0], content[1][1], content[1][2]) if result == 'RecordNothingToChange': return return_json(result) else: if result: return return_json('UpdateRecordSuccess') elif not result: return return_json('UpdateRecordFail') # 客户端请求查询当前用户所有存储信息 elif signal == 8: result = detailTable.select(str(id_dict[content[0]])) if result == 'UserHaveNoData': return return_json(result) else: return return_json('QuerySuccess', [content[0], result]) # 客户端请求查询用户是否存在 elif signal == 9: result = userTable.select(user=content[0]) if result is None: result = sendMail.send_mail(content[0]) return return_json('SendMailSuccess', [result]) else: return return_json('UserExists') elif signal == 10: result = userTable.select(user=content[0]) if result is None: return 'UserNotExists' else: return result[0]
#cc_list = ('*****@*****.**','*****@*****.**') cc_list = ('*****@*****.**') model = 'MaxAlphaLive' timestr = time.strftime("%d%m%y") session = ftplib.FTP(gdurl, gduser, gdpass) # Backtest Js and download prices os.chdir('c:\\dep\\Mechanizd\\rightedge\\') #send live MaxAlpha Output with open('C:\dec\RightEdge\Systems\MaxAlphaLive\output.html', 'r') as f: data = str(f.read()) sendMail.send_mail('*****@*****.**', cc_list, 'Max Alpha One Live', data, ['C:\dec\RightEdge\Systems\MaxAlphaLive\output.txt'], server, port, username, password) copyfile( "C:\dec\RightEdge\Systems\\" + model + "\output.html", 'C:\dev\godaddy\\mech\output\RightEdge\\Live\\' + model + '_' + timestr + '.htm') file = open('C:\dec\RightEdge\Systems\MaxAlphaLive\output.html', 'rb') session.storbinary('STOR /mech/output/RightEdge/Live/' + model + '_' + timestr + '.htm', file) # send the file file.close() f.close() FR.fileReading(
def mycallback_push(): # 发送邮件 send_mail('招标爬虫', 'push错误') print('招标爬虫', 'check_run错误')
from sendMail import send_mail import config import datetime sbj = "iGrower: Ponovno pokrenuto računalo" txt = "(" + str( datetime.datetime.now())[:-7:] + ") RPi-Filakov je ponovno pokrenut." send_mail(config.mail['username'], config.mail['recipients'], sbj, txt, [], config.mail['server'], config.mail['port'], config.mail['username'], config.mail['password'], True)
def test(): history_bar_data = pd.DataFrame({ ' NTAsset': [ 'BAMS-1001068584', 'BAMS-1001068511', 'BAMS-1001068512', 'BAMS-1001068513' ], ' GDNTAsset': ['CO12034450', 'CO12034451', 'CO12034452', 'CO12034453'], ' SN': ['NNTM000078J0', 'NNTM000078J1', 'NNTM000078J2', 'NNTM000078J3'], ' PEC': ['RNC', 'PP15K', 'ATCA', 'SUN T4'], 'FrameRackPosition': [ '/CNGN18/Lab/CP00/33', '/CNGN18/Lab/CN01/33', '/CNGN18/Lab/CN02/33', '/CNGN18/Lab/CN04/33' ], ' SiteLocation': ['IU', 'IU', 'IU', 'IU'] }) history_bar_data = history_bar_data.set_index(' NTAsset') #print('Raw DB data:') #raw_db_file_name="C:/BarScannerExcels/hist/CGC_asset.xls" #history_bar_data.to_excel(raw_db_file_name) eqm_data = get_eqm_data() print(eqm_data) print(eqm_data.columns.values.tolist()) #print(history_bar_data) #ROOT_DIR="C:/BarScannerExcels/" ROOT_DIR = "D:/baiduyun/百度云同步盘/amazon新品/广告数据下载/自动广告数据下载/" bar_data_df = consolidate_scan_data(ROOT_DIR + 'data/') print('Scanning data:') print(bar_data_df) update_data, updated_history_bar_data = compare_scan_data( bar_data_df, history_bar_data) print('Compare new scan data with DB raw data') update_data_file_name = 'C:/BarScannerExcels/temp/updated_scan_data.xls' final_db_data_file_name = 'C:/BarScannerExcels/temp/db_data.xls' #asset_prime = '*****@*****.**' #asset_prime = '*****@*****.**' asset_prime = '*****@*****.**' #copy_addr='*****@*****.**' #copy_addr = ['*****@*****.**','*****@*****.**'] copy_addr = '*****@*****.**' bcopy_addr = '*****@*****.**' if update_data.empty: print("no data need to update") pass else: update_data.to_excel(update_data_file_name) print('Scan data write as: %s' % update_data_file_name) updated_history_bar_data.to_excel(final_db_data_file_name) print('Final DB data write as: %s' % final_db_data_file_name) """ sm.send_mail(from_addr='*****@*****.**', to_addr='*****@*****.**',cc_addr='*****@*****.**', subjest_content='E-location update', mail_content='Please see the asset update in the attachment', attachment=update_data_file_name) """ sm.send_mail( from_addr='*****@*****.**', to_addr=asset_prime, subjest_content='E-location update', mail_content='Please see the asset update in the attachment', cc_addr=copy_addr, bcc_addr=bcopy_addr, attachment=update_data_file_name) #updated_history_bar_data.to_excel() print('Send the new scan data to asset prime completed.')
gdpass = config['godaddy']['godaddy.pass'] url = config['yahoo']['yahoo.url'] user = config['yahoo']['yahoo.user'] password = config['yahoo']['yahoo.pass'] server = config['yahoo']['yahoo.server'] port = config['yahoo']['yahoo.port'] username = config['yahoo']['yahoo.username'] exec(open("C:\\dep\\Mechanizd\\coin\\market.py").read()) timestr = time.strftime("%Y%m%d_%H%M%S") session = ftplib.FTP(gdurl, gduser, gdpass) theFile = 'C:\\dep\\Mechanizd\\coin\\btcmktcap.htm' copyfile(theFile, 'C:\dev\godaddy\\mech\output\Bitcoin\\btcmktcap.htm') file = open(theFile, 'rb') session.storbinary('STOR /mech/output/Bitcoin/btcmktcap.htm', file) file.close() with open(theFile, 'r') as f: data = str(f.read()) sendMail.send_mail('*****@*****.**', '*****@*****.**', 'BTC Mkt Cap', data, [], server, port, username, password) session.quit()
def main(self): logging.info('--%s-- Start Python Monitor Service ...' %time.strftime('%Y-%m-%d %H:%M:%S')) logging.info('--%s-- Start Load Job Setting ...' %time.strftime('%Y-%m-%d %H:%M:%S')) excute_flag = False try : job = baseSetting.property_setting() job_list = job.job_setting() clock = job_list[0]['clock'] interval = int(job_list[0]['interval']) excute_flag = True except Exception as e : logging.info('--%s-- Load Job Setting Error ... %s' %(time.strftime('%Y-%m-%d %H:%M:%S'),str(e))) logging.info('--%s-- Finish Load Job Setting ...' %time.strftime('%Y-%m-%d %H:%M:%S')) if excute_flag : while 1: logging.info('--%s-- Excute Python Monitor Service ...' %time.strftime('%Y-%m-%d %H:%M:%S')) if self.stop_requested: logging.info('--%s-- A Stop Signal Was Received: Breaking Main Loop ...' %time.strftime('%Y-%m-%d %H:%M:%S')) break else : try : if time.strftime('%H') == clock : logging.info('--%s-- Start Load base Setting ...' %time.strftime('%Y-%m-%d %H:%M:%S')) base = baseSetting.property_setting() senderList = base.sender_setting() mail_user = senderList[0]['mailuser'] mail_pass = senderList[0]['mailpwd'] mail_postfix = senderList[0]['mailpostfix'] mail_host = senderList[0]['mailhost'] mail_success_subject = senderList[0]['successsubject'] mail_success_context = senderList[0]['successcontext'] mail_fail_subject = senderList[0]['failsubject'] mail_fail_context = senderList[0]['failcontext'] mailto_list = base.reciever_setting() backupList = base.backup_setting() file_path = backupList[0]['filepath'] file_name = backupList[0]['filename'] file_fullname = os.path.join(file_path,file_name) %time.strftime('%Y%m%d') databaseList = base.database_setting() db_host = databaseList[0]['ip'] db_user = databaseList[0]['user'] db_pwd = databaseList[0]['password'] db_db = databaseList[0]['db'] db_port = databaseList[0]['port'] logging.info('--%s-- Finish Load base Setting ...' %time.strftime('%Y-%m-%d %H:%M:%S')) if os.path.exists(file_fullname): logging.info('--%s-- Backup Success' %time.strftime('%Y-%m-%d %H:%M:%S')) mail_sub = mail_success_subject +'----' + time.strftime('%Y-%m-%d %H:%M:%S') mail_context = mail_success_context backup_flag = 1 else: logging.info('--%s-- Backup Faild' %time.strftime('%Y-%m-%d %H:%M:%S')) mail_sub =mail_fail_subject +'----' + time.strftime('%Y-%m-%d %H:%M:%S') mail_context = mail_fail_context backup_flag = 0 logging.info('--%s-- Start Send E-Mail' %time.strftime('%Y-%m-%d %H:%M:%S')) s = sendMail.send_mail(mail_host,mail_user,mail_pass,mail_postfix) send_flag = s.send(mailto_list,mail_sub,mail_context) logging.info('--%s-- Finish Send E-Mail' %time.strftime('%Y-%m-%d %H:%M:%S')) conn = serverInfo.get_server_information() ipList = conn.ip_desc() driveList = conn.drive_desc() dataList = [] for drive in driveList: dataSubList = [] dataSubList.append([ipList[0]['IP']]) dataSubList.append(drive['DriveDesc']) dataSubList.append(drive['DriveSize']) dataSubList.append(drive['DriveFreeSpace']) dataSubList.append(backup_flag) dataSubList.append(send_flag) dataList.append(tuple(dataSubList)) logging.info('--%s-- Start Insert Database' %time.strftime('%Y-%m-%d %H:%M:%S')) ms = dbHelper.MSSQL(db_host,db_user,db_pwd,db_db) ms.InsertMany('INSERT INTO MS_Record ([IPV4],[Drive],[DriveSize],[DriveFree]\ ,[Backups],[SendMail]) VALUES (%s,%s,%s,%s,%s,%s)',dataList) logging.info('--%s-- Finish Insert Database' %time.strftime('%Y-%m-%d %H:%M:%S')) else : pass except Exception as e : logging.info('--%s-- Python Monitor Service Error : %s' %(time.strftime('%Y-%m-%d %H:%M:%S'),str(e))) time.sleep(interval) else : pass return