def test(): appPackage = [ 'com.android.settings', 'com.android.browser', 'com.android.calculator2', 'com.android.calendar', 'com.android.camera2', 'com.android.deskclock', 'com.android.contacts', 'com.android.email', 'com.sprd.fileexplorer', 'com.thunderst.radio', 'com.android.gallery3d', 'com.google.android.gm', 'com.google.android.gms', 'com.android.dialer', 'com.android.mms', 'com.android.music', 'com.sprd.note', 'com.android.dialer', 'com.android.vending', 'com.android.quicksearchbox', 'com.android.soundrecorder', 'tran.com.android.taplaota', 'com.android.launcher3', 'com.android.messaging' ] str = '' for i in appPackage: os.popen('adb shell monkey -p ' + i + ' --throttle 500 100') # print 'adb shell monkey -p '+i+' 1' time.sleep(5) cmd = os.popen('adb shell dumpsys activity top | ' + seek + ' ACTIVITY').readline() if i not in cmd: str += i + '未启动成功,也可能是谷歌应用跳转到登陆界面' + '\n' print i + '未启动成功,也可能是谷歌应用跳转到登陆界面' tester_list = ['*****@*****.**'] sendMail.send(tester_list, u"未启动的应用", "hi all:" + "\n" + " 本次测试疑似未启动的应用有:" + "\n" + str)
def ota(): ftp = ftpconnect() ftp.cwd("/work/Doc_For_OSTeam/Doc_For_OSTeam/simg2img/out_ota/w3_60_debug") fileList = [] time = GetLog.getTime('%Y%m%d') print '当前日期'+time getOta = 'false' time2 = time[2:] print time2 for i in ftp.nlst(): if 'zip' in i and len(i)>18: fileList.append(i) otaName = i.split('.') if time2 in i: getOta = i break print 'ota包名'+getOta #没有ota包发送邮件 if getOta == 'false': #发送邮件通知 sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-无刷机版本","hi all:"+"\n"+" "+time2+"无刷机版本!请负责版本编译的开发同学关注。") sys.exit(0) #终止程序 #下载ota包 downloadfile(getOta) return getOta
def ota(): ftp = ftpconnect() ftp.cwd("/work/Doc_For_OSTeam/Doc_For_OSTeam/simg2img/out_ota/w3_60_debug") fileList = [] time = GetLog.getTime('%Y%m%d') print '当前日期' + time getOta = 'false' time2 = time[2:] print time2 for i in ftp.nlst(): if 'zip' in i and len(i) > 18: fileList.append(i) otaName = i.split('.') if time2 in i: getOta = i break print 'ota包名' + getOta #没有ota包发送邮件 if getOta == 'false': #发送邮件通知 sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-无刷机版本", "hi all:" + "\n" + " " + time2 + "无刷机版本!请负责版本编译的开发同学关注。") sys.exit(0) #终止程序 #下载ota包 downloadfile(getOta) return getOta
def work(self, input_items, output_items): in0 = input_items[0] try: if self.counter >= 100: self.isReady = 1 self.counter = 0 else: self.counter = self.counter + 1 for items in input_items: for item in items: if item > self.value: if self.isReady == 1: updateNode.setNode2() sendMail.send() print("on") self.isReady = 0 self.isOn = 1 else: if self.isOn == 1: updateNode.resetNode2() print("off") self.isOn = 0 except: print("error") return len(input_items[0])
def analyzeForNCQ(soup, toMailList): # find new case newCaseTable = soup.find('table', {'id': "table_unassigned"}) if newCaseTable is None: printTime("No New Case exists") return for case_row in newCaseTable.find('tbody').find_all('tr'): case_NoTitle = (case_row.find_all('td'))[0] case_NoTitle_text = (case_row.find_all('td'))[0].text case_sev = (case_row.find_all('td'))[1] case_sbr = (case_row.find_all('td'))[7] if case_NoTitle_text not in newCaseSent: newCaseSent.append(case_NoTitle_text) thead = newCaseTable.find('thead') case_summary = str(thead) + str(case_row) sendMail.send(case_summary, "NCQ", toMailList, FROM_ADDR, FROM_ADDR_PW) printTime("NCQ Case Checked.")
def s_email(self): self.dialog = MDDialog( text="Sending E-Mail", buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color), MDFlatButton(text="DISCARD", text_color=self.theme_cls.primary_color), ], ) self.dialog.open() sendMail.send('mycontacts.txt', 'message.txt', datetime.now().strftime('%Y%m%d') + '.csv', datetime.now().strftime('%Y%m%d')) self.dialog.close()
def launcher(VersionsName, otaVersionsPath): #判断是否进入第二屏 for i in range(30): cmd = os.popen('adb shell dumpsys activity top | ' + seek + ' ACTIVITY').readline() if cmd != None: print '手机进入第二屏' login = True break else: login = False time.sleep(5) if not login: print '手机无法进入第二屏' #发送邮件通知手机无法正常开启 sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-刷机失败", "hi all:" + "\n" + " " + "版本" + VersionsName + "刷机后无法进入系统!" + "\n" + " " + otaVersionsPath) sys.exit(0) #判断是否运行launcher for i in range(30): cmd = os.popen('adb shell dumpsys activity top | ' + seek + ' ACTIVITY').readline() pid = cmd.strip().split(' ')[-1].strip() print pid if 'not running' in pid: lcRun = False time.sleep(5) else: print 'launcher已启动' lcRun = True time.sleep(10) break if not lcRun: print 'launcher未运行' #发送邮件通知手机无法正常运行launcher sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-刷机失败", "hi all:" + "\n" + " " + "版本" + VersionsName + "刷机后无法进入系统!" + "\n" + " " + otaVersionsPath) sys.exit(0)
def contrast(): # 接收人 mailto_list = '**********@**.**,***@**.***' # 附件路径名 filename = './excel/E3+与IWMS库存对比.xlsx' try: # 建立数据库连接 oracle = Oracle(dbtype='oracle', db='E3ZS') mssql = MsSql(dbtype='mssql', db='IWMS') # 执行脚本,并返回数据帧对象 e3 = oracle.get_DataFrame('./sql/E3+inventory.sql') iwms = mssql.get_DataFrame('./sql/IWSinventory.sql') finally: if oracle: del oracle if mssql: del mssql # 通过仓库和SKU进行连接 rs = pd.merge(e3, iwms, how='outer', left_on=['仓库', 'SKU'], right_on=['仓库', 'SKU'], sort=False, suffixes=['_E3', '_IWMS']) # 筛选数量不一致的记录 rs = rs[(rs['库存数量_E3'] != rs['库存数量_IWMS']) | (rs['可用数量_E3'] != rs['可用数量_IWMS'])] # 将结果写入EXCEL writer = pd.ExcelWriter(filename) rs.to_excel(writer, '对比结果', index=False) e3.to_excel(writer, 'E3+库存', index=False) iwms.to_excel(writer, 'IWMS库存', index=False) writer.save() # 保存文件 # 将结果附件通过邮件发送出去 sendMail.send(mailto_list, 'E3+与IWMS库存对比', None, filelist=[filename])
def run(): f = open("logs.txt", "w+") url = "https://www.leboncoin.fr/recherche/?category=15&text=thinkpad&locations=r_12" + "&page=" page = 0 unFind = None list_all_ads = [] while unFind == None: page += 1 try: soup = scrapUrl(url + str(page)) all_ads = soup.find("ul", class_="undefined").find_all("li") list_all_ads = fillTable(all_ads, list_all_ads) except: unFind = soup.find("p", class_="_2fdgs") f.write(str(datetime.datetime.now())) f.write("\n #" + page) df_leboncoin = pd.DataFrame(list_all_ads).dropna(how='any') offres = FindBonneAffaire(df_leboncoin) sendMail.send(offres) f.write("\n Email sent successfully")
def test(): appPackage = ['com.android.settings', 'com.android.browser', 'com.android.calculator2', 'com.android.calendar', 'com.android.camera2', 'com.android.deskclock', 'com.android.contacts', 'com.android.email', 'com.sprd.fileexplorer', 'com.thunderst.radio', 'com.android.gallery3d', 'com.google.android.gm', 'com.google.android.gms', 'com.android.dialer', 'com.android.mms', 'com.android.music', 'com.sprd.note', 'com.android.dialer', 'com.android.vending', 'com.android.quicksearchbox', 'com.android.soundrecorder', 'tran.com.android.taplaota', 'com.android.launcher3', 'com.android.messaging'] str = '' for i in appPackage: os.popen('adb shell monkey -p '+i+' --throttle 500 100') # print 'adb shell monkey -p '+i+' 1' time.sleep(5) cmd = os.popen('adb shell dumpsys activity top | '+seek+' ACTIVITY').readline() if i not in cmd: str += i+'未启动成功,也可能是谷歌应用跳转到登陆界面'+'\n' print i+'未启动成功,也可能是谷歌应用跳转到登陆界面' tester_list = ['*****@*****.**'] sendMail.send(tester_list,u"未启动的应用","hi all:"+"\n"+" 本次测试疑似未启动的应用有:"+"\n"+str)
def launcher(VersionsName,otaVersionsPath): #判断是否进入第二屏 for i in range(30): cmd = os.popen('adb shell dumpsys activity top | '+seek+' ACTIVITY').readline() if cmd != None: print '手机进入第二屏' login = True break; else: login = False time.sleep(5) if not login: print '手机无法进入第二屏' #发送邮件通知手机无法正常开启 sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-刷机失败","hi all:"+"\n"+" "+"版本"+VersionsName+"刷机后无法进入系统!"+"\n"+" " +otaVersionsPath) sys.exit(0) #判断是否运行launcher for i in range(30): cmd = os.popen('adb shell dumpsys activity top | '+seek+' ACTIVITY').readline() pid = cmd.strip().split(' ')[-1].strip() print pid if 'not running' in pid: lcRun = False time.sleep(5) else: print 'launcher已启动' lcRun = True time.sleep(10) break if not lcRun: print 'launcher未运行' #发送邮件通知手机无法正常运行launcher sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-刷机失败","hi all:"+"\n"+" "+"版本"+VersionsName+"刷机后无法进入系统!"+"\n"+" " +otaVersionsPath) sys.exit(0)
def analyzeForFTS(soup, toMailList): # find active fts case ftsCaseTable = soup.find('table', {'id': 'table_fts'}) if ftsCaseTable is None: printTime("No active fts case exists, WoW") return for case_row in ftsCaseTable.find('tbody').find_all('tr'): case_NoTitle = (case_row.find_all('td'))[0] case_NoTitle_text = (case_row.find_all('td'))[0].text case_sev = (case_row.find_all('td'))[1] case_sbt = (case_row.find_all('td'))[3].text case_status = (case_row.find_all('td'))[4].text case_sbr = (case_row.find_all('td'))[8] # will not send WoC fts case if case_status == "WoCustomer": # remove from sent list is to make sure # the case will be send when it move to WoOnwer again if case_NoTitle_text in ftsCaseSent: ftsCaseSent.remove(case_NoTitle_text) continue if case_NoTitle_text not in ftsCaseSent: ftsCaseSent.append(case_NoTitle_text) thead = ftsCaseTable.find('thead') case_summary = str(thead) + str(case_row) sendMail.send(case_summary, "active FTS alert", toMailList, FROM_ADDR, FROM_ADDR_PW) printTime("FTS Case Checked.")
documents = db.HS300.find() for document in documents: stockCodes.append(document['stockcode']) grab_time = ['07-03'] # for i in range(20): # now_time = datetime.datetime.now() # yes_time = now_time + datetime.timedelta(days=-29+i) # grab_time.append(yes_time.strftime('%m-%d')) # Todo:add time.sleep(60*60*24) for stockCode in stockCodes: # stockClose.getStockClose(stockCode) for date in grab_time: produceFactor.getSentimentFactor(stockCode,date) aggregateFactor.getSentimentFactor2(stockCode,date) dailyResult.setDailyResult(stockCode,date) # combine.getPriceAndSentimentFactor(stockCode) # draw.getPic(stockCode) for date in grab_time: outputResult.getDailyResult(date) outputResult.getDailyAttachment(date) for date in grab_time: sendMail.send(date)
# 検索に単語を追加したい場合は「TROUBLE.append("ここに検索したい単語を入れる")」のコメントアウトを削除してください。 # print("↓不具合一覧↓\n") # print(TROUBLE) # TROUBLE.append("ここに検索したい単語を入れる") def trouble_search(file, number): trouble_data = '' for key in TROUBLE: inpe = file[file['不具合情報'].str.match('^.*' + key + '.*$')] inpe_count = len(inpe) if (inpe_count >= 3): inpe.to_csv('to_csv_out_' + number + '_' + key + '.csv') trouble_data = trouble_data + key + "の不具合は" + str( inpe_count) + "回です。\n" print("【機体番号 " + number + " 】\n") print(trouble_data) return inpe_count, trouble_data mailContent = '' for key in MACHINE_NUMBER: inpe = file[file['機番'].str.match('^.*' + key + '.*$')] inpe_count, trouble_data = trouble_search(inpe, key) mailContent = mailContent + "【機体番号 " + key + " 】\n" + trouble_data + "\n" sendMail.send(mailContent) print("メールを送信しました。")
surveyLog = open('log/Survey.txt') for line in csv.reader( surveyLog, dialect="excel-tab" ): #You can also use delimiter="\t" rather than giving a dialect. # print line ### LogFile Overview ### ## 1. ID # 2. BonusCode ## 3. Date # 4. Email ## 5. Choice # 6. FinalStage # if i >= lastLine: ## Check if Email is Valid if i >= int(lastLine) and re.match(r"[^@]+@[^@]+\.[^@]+", line[3]): # print "Send email to:",line[3] # print "new line",i sendMail.send(line[3]) i += 1 surveyLog.close() ### UPDATE LAST LINE-LOG lastLine = i print "new lastLine:", lastLine lineLog = open('log/lastLine.txt', "wb") lineLog.write(str(lastLine)) lineLog.close()
for k in mddict: modules_dict[importlib.import_module(k)] = mddict[k] del mddict def setup_logging(default_path='./conf/logging.json'): if not os.path.exists(default_path): default_path = './conf/logging.json' with open(default_path, 'r') as f: config = json.load(f) logging.config.dictConfig(config) if __name__ == '__main__': im_module() setup_logging() logger = logging.getLogger('error_file') try: # 执行动态模块中的函数,目前默认无参 for k in modules_dict: for met in modules_dict[k]: getattr(k, met)() except Exception as e: try: sendMail.send('*****@*****.**', 'E3+监控程序出错', str(e)) except Exception as e1: logger.exception(e1) logger.exception(e)
def pushVersions(): #下载OTA包 OTA = ftpRun.ota() otaVersionsPath = 'ota包下载地址:ftp://FTP_Talpa:[email protected]/work/Doc_For_OSTeam/Doc_For_OSTeam/simg2img/out_ota/w3_60_debug/' + OTA #判断是否连接上设备 run = wait_for_device(30) if run == 'false': print '刷机前手机连接超时,程序终止' #发邮件提示tester,未识别到手机,检查测试环境 sendMail.send( MailRecipients.tester_list, u"升级异常", "hi all:" + "\n" + " " + "版本" + OTA + "在升级版本前未识别到手机,请检查手机是否已连接,或PC测试环境是否有问题!") sys.exit(0) else: print '手机已连接' #push包到手机内存 print '正push文件' os.popen("adb push " + os.path.join(os.getcwd(), 'versions', OTA) + " sdcard/") print "adb push " + os.path.join(os.getcwd(), 'versions', OTA) + " sdcard/" print 'push结束' #判断手机中是否含有ota包 cmd = os.popen('adb shell ls sdcard/').read() print cmd if OTA in cmd: print '手机中已有ota包' # # 本地调试路径; # os.system('adb install -r '+os.path.join(os.getcwd(),'app','OTAtest1.apk')) # os.system('adb install -r '+os.path.join(os.getcwd(),'app','OTAtest2.apk')) # 傻逼Linux服务器本地路径; os.system('adb install -r /home/zf/桌面/app/OTAtest1.apk') os.system('adb install -r /home/zf/桌面/app/OTAtest2.apk') os.system( 'adb shell am start -n tran.com.android.taplaota/.activity.OtaActivity' ) time.sleep(5) os.system( 'adb shell am instrument -w -r -e debug false -e class com.talpa.ota.ApplicationTest#otaTest com.talpa.ota.test/android.support.test.runner.AndroidJUnitRunner' ) time.sleep(30) #判断是否连接上设备 run = wait_for_device(15) if run == 'false': print '手机连接超时,发送邮件通知并程序终止' #发送邮件通知手机无法进入系统 sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-刷机失败", "hi all:" + "\n" + " " + "版本" + OTA + "刷机后无法进入系统或无法识别设备!" + "\n" + " " + otaVersionsPath) os.system('adb reboot') time.sleep(300) os.system('adb shell rm /sdcard/*.zip') sys.exit(0) #终止程序 else: print '手机已连接' #判断是否进入Launcher launcher(OTA, otaVersionsPath) #判断屏幕是否锁屏 for i in range(5): time.sleep(1) lockScreen = os.popen('adb shell dumpsys power | ' + seek + ' mWakefulness=').readline() if 'Asleep' in lockScreen: print '手机锁屏' os.popen('adb shell input keyevent POWER') #点亮屏幕 else: break #测试启动所有应用 #判断手机是否进入开机后的设置界面 times = 0 while True: cmd = os.popen('adb shell dumpsys activity top | ' + seek + ' ACTIVITY').readline() if 'com.android.settings' not in cmd: print '未进入到开机后的设置界面' os.popen('adb shell am start com.android.settings') time.sleep(15) else: print '手机进入系统界面' break if times == 40: print '系统长时间未进入开机后的设置界面' #发送邮件通知手机无法正常进入开机后界面 sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-刷机失败", "hi all:" + "\n" + " " + "版本" + OTA + "刷机后无法进入系统!" + "\n" + " " + otaVersionsPath) sys.exit(0) times += 1 #获取手机版本 build = os.popen('adb shell getprop ro.build.display.id').readline() fileTime = GetLog.getTime('%Y%m%d') fileName = build.strip() + '_' + fileTime #FTP上的版本目录名称 print '版本文件名:' + fileName if fileTime in build: print '已刷入当天版本' os.system('adb shell rm /sdcard/*.zip') time.sleep(2) os.system('adb shell input keyevent 4') else: print '刷机后不是当天版本' sendMail.send( MailRecipients.tester_list, u"版本刷机报告-刷机失败", "hi all:" + "\n" + " " + "版本" + OTA + "刷机后检测到版本号不是当天的版本!" + "\n" + " " + otaVersionsPath) sys.exit(0) #开启log抓取 # child = subprocess.Popen('python '+os.path.join(os.getcwd(),'GetLog.py')+' -p '+ fileName,shell=True) child = subprocess.Popen( 'python /var/lib/jenkins/workspace/SmokeProject/GetLog.py -p ' + fileName, shell=True) print '开启抓log' #运行启动程序 startApp.test() #关闭log抓取 subprocess.Popen("taskkill /F /T /PID %i" % child.pid, shell=True) print '关闭抓log' os.system('adb reboot') #结束后发邮件 if os.path.exists(os.path.join(os.getcwd(), 'ErrorLog', fileName)): files = os.listdir(os.path.join(os.getcwd(), 'ErrorLog', fileName)) print files errorsFile = len(files) errorsNumber = 0 if errorsFile == 0: print '没有报错文件' sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-刷机成功", "hi all:" + "\n" + " " + "版本" + OTA + "刷机成功!所有应用启动正常。" + "\n" + " " + otaVersionsPath) if OTA != 'false': createOtaFile(OTA) ftpRun.uploadOtaFile() else: errorPath = '' for i in files: if '.zip' in i: errorsNumber += 1 packageName = i.split('_')[0] if packageName == 'none': errorPath += '应用报错' + '\n' + 'ftp://*****:*****@10.250.1.88/Log/' + fileName + '/' + i + '\n' else: errorPath += '应用' + packageName + '报错' + '\n' + 'ftp://*****:*****@10.250.1.88/Log/' + fileName + '/' + i + '\n' print '有报错文件' sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-刷机成功", "hi all:" + "\n" + " " + "版本" + OTA + "刷机成功!启动所有应用过程共出现" + str(errorsNumber) + "次报错。" + "\n" + " " + otaVersionsPath + "\n" + "对应应用报错log地址如下:" + "\n" + errorPath) else: print '没有报错文件' sendMail.send( MailRecipients.mailto_list, u"版本刷机报告-刷机成功", "hi all:" + "\n" + " " + "版本" + OTA + "刷机成功!所有应用启动正常。" + "\n" + " " + otaVersionsPath) if OTA != 'false': createOtaFile(OTA) ftpRun.uploadOtaFile() else: print '无ota包'
def listen(): try: connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) connection.bind(('0.0.0.0', int(sys.argv[1]))) connection.listen(10) while True: current_connection, address = connection.accept() while True: # generate IV for AES encryption IV = aescbc.generateIV(AES_BLOCK_SIZE) current_connection.send(IV) IV = IV[:16] # because of some strange things #print(bcolors.color.HEADER + "--- Generated IV for AES ---\n" + bcolors.color.ENDC + IV + "\n") datalength = current_connection.recv(6) # print(bcolors.color.HEADER + "--- Now receiving json of this datalength ---\n" + bcolors.color.ENDC + datalength + "\n") # getting value of the stream that will be send from client data = current_connection.recv(int(datalength)) #print(bcolors.color.OKBLUE + "--- Encryted string ---\n" + bcolors.color.ENDC + data + "\n") # decrypting the data auth = credentials.getAUTH() data = aescbc.decrypt(data, auth, IV) #print(bcolors.color.OKBLUE + "--- Got this data ---\n" + bcolors.color.ENDC + data + "\n") if data.startswith("getServerData"): json = jsonHandler.buildJSON() jsonpad = aescbc.generatePadding(json) jsonencrypt = aescbc.encrypt(jsonpad, auth, IV) current_connection.send(jsonencrypt) #print(bcolors.color.OKGREEN + "--- Sent this encrypted data to server ---\n" + bcolors.color.ENDC) current_connection.shutdown(1) current_connection.close() print(bcolors.color.WARNING + "--- Closed connection ---\n" + bcolors.color.ENDC) break else: print(bcolors.color.OKBLUE + "--- Client sent this data ---\n" + bcolors.color.ENDC + data + "\n") sqlId, product, requester, price, dates, done = jsonHandler.parseJSON( data) # getting parsed data from json send from app credit = sqlHandler.getCreditSQL() # get the actual credit credit -= price # new credit if done is 0: resultState = sqlHandler.insertIntoSQL( credit, product, requester, price, dates, done) # inserting date into SQL database if resultState == 1: # send Email about entry only in case of success sendMail.send(credit, product, requester, price, dates, done) elif done is 1: sqlHandler.updateSQL( sqlId) # updating entry to done in SQL database current_connection.shutdown(1) current_connection.close() print(bcolors.color.WARNING + "--- Closed connection ---\n" + bcolors.color.ENDC) break sleep(1) except Exception as e: print(bcolors.color.FAIL + str(e) + bcolors.color.ENDC) print( bcolors.color.FAIL + "Either the data is empty or an other error occured getting data" + bcolors.color.ENDC) current_connection.shutdown(1) current_connection.close()
#!/usr/bin/python import sys, os import json import sendMail print "Content-type: text/plain;charset=utf-8\n" try: #extract the input variables to json myjson = json.load(sys.stdin) name = myjson["name"] if 'email' in myjson: email = myjson["email"] else: email = "no email provided" subject = myjson["subject"] message = myjson["message"] import emailConfig to = emailConfig.to message = 'New scaliseprep.com contact form submission.\nName: ' + name + '\nEmail: ' + email + '\nSubject: ' + subject + '\nMessage: ' + message sendMail.send(to, subject, message) print '{"success":true}' #message sent successfully except Exception as e: print(e) print '{"success":false}' #message send failed
myresult = mycursor.fetchone() if not myresult: print '{"success":false,"failureMode":"user"}' #no user found matching username mycursor.close() mydb.close() else: #user with username found uid = myresult[0] #get email for this user sqlEmail = "SELECT * FROM email WHERE id =%s" u = (uid, ) mycursor.execute(sqlEmail, u) emailResult = mycursor.fetchone()[1] if emailResult: #get email for this user sqlPwrd = "SELECT * FROM password WHERE id =%s" u = (uid, ) mycursor.execute(sqlPwrd, u) pwrd = mycursor.fetchone()[1] to = emailResult message = 'You requested your Scalise Prep password, it is:\n' + pwrd sendMail.send(to, "Scalise Prep Password", message) print '{"success":true}' else: print '{"success":false,"failureMode":"email"}' #no user found matching username mycursor.close() mydb.close() except Exception as e: print sys.exc_info()[-1].tb_lineno print(repr(e))
# Add the ending "new" if the file already exists. if os.path.exists(def_path + u'folder_{0}/{1}.cfg'.format(ip, today_date)): today_date = today_date + '_new' # Download config. Or not. if not upload_to_tftp(ip, today_date, users): report += 'Unknow error with backup on {0}\n ------------------------ \n'.format( ip) continue # Check if the files are different, and if not, delete the downloaded file. if len(os.listdir(full_path)) > 1: f = files_in_dir(full_path) difference = diff(full_path, f[0], f[1]) if difference: report += '!!Config has been changed on switch {0} \n'.format(ip) report += difference else: if len(f) == 2: print('Duplicate deleted from folder {0}'.format(full_path)) os.remove(full_path + '/' + f[0]) print 'Backup on {0} completed \n'.format(ip), '-' * 35 report += 'Backup on {0} completed \n ------------------------ \n'.format( ip) # Send the report by email. report += 'End of report\n'.format(ip) send(report, mail)
#!/usr/bin/env python3 import os import sys from datetime import * import prepareData import sendMail import getYesterdaysData os.chdir(os.path.dirname(sys.argv[0])) #Get todays Date today = date.today() # Yesterday date yesterday = today - timedelta(days=1) #Adjust to linkformat year = str(yesterday.year) month = str( yesterday.month) if yesterday.month >= 10 else "0" + str(yesterday.month) day = str(yesterday.day) if yesterday.day >= 10 else "0" + str(yesterday.day) print(yesterday) print('Call getYesterdaysData') getYesterdaysData.get(year, month, day) print('Call preData') prepareData.prepData(year, month, day) print('Call Send') sendMail.send(year, month, day)
# stockCodes = ['000001','000002','000009','000027','000039','000046','000060','000061','000063','000069'] client = MongoClient() db = client['stockcodes'] documents = db.HS300.find() for document in documents: stockCodes.append(document['stockcode']) grab_time = ['07-03'] # for i in range(20): # now_time = datetime.datetime.now() # yes_time = now_time + datetime.timedelta(days=-29+i) # grab_time.append(yes_time.strftime('%m-%d')) # Todo:add time.sleep(60*60*24) for stockCode in stockCodes: # stockClose.getStockClose(stockCode) for date in grab_time: produceFactor.getSentimentFactor(stockCode, date) aggregateFactor.getSentimentFactor2(stockCode, date) dailyResult.setDailyResult(stockCode, date) # combine.getPriceAndSentimentFactor(stockCode) # draw.getPic(stockCode) for date in grab_time: outputResult.getDailyResult(date) outputResult.getDailyAttachment(date) for date in grab_time: sendMail.send(date)
user=config.username, passwd=config.password, database="myMembers" ) #request any user with input username mycursor = mydb.cursor() sql = "SELECT * FROM username WHERE username =%s" u = (usr, ) mycursor.execute(sql, u) myresult = mycursor.fetchone() if not myresult: #send alert message to admin to indicate new signup to = emailConfig.to sendMail.send(to,'New User Signup','Hi Admin,\n\nCongrats! A new user "'+usr+'" just signed up!\n\nSincerely,\nYour trusty automated scaliseprep.com website') #create a new user entry in the database sql = "INSERT INTO username (username) VALUES (%s);" val = (usr, ) mycursor.execute(sql, val) mydb.commit() #get the new user id uid = mycursor.lastrowid #fill in the remaining fields #password sql = "INSERT INTO password (id, password) VALUES (%s, %s);" val = (uid, pwrd) mycursor.execute(sql, val) mydb.commit() #email
def Mail(emailID): sendMail.send(emailID)
def pushVersions(): #下载OTA包 OTA = ftpRun.ota() otaVersionsPath = 'ota包下载地址:ftp://FTP_Talpa:[email protected]/work/Doc_For_OSTeam/Doc_For_OSTeam/simg2img/out_ota/w3_60_debug/'+OTA #判断是否连接上设备 run = wait_for_device(30) if run == 'false': print '刷机前手机连接超时,程序终止' #发邮件提示tester,未识别到手机,检查测试环境 sendMail.send(MailRecipients.tester_list,u"升级异常","hi all:"+"\n"+" "+"版本"+OTA+"在升级版本前未识别到手机,请检查手机是否已连接,或PC测试环境是否有问题!") sys.exit(0) else: print '手机已连接' #push包到手机内存 print '正push文件' os.popen("adb push "+os.path.join(os.getcwd(),'versions',OTA)+" sdcard/") print "adb push "+os.path.join(os.getcwd(),'versions',OTA)+" sdcard/" print 'push结束' #判断手机中是否含有ota包 cmd = os.popen('adb shell ls sdcard/').read() print cmd if OTA in cmd: print '手机中已有ota包' # # 本地调试路径; # os.system('adb install -r '+os.path.join(os.getcwd(),'app','OTAtest1.apk')) # os.system('adb install -r '+os.path.join(os.getcwd(),'app','OTAtest2.apk')) # 傻逼Linux服务器本地路径; os.system('adb install -r /home/zf/桌面/app/OTAtest1.apk') os.system('adb install -r /home/zf/桌面/app/OTAtest2.apk') os.system('adb shell am start -n tran.com.android.taplaota/.activity.OtaActivity') time.sleep(5) os.system('adb shell am instrument -w -r -e debug false -e class com.talpa.ota.ApplicationTest#otaTest com.talpa.ota.test/android.support.test.runner.AndroidJUnitRunner') time.sleep(30) #判断是否连接上设备 run = wait_for_device(15) if run == 'false': print '手机连接超时,发送邮件通知并程序终止' #发送邮件通知手机无法进入系统 sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-刷机失败","hi all:"+"\n"+" "+"版本"+OTA+"刷机后无法进入系统或无法识别设备!"+"\n"+" " +otaVersionsPath) os.system('adb reboot') time.sleep(300) os.system('adb shell rm /sdcard/*.zip') sys.exit(0) #终止程序 else: print '手机已连接' #判断是否进入Launcher launcher(OTA,otaVersionsPath) #判断屏幕是否锁屏 for i in range(5): time.sleep(1) lockScreen = os.popen('adb shell dumpsys power | '+seek+' mWakefulness=').readline() if 'Asleep' in lockScreen: print '手机锁屏' os.popen('adb shell input keyevent POWER') #点亮屏幕 else: break #测试启动所有应用 #判断手机是否进入开机后的设置界面 times = 0 while True: cmd = os.popen('adb shell dumpsys activity top | '+seek+' ACTIVITY').readline() if 'com.android.settings' not in cmd: print '未进入到开机后的设置界面' os.popen('adb shell am start com.android.settings') time.sleep(15) else: print '手机进入系统界面' break if times == 40: print '系统长时间未进入开机后的设置界面' #发送邮件通知手机无法正常进入开机后界面 sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-刷机失败","hi all:"+"\n"+" "+"版本"+OTA+"刷机后无法进入系统!"+"\n"+" " +otaVersionsPath) sys.exit(0) times += 1 #获取手机版本 build = os.popen('adb shell getprop ro.build.display.id').readline() fileTime = GetLog.getTime('%Y%m%d') fileName = build.strip()+'_'+fileTime #FTP上的版本目录名称 print '版本文件名:'+ fileName if fileTime in build: print '已刷入当天版本' os.system('adb shell rm /sdcard/*.zip') time.sleep(2) os.system('adb shell input keyevent 4') else: print '刷机后不是当天版本' sendMail.send(MailRecipients.tester_list,u"版本刷机报告-刷机失败","hi all:"+"\n"+" "+"版本"+OTA+"刷机后检测到版本号不是当天的版本!"+"\n"+" " +otaVersionsPath) sys.exit(0) #开启log抓取 # child = subprocess.Popen('python '+os.path.join(os.getcwd(),'GetLog.py')+' -p '+ fileName,shell=True) child = subprocess.Popen('python /var/lib/jenkins/workspace/SmokeProject/GetLog.py -p '+ fileName,shell=True) print '开启抓log' #运行启动程序 startApp.test() #关闭log抓取 subprocess.Popen("taskkill /F /T /PID %i"%child.pid , shell=True) print '关闭抓log' os.system('adb reboot') #结束后发邮件 if os.path.exists(os.path.join(os.getcwd(),'ErrorLog',fileName)): files = os.listdir(os.path.join(os.getcwd(),'ErrorLog',fileName)) print files errorsFile = len(files) errorsNumber = 0 if errorsFile == 0: print '没有报错文件' sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-刷机成功","hi all:"+"\n"+" "+"版本"+OTA+"刷机成功!所有应用启动正常。"+"\n"+" " +otaVersionsPath) if OTA != 'false': createOtaFile(OTA) ftpRun.uploadOtaFile() else: errorPath = '' for i in files: if '.zip' in i: errorsNumber += 1 packageName = i.split('_')[0] if packageName == 'none': errorPath += '应用报错' +'\n'+'ftp://*****:*****@10.250.1.88/Log/'+fileName+'/'+i+'\n' else: errorPath += '应用'+packageName+'报错' +'\n'+'ftp://*****:*****@10.250.1.88/Log/'+fileName+'/'+i+'\n' print '有报错文件' sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-刷机成功","hi all:"+"\n"+" "+"版本"+OTA+"刷机成功!启动所有应用过程共出现"+str(errorsNumber)+"次报错。"+"\n"+" " +otaVersionsPath+"\n"+"对应应用报错log地址如下:"+"\n"+errorPath) else: print '没有报错文件' sendMail.send(MailRecipients.mailto_list,u"版本刷机报告-刷机成功","hi all:"+"\n"+" "+"版本"+OTA+"刷机成功!所有应用启动正常。"+"\n"+" " +otaVersionsPath) if OTA != 'false': createOtaFile(OTA) ftpRun.uploadOtaFile() else: print '无ota包'