def sendemail(test_Report_path): # 第20次执行用例,主动报告测试情况 try: value = GlobalVariable.get_value() except: log.error(u"Runner fail =》Report.py,result error") run_case_total, run_pass_total, run_failures_total, run_error_total = GlobalVariable.parsing_string(value) log.warning("run_case_total:%s" % str(run_case_total)) log.warning("run_error_total:%s" % str(run_error_total)) log.warning("run_failures_total:%s" % str(run_failures_total)) log.warning("run_pass_total:%s" % str(run_pass_total)) sendemail = Run.email send_who = Run.send_who times = GlobalVariable.get_times() log.debug("times:%s" % times) send_msg = 'send_email=> fail' send_mail_msg = 'send_email=> No' if sendemail in 'true': try: send_mail(test_Report_path, send_who) except Exception as msg: log.error(send_msg) log.error(msg) raise msg elif sendemail in 'misc': if times in [49, 50]: try: send_mail(test_Report_path, send_who) except Exception as msg: log.error(send_msg) log.error(msg) raise msg elif run_error_total != '0' or run_failures_total != '0': try: send_mail(test_Report_path, send_who) except Exception as msg: log.error(send_msg) log.error(msg) elif send_who != 'Null': try: send_mail(test_Report_path, send_who) except Exception as msg: log.error(send_msg) log.error(msg) raise msg else: log.warning(send_mail_msg) else: log.warning(send_mail_msg)
def pointOperateRecordsShow(mac): params = { "source": 1, "mac": mac, "pageSize": GlobalVariable.records_num, "currentPage": 1 } point_records = [] res = requests.get(GlobalVariable.jd_base_url + "pointOperateRecords:show", params=params, headers=GlobalVariable.headers) if res.status_code == 200: res_json = res.json() result = res_json["result"] pointRecords = result["pointRecords"] for pointRecord in pointRecords: recordType = pointRecord["recordType"] pointAmount = pointRecord["pointAmount"] createTime = pointRecord["createTime"] createTime_str = datetime.datetime.fromtimestamp( createTime / 1000).strftime("%Y-%m-%d") point_record = { "recordType": recordType, "pointAmount": pointAmount, "createTime": createTime_str } point_records.append(point_record) index = GlobalVariable.findALocation(mac) if index != -1: point_info = GlobalVariable.final_result["pointInfos"][index] point_info.update({"pointRecords": point_records}) else: print("Request pointOperateRecordsShow failed!")
def routerAccountInfo(mac): params = { "mac": mac, } res = requests.get(GlobalVariable.jd_base_url + "routerAccountInfo", params=params, headers=GlobalVariable.headers) if res.status_code == 200: res_json = res.json() result = res_json["result"] accountInfo = result["accountInfo"] mac = accountInfo["mac"] amount = accountInfo["amount"] bindAccount = accountInfo["bindAccount"] GlobalVariable.service_headers["pin"] = quote(bindAccount) recentExpireAmount = accountInfo["recentExpireAmount"] recentExpireTime = accountInfo["recentExpireTime"] recentExpireTime_str = datetime.datetime.fromtimestamp( recentExpireTime / 1000).strftime("%Y-%m-%d %H:%M:%S") account_info = { "amount": str(amount), "bindAccount": str(bindAccount), "recentExpireAmount": str(recentExpireAmount), "recentExpireTime": recentExpireTime_str } index = GlobalVariable.findALocation(mac) if index != -1: point_info = GlobalVariable.final_result["pointInfos"][index] point_info.update(account_info) else: print("Find mac failure!") else: print("Request routerAccountInfo failed!")
def generate_report(cls, test_dir, test_Report_path): """ 主套件执行方法 :param test_dir: :param test_Report_path: :return: """ try: test_dir = str(test_dir) test_Report_path = str(test_Report_path) now = datetime.datetime.now().strftime("%Y%m%d.%H%M%S.%f")[:-4] filename = test_Report_path + now + '_report.html' fp = open(filename, 'wb') if report in 'true' or report == '': name = '' if Main in 'ui': name = "UI Automated test report" elif Main in 'api': name = "API Automated test report" # 定义测试报告 runner = HTMLTestRunner(stream=fp, title=name, description='General situation of testcase') log.debug(u'BY=>HtmlTestRunner') elif report in 'false': runner = unittest.TextTestRunner() log.debug('BY=>Unittest') # 控制执行路径 result = '<unittest.runner.TextTestResult run=0 errors=0 failures=0>' if os.listdir(test_dir): discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py') r = runner.run result = r(discover) log.debug(result) else: log.warning(u'test_dir is empty') # 传递运行结果 GlobalVariable.set_value(result, report) except Exception as msg: log.error(u'Runner=》ERROR') raise msg finally: fp.close()
def generate_report(cls, test_dir, test_Report_path): """ 主套件执行方法 :param test_dir: :param test_Report_path: :return: """ try: test_dir = str(test_dir) test_Report_path = str(test_Report_path) now = datetime.datetime.now().strftime("%Y%m%d.%H%M%S.%f")[:-4] filename = test_Report_path + now + '_report.html' fp = open(filename, 'wb') if report in 'true': name = '' if Main in 'ui': name = "UI Automated test report" elif Main in 'api': name = "API Automated test report" # 定义测试报告 runner = HTMLTestRunner(stream=fp, title=name, description='General situation of testcase') log.debug(u'BY=>HtmlTestRunner') elif report in 'false': runner = unittest.TextTestRunner() log.debug('BY=>Unittest') # 控制执行路径 result = '<unittest.runner.TextTestResult run=0 errors=0 failures=0>' if os.listdir(test_dir): discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py') r = runner.run result = r(discover) log.debug(result) else: log.warning(u'test_dir is empty') # 传递运行结果 GlobalVariable.set_value(result, report) except Exception as msg: log.error(u'Runner=》ERROR') raise msg finally: fp.close()
def run(self): GlobalVariable.log("consume start Time:"+"\t"+str(time.time())+"\n") #time.sleep(1) while(not GlobalVariable.finishSniffing or not GlobalVariable.dnsResponseQueue.empty()): if (not GlobalVariable.dnsResponseQueue.empty()): print "CONSUMER EMPTY dns" continue dnsResponse = GlobalVariable.dnsResponseQueue.get() if dnsResponse == "END OF THE SYSTEM": break flowValue = dnsResponse if len(self.growingTreeArray) > 0: print "growingTree is larger than 0" flag = False print "DEBUG 1" for growingTree in self.growingTreeArray: #if not growingTree.isActivatedtivated(): #continue ifAppended = growingTree.tryAddingNode(flowValue) if ifAppended == True: flag = True break else: pass print "DEBUG 2", flag if flag == False: if flowValue[10] != "": continue self.growingTreeIndex += 1 GlobalVariable.log("flag == False"+"\t"+str(self.growingTreeIndex)+"\t"+str(flowValue)+"\n") print "flag == False", self.growingTreeIndex, flowValue ts = time.time() growingTree = GrowingTree.GrowingTree(self.growingTreeIndex,flowValue, ts, parent = self) with self.lock: self.growingTreeArray.append(growingTree) else: print "growingTree is equal to 0" if flowValue[10] != "": continue self.growingTreeIndex += 1 GlobalVariable.log("no trees"+"\t"+str(self.growingTreeIndex)+"\t"+str(flowValue)) print "no trees", self.growingTreeIndex, flowValue ts = time.time() growingTree = GrowingTree.GrowingTree(self.growingTreeIndex,flowValue, ts, parent = self) with self.lock: self.growingTreeArray.append(growingTree) print "loop loop loop", GlobalVariable.finishSniffing, GlobalVariable.dnsResponseQueue.empty() print "not stucked any more" GlobalVariable.log(str(len(self.growingTreeArray))+"\t"+str(self.growingTreeIndex)) print len(self.growingTreeArray), self.growingTreeIndex print "the end of consume"
def run(self): GlobalVariable.log("sniff start Time:"+"\t"+str(time.time())+"\n") if self.targetInputMethod == "-i": self.__sniff_online(self.targetInputValue) pass elif self.targetInputMethod == "-p": self.__sniff_offline(self.targetInputValue) pass elif self.targetInputMethod == "-d": filelist = self.__target_files(self.targetInputValue) for filename in filelist: print filename self.__sniff_offline(filename) print "going to finish sniff" GlobalVariable.finishSniffing = True GlobalVariable.httpRequestQueue.put("END OF THE SYSTEM") GlobalVariable.dnsResponseQueue.put("END OF THE SYSTEM") GlobalVariable.smtpQueue.put("END OF THE SYSTEM") GlobalVariable.ftpQueue.put("END OF THE SYSTEM")
def run(self): #print "watchdog thread is running" remainingTime = 5 while remainingTime > 0: #print "watchdog thread is in the loop" if True: if self.queue.empty(): pass else: #print "watchDog queueSize Before ", self.queue.qsize() num = self.queue.get() #print "watchDog queueSize After ", self.queue.qsize() remainingTime = 5 #self.queue.task_done() #print "Consumed", num #print "remainingTime: ", remainingTime remainingTime -= 1 time.sleep(1) GlobalVariable.log("watchDog set threadEvent\n") #print "watchDog thread is going to finish" #self.threadEvent.set() self.parent.watchDogCallBack()
def routerActivityInfo(mac): params = { "mac": mac, } res = requests.get(GlobalVariable.jd_base_url + "router:activityInfo", params=params, headers=GlobalVariable.headers) if res.status_code == 200: res_json = res.json() result = res_json["result"] # finishActivity = result["finishActivity"] totalIncomeValue = result["routerUnderwayResult"]["totalIncomeValue"] satisfiedTimes = result["routerUnderwayResult"]["satisfiedTimes"] activity_info = {"mac": mac, "totalIncomeValue": totalIncomeValue, "satisfiedTimes": satisfiedTimes} index = GlobalVariable.findALocation(mac) if index != -1: point_info = GlobalVariable.final_result["pointInfos"][index] point_info.update(activity_info) else: print("Request routerActivityInfo failed!")
def __init__(self, stabilizedTree): self.hitTimes = 1 self.flow = stabilizedTree.flow self.ts = stabilizedTree.ts self.flowArray = stabilizedTree.flowArray self.dst = [] self.srcport = [] #self.host = [] self.t2ld = [] self.uri = [] self.packetIndex = [] for item in self.flowArray: if item[0] == "request": dst = item[3] srcport = item[4] t2ld = GlobalVariable.hostnameTop2LevelDomain(item[6]) uri = item[7] packetIndex = item[11] if dst != "": self.dst.append(dst) if srcport != "": self.srcport.append(srcport) if t2ld != "": self.t2ld.append(t2ld) if uri != "": self.uri.append(uri) self.packetIndex.append(packetIndex) if item[0] == "dnsresponse": self.packetIndex.append(item[8]) self.dst = set(self.dst) self.srcport = set(self.srcport) self.t2ld = set(self.t2ld) self.uri = set(self.uri) self.packetIndex = set(self.packetIndex) def show(self): return self.flow
def run(self): GlobalVariable.log("consume start Time:"+"\t"+str(time.time())+"\n") #time.sleep(1) while(not GlobalVariable.finishSniffing or not GlobalVariable.httpRequestQueue.empty()): #print "coming AAAAAAAAAAA" if (GlobalVariable.httpRequestQueue.empty()): #print "CONSUMER EMPTY http" continue httpRequest = GlobalVariable.httpRequestQueue.get() if httpRequest == "END OF THE SYSTEM": break flowValue = httpRequest if len(self.growingTreeArray) > 0: #print "growingTree is larger than 0" flag = False #print "DEBUG 1" for growingTree in self.growingTreeArray: #if not growingTree.isActivatedtivated(): #continue ifAppended = growingTree.tryAddingNode(flowValue) if ifAppended == True: flag = True break else: pass #print "DEBUG 2", flag if flag == False: if flowValue[10] != "": continue GlobalVariable.log("flag == False"+"\t"+str(self.growingTreeIndex)+"\t"+str(flowValue)+"\n") print "flag == False", self.growingTreeIndex, flowValue ts = time.time() growingTree = GrowingTree.GrowingTree(self.growingTreeIndex,flowValue, ts, parent = self) with self.lock: self.growingTreeArray.append(growingTree) self.growingTreeIndex += 1 else: #print "growingTree is equal to 0" if flowValue[10] != "": continue GlobalVariable.log("no trees"+"\t"+str(self.growingTreeIndex)+"\t"+str(flowValue)) #print "no trees", self.growingTreeIndex, flowValue ts = time.time() growingTree = GrowingTree.GrowingTree(self.growingTreeIndex,flowValue, ts, parent = self) with self.lock: self.growingTreeArray.append(growingTree) self.growingTreeIndex += 1 #print "loop loop loop", GlobalVariable.finishSniffing, GlobalVariable.httpRequestQueue.empty() pass # add join here for growingTree in self.growingTreeArray: #print "number of growing Tree:", len(self.growingTreeArray) growingTree.__join__() time.sleep(5) print "not stucked any more" GlobalVariable.log(str(len(self.growingTreeArray))+"\t"+str(self.growingTreeIndex)) #print len(self.growingTreeArray) print "the end of consume"
def __compare_http_http(self, flow, item): if (item[4] != "" and flow[4] == item[4]) or (item[8] != "" and flow[10] == item[8]) or (item[7] != "" and item[7] != "/" and flow[7] == item[7]) or (item[6] != "" and flow[6] == item[6]) or (item[3] != "" and flow[3] == item[3]) or (item[6] != "" and GlobalVariable.hostnameTop2LevelDomain(flow[6]) == GlobalVariable.hostnameTop2LevelDomain(item[6])): if abs(float(flow[1]) - float(item[1])) > 10: #flagLargerThanFive = False #print "going to return false" return False self.flowArray.append(flow) #if "apple" in ",".join(flow) and "microsoft" in ",".join(item): #if "apple" in flow[6]: #print "growing tree append:", flow, item if self.queue.empty(): self.queue.put(1) return True else: return False
def modify(self, uc_, addr_, size_, value_): GlobalVariable().modify(uc_, addr_, size_, value_) return
def getControlDevice(mac, i): feed_id = GlobalVariable.device_list[mac]["feed_id"] url = GlobalVariable.jd_service_url + "controlDevice" body = GlobalVariable.service_body % (feed_id, GlobalVariable.cmds[i]) GlobalVariable.service_headers["Authorization"] = str( getAuthorization(body, GlobalVariable.accessKey)) res = requests.post(url, params=GlobalVariable.service_pram, headers=GlobalVariable.service_headers, data=body) control_device = {} if res.status_code == 200 and res.json()["result"] is not None: res = res.json() result = json.loads(res["result"]) streams = result["streams"][0] current_value = json.loads(streams["current_value"]) data = current_value["data"] if i == 0: # 连接的设备列表 # print(data) pass elif i == 1: # 上传与下载 upload = data["upload"] download = data["download"] bandwidth = data["bandwidth"] elif i == 2: # 运行信息 mac = data["mac"] rom = data["rom"] sn = data["sn"] upload = data["upload"] download = data["download"] romType = data["romType"] model = data["model"] cpu = data["cpu"] onlineTime = data["onlineTime"] wanip = data["wanip"] mem = data["mem"] upload_str = "" download_str = "" if int(upload) < 10240: upload_str = str(round(int(upload) / 10)) + "KB/s" download_str = str(round(int(download) / 10)) + "KB/s" else: upload_str = str(round(int(upload) / 10 / 1024, 2)) + "MB/s" download_str = str(round(int(upload) / 10 / 1024, 2)) + "MB/s" control_device = { "rom": rom, "speed": "↑%s ↓%s" % (upload_str, download_str), "cpu": cpu + "%", "onlineTime": calculatingTime(onlineTime), "wanip": wanip, "model": model } elif i == 3: # 插件版本 if isinstance(data, str): print("无法获取插件信息!") print("信息如下:", data) control_device = {"pluginInfo": False} else: pcdn_list = data["pcdn_list"] pcdn_st = pcdn_list[0] status = pcdn_st["status"] nickname = pcdn_st["nickname"] name = pcdn_st["name"] cache_size = pcdn_st["cache_size"] extstorage_exist = data["extstorage_exist"] extstorage_enable = data["extstorage_enable"] board = data["board"] control_device = { "pluginInfo": True, "status": status, "nickname": nickname, "pcdnname": name, "cache_size": str(round(int(cache_size) / 1000000, 2)) + "GB" } else: control_device = {"pluginInfo": False} print("Request getControlDevice failed!") index = GlobalVariable.findALocation(mac) if index != -1: point_info = GlobalVariable.final_result["pointInfos"][index] point_info.update(control_device) else: print("Find mac failure!")
def merge_new(treeFeature): #print "in the merge now" flowTuble = (treeFeature.dst, treeFeature.srcport, treeFeature.t2ld, treeFeature.uri, treeFeature.packetIndex, treeFeature.hitTimes) flag = False for iterator, item in enumerate(TreeComparator.treeFeatureArray): tempFlag = False for i in range(5): if (len(flowTuble[i]) != 0 and (flowTuble[i] & item[i])): if set(['/']) == (flowTuble[i] & item[i]): tempFlag = False else: #print "bingo", flowTuble[i], item[i] tempFlag = True if tempFlag == True: TreeComparator.treeFeatureArray[iterator] = TreeComparator.combine(item, flowTuble) flag = True GlobalVariable.log("matched tree feature array:"+"\t"+str(item)+"\n") break #if flowTuble in TreeComparator.treeFeatureArray: if flag == True: GlobalVariable.log("match\n") #print "match" #treeFeature.show() pass else: GlobalVariable.log("unmatch\n") #print "unmatched ", flowTuble #treeFeature.show() (TreeComparator.treeFeatureArray).append(flowTuble) #GlobalVariable.log(str(treeFeature.flow[0])+"|"+str(treeFeature.flow[1])+"|"+str(treeFeature.flow[2])+"|"+str(treeFeature.flow[3])+"|"+str(treeFeature.flow[4])+"|"+str(treeFeature.flow[5])+"|"+str(treeFeature.flow[6])+"|"+str(treeFeature.flow[7])+"|"+str(treeFeature.flow[8])+"|"+str(treeFeature.flow[9])+"|"+str(treeFeature.flow[10])+"|"+str(treeFeature.flow[11])+"\n") #GlobalVariable.log("tree feature array:"+"\t"+str(TreeComparator.index)+"\t"+str(treeFeature.flow)+"\n") #print "tree feature array:", TreeComparator.index, treeFeature.flow TreeComparator.index += 1 GlobalVariable.log("merge ends"+"|"+str(len(TreeComparator.treeFeatureArray))+"|"+str(TreeComparator.treeFeatureArray)+"\n") GlobalVariable.log("duration:"+"\t"+str(time.time() - treeFeature.ts)+"\n") #print "merge ends", len(TreeComparator.treeFeatureArray), TreeComparator.treeFeatureArray #print "duration:", time.time() - treeFeature.ts durationList.append(time.time() - treeFeature.ts) GlobalVariable.log("average duration:"+"\t"+str(sum(durationList)/len(durationList))+"\n") GlobalVariable.log("end Time:"+"\t"+str(time.time())+"\n")
def getControlDevice(mac,i): feed_id = GlobalVariable.device_list[mac]["feed_id"] url = GlobalVariable.jd_service_url + "controlDevice" body = GlobalVariable.service_body%(feed_id,GlobalVariable.cmds[i]) GlobalVariable.service_headers["Authorization"] = str(getAuthorization(body,GlobalVariable.accessKey)) res = requests.post(url, params=GlobalVariable.service_pram, headers=GlobalVariable.service_headers, data=body) control_device = {} if res.status_code == 200 and res.json()["result"] is not None: res = res.json() result = json.loads(res["result"]) streams = result["streams"][0] current_value = json.loads(streams["current_value"]) if current_value.get("data"): data = current_value["data"] if i == 0: # 连接的设备列表 # print(data) pass elif i == 1: # 上传与下载 upload = data["upload"] download = data["download"] bandwidth = data["bandwidth"] elif i == 2: # 运行信息 if isinstance(data, str): print("无法获取运行信息!") print("信息如下:", data) control_device.update({"runInfo": False}) mac = data["mac"] rom = data["rom"] sn = data["sn"] upload = data["upload"] download = data["download"] romType = data["romType"] model = data["model"] cpu = data["cpu"] onlineTime = data["onlineTime"] wanip = data["wanip"] mem = data["mem"] upload_str = "" download_str = "" if int(upload) < 10240: upload_str = str(round(int(upload)/10)) + "KB/s" download_str = str(round(int(download)/10)) + "KB/s" else: upload_str = str(round(int(upload)/10/1024,2)) + "MB/s" download_str = str(round(int(download)/10/1024,2)) + "MB/s" control_device.update({"runInfo": True,"rom":rom,"speed":"↑%s ↓%s"%(upload_str,download_str),"cpu":cpu + "%","onlineTime":calculatingTime(onlineTime),"wanip":wanip,"model":model}) elif i == 3: # 插件版本 if isinstance(data,str): print("无法获取插件信息!") print("信息如下:",data) control_device.update({"pluginInfo":False}) else: pcdn_list = data["pcdn_list"] # print(pcdn_list) status = "" # name = "" cache_size = "" for pcdn_st in pcdn_list: status += f'''{pcdn_st["nickname"]}({pcdn_st["status"]}) ''' # name += f'''{pcdn_st["nickname"]}({pcdn_st["name"]}) ''' cache_size += f'''{pcdn_st["nickname"]}({str(round(int(pcdn_st["cache_size"])/1048/1000,2))}GB) ''' extstorage_exist = data["extstorage_exist"] extstorage_enable = data["extstorage_enable"] #board = data["board"] //delete useless code control_device.update({"pluginInfo":True,"status":status,"cache_size":cache_size}) elif current_value.get("msg"): print(current_value.get("msg")) else: if res.json()["error"] is not None: error = res.json()["error"] errorCode = error['errorCode'] errorInfo = error['errorInfo'] print("错误代码:%s,错误信息:%s"%(errorCode,errorInfo)) control_device.update({"ControlDevice": False}) print("Request getControlDevice failed!") index = GlobalVariable.findALocation(mac) if index != -1: point_info = GlobalVariable.final_result["pointInfos"][index] point_info.update(control_device) else: print("Find mac failure!")
def __target_files(self, targetInputValue): #folder = "/home/yang/development/ditto/live/crawl/Dridex-set1" folder = targetInputValue filelist = [] GlobalVariable.allFiles(folder, filelist) return filelist
def send_mail(send_file_path, send_who): """ :param send_file_path: 测试报告文件路径 :return: """ Main = Run.Main input_url = Run.url_target config_file_path = Misc.ABSpath() + "/Src/Conf/Config.yml" email = readConfig(config_file_path)['email'] smtpserver = email['mail_host'] smtpuser = email['mail_user'] password = email['mail_pass'] mailto = [] try: if send_who == "Null": # 拼装接收人 if input_url in 'www.wanpinghui.com': receive_category = "email_receiver_wph" mailto = readConfig(config_file_path)[receive_category] elif input_url in 'www.xxtao.com': receive_category = "email_receiver_xxtao" mailto = readConfig(config_file_path)[receive_category] else: mailto = send_who log.debug("send_file_path:%s" % send_file_path) log.debug("smtpserver:%s" % smtpserver) log.debug("smtpuser:%s" % smtpuser) log.debug("password:%s" % password) log.debug("mailto:%s" % mailto) msg = MIMEMultipart() # 定义发送人 msg['From'] = smtpuser # 定义接收邮件对象 msg['To'] = ",".join(mailto) # 邮件标题 run_case_total, run_pass_total, run_failures_total, run_error_total = GlobalVariable.parsing_string( GlobalVariable.get_value()) title = "[" + str(input_url) + "|C:" + str(run_case_total) + "|P:" + str(run_pass_total) + "|F:" + str( run_failures_total) + "|E:" + str(run_error_total) + "]" except Exception as msg: raise msg if 'u' in Main: Subject = "%sUI_Report" % title else: Subject = "%sAPI_Report" % title times = GlobalVariable.get_times() if times in [49, 50]: Subject1 = "=>System_Push" else: Subject1 = '' Subject = Subject + Subject1 msg['Subject'] = Header(Subject, 'utf-8').encode() msg["Accept-Language"] = "zh-CN" msg["Accept-Charset"] = "ISO-8859-1,utf-8" file_name = new_report(send_file_path) sendfile = send_file_path + file_name content1 = """<h3><a href = "http://pages.wph.xxtao.com/test-report/""" + file_name + """"">在线报告</a>||<a href = "http://at.test.xxtao.com/">实时监控系统</a><h3>""" content2 = "<h3>测试环境:[" + input_url + "] <h3>" content = content1 + content2 fp = open(sendfile, 'rb') try: # 将html中内容贴在邮件正文中 msg.attach(MIMEText(content + fp.read(), 'html', 'utf-8')) except Exception as msg: log.error(u'邮件发送失败') raise msg finally: fp.close() # 添加附件 fp = open(sendfile, 'rb') try: part = MIMEApplication(fp.read()) part.add_header('Content-Disposition', 'attachment', filename=file_name) msg.attach(part) except Exception as msg: log.error(u'邮件发送失败') raise msg finally: fp.close() try: # 发送邮件 server = smtplib.SMTP() try: # 不加密形式 server.connect(smtpserver, '25') except: # 通过ssl形式发送邮件 server = smtplib.SMTP_SSL(smtpserver, '465') # log.debug(u'邮件日志'+str(server.set_debuglevel(1))) server.login(smtpuser, password) server.sendmail(smtpuser, mailto, msg.as_string()) server.quit() log.debug(u'邮件发送成功') except Exception as msg: log.error(u'邮件发送失败') raise msg
#End_Func #MonoStickから取得したデータよりXYZの加速度を抽出 def GetXYZ(splited): x = splited[-3] x = x.replace("x=", "") x = int(x) y = splited[-2] y = y.replace("y=", "") y = int(y) z = splited[-1] z = z.replace("z=", "") z = z.replace("\\r\\n'", "") z = int(z) return x, y, z #End_Func if __name__ == "__main__": G.Initialize() #デフォルト画像取得 ret, frame = G.Capture.read() G.DefaultImage = cv2.resize(frame, G.FrameSize) cv2.imwrite("./BackGround.jpg", G.DefaultImage) #デフォルト画像を更新する処理をバックグラウンドで # 定期処理開始 th = threading.Thread(target=IP.UpdateDefaultImage) th.start() main()