def ch4dvr(frame,dvrIP):
    cams_on=np.array([101,201,301,401])
    (height,width)=frame.shape[:2]
    x1=int(width/2)
    y1=int(height/2)

    error_msg=""
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    frame1=cv2.calcHist([gray[0:y1,0:x1]],[0],None,[256],[0,256])
    frame2=cv2.calcHist([gray[0:y1,x1:width]],[0],None ,[256],[0,256])
    frame3=cv2.calcHist([gray[y1:height,0:x1]],[0],None,[256],[0,256])
    frame4=cv2.calcHist([gray[y1:height,x1:width]],[0],None,[256],[0,256])

    if frame4[0]>24000:
        error_msg=notify(4,error_msg,dvrIP)
        cams_on=np.delete(cams_on,3)  # (array,index)
    if frame3[0]>24000:
        error_msg=notify(3,error_msg,dvrIP)
        cams_on=np.delete(cams_on,2)
    if frame2[0]>24000:
        error_msg=notify(2,error_msg,dvrIP)
        cams_on=np.delete(cams_on,1)
    if frame1[0]>24000:
        error_msg=notify(1,error_msg,dvrIP)
        cams_on=np.delete(cams_on,0)

    #print("[ERROR]",error_msg)
    email(str(datetime.datetime.now())+error_msg)
    return cams_on
def checkDVR(lines):
    ret_val=""
    path=lines[:-1]
    dvrIP=path[-32:-20]
    path=path+"01"
    '''
    path='rtsp://*****:*****@[email protected]/Streaming/Channels/01'
    '''
    channel=int(lines[-1])
    print("path",path)
    vid=cv2.VideoCapture(path)
    startTime=time.time()
    while True:
        O_O,frame=vid.read()
        if not O_O and time.time()-startTime>30: #increse the time(seconds) and remove that break
            #print("DVR of IP {} not working".format(path[-34:-22]))
            file=open("log.txt",'a+')
            file.write(str(os.getpid())+"\n"+str(datetime.datetime.now())+" DVR of IP {} not working".format(dvrIP)+"\n")
            file.close()
            email(str(datetime.datetime.now())+" DVR of IP {} not working".format(dvrIP)+"\n")
            break
        elif channel==4:
            cams_on=ch4dvr(frame,dvrIP)
            for i in range(cams_on.shape[0]):
                print(str(path[:-2])+str(cams_on[i]))
            break
        elif O_O and channel==8:
            cams_on=ch8dvr(frame,dvrIP)
            break
        else:
            print("NOTHING")
            break       #important for breaking the loop
    vid.release()
Ejemplo n.º 3
0
def createmail():
    try:
        if not request.is_json:
            raise InvalidInput
        mail1 = request.json['email']
        email(mail1)
        return {}
    except (KeyError, InvalidInput):
        return {'error': 0}, 400, {'Content-Type': 'application/json'}
def ch8dvr(frame,dvrIP):
    cams_on=np.array([101,201,301,401,501,601,701,801])
    (height,width)=frame.shape[:2]   
    x1=int(width/3)
    x2=int(width*(2/3))
    y1=int(height/3)
    y2=int(height*(2/3))

    error_msg=""
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    frame1=cv2.calcHist([gray[0:y1,0:x1]],[0],None,[256],[0,256])
    frame2=cv2.calcHist([gray[0:y1,x1:x2]],[0],None,[256],[0,256])
    frame3=cv2.calcHist([gray[0:y1,x2:width]],[0],None,[256],[0,256])
    frame4=cv2.calcHist([gray[y1:y2,0:x1]],[0],None,[256],[0,256])
    frame5=cv2.calcHist([gray[y1:y2,x1:x2]],[0],None,[256],[0,256])
    frame6=cv2.calcHist([gray[y1:y2,x2:width]],[0],None,[256],[0,256])
    frame7=cv2.calcHist([gray[y2:height,0:x1]],[0],None,[256],[0,256])
    frame8=cv2.calcHist([gray[y2:height,x1:x2]],[0],None,[256],[0,256])
    frame9=cv2.calcHist([gray[y2:height,x2:width]],[0],None,[256],[0,256])


    if frame9[0]>24000:
        pass
    if frame8[0]>24000:
        error_msg=notify(8,error_msg,dvrIP)
        cams_on=np.delete(cams_on,7)
    if frame7[0]>24000:
        error_msg=notify(7,error_msg,dvrIP)
        cams_on=np.delete(cams_on,6)
    if frame6[0]>24000:
        error_msg=notify(6,error_msg,dvrIP)
        cams_on=np.delete(cams_on,5)
    if frame5[0]>24000:
        error_msg=notify(5,error_msg,dvrIP)
        cams_on=np.delete(cams_on,4)
    if frame4[0]>24000:
        error_msg=notify(4,error_msg,dvrIP)
        cams_on=np.delete(cams_on,3)
    if frame3[0]>24000:
        error_msg=notify(3,error_msg,dvrIP)
        cams_on=np.delete(cams_on,2)
    if frame2[0]>24000:
        error_msg=notify(2,error_msg,dvrIP)
        cams_on=np.delete(cams_on,1)
    if frame1[0]>24000:
        error_msg=notify(1,error_msg,dvrIP)
        cams_on=np.delete(cams_on,0)

    email(str(datetime.datetime.now())+error_msg)
    return cams_on
Ejemplo n.º 5
0
def log(device, timestamp):
    date = str(datetime.now())
    try:
        fichier = open("log/{}".format(date[0:10]), 'r+')
    except:
        fichier = open("log/{}".format(date[0:10]), 'a+')

    ok = 1

    for ligne in fichier:
        if ligne.find(device) != -1:
            ok = 0
    if ok == 1:
        fichier.write("{} :: {}\n".format(device, timestamp))
        email("{} :: {}\n".format(device, timestamp))
Ejemplo n.º 6
0
def log(gateway, port):
    if not os.path.exists("log"):
        os.makedirs("log")
    date = str(datetime.now())
    try:
        fichier = open("log/{}".format(date[0:10]), 'r+')
    except:
        fichier = open("log/{}".format(date[0:10]), 'a+')
    seen = 0
    for ligne in fichier:
        if ligne.find(gateway) != -1:
            seen = 1
    if seen == 0:
        fichier.write("{} {} ## {}\n".format(gateway, port,
                                             str(datetime.now())))
        mail.email("la gateway {} ({}) ne fonctionne plus depuis {}".format(
            gateway, port, str(datetime.now())))
Ejemplo n.º 7
0
def email_alert(to = app_email, file = False, critcal = False):
    #email a log file to a email address

    #Get current time/date.
    time = strftime("%Y-%m-%d %H:%M:%S")

    #Check file then open it, using location defined by function call if defined.
    if file == False:
        check_file(log_path, log_default)
        f = open(log_path + log_default, 'a')
    else:
        check_file(log_path, file)
        f = open(log_path + file, 'a')

    #Send the mail already!
    import mail
    
    if critcal:
        mail.email(to, f.read(), 'ALERT:' + app_name + ' log ' + time)
    else:
        mail.email(to, f.read(), app_name + ' log ' + time)
Ejemplo n.º 8
0
 def handle(self, *args, **kwargs):
  body = ''
  i = 0
  for j in Journey.objects.all():
   if j.out.date() == now:
    i += 1
    body += '{name} from {address} to arrive by {time}.\n'.format(name = j.person.name(), address = j.person.address(), time = j.out.time())

  if body:
   subject = 'Tomorrow%s %s' % (i, 'journey' if i == 1 else 'journeys')
   body = head + body
  else:
   subject = 'There are no journeys booked for today.'
   body = 'There are no journeys for today. These notifications should probably stop appearing over time.'

  body += """
  ---

  To log into the driver system, use the url
  http://%s:8000/admin
  """ % [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
  for a in addresses:
   email(a, subject, body)
Ejemplo n.º 9
0
Archivo: rest.py Proyecto: mkarnick/FF
    def POST(self):
        i = web.input()
        web.header('Content-Type', 'application/json')
        web.header('Access-Control-Allow-Origin', '*')
        web.header('Access-Control-Allow-Credentials', 'true')
        #print web.data()
        d = json.loads(web.data())
        #print d
        print "Checking for existing obj %s" %(d['subname'])
        existing = Subdomain.objects.filter(subname=d['subname'])
        try:
            if len(existing) == 0:
                newSignup = Subdomain(subname=d['subname'], leagueId=int(d['leagueId']), email=d['email']) 
                newSignup.save()
                mail.email(d['email'])
            else:
                print "Object exists. Bailing out."
                raise web.internalerror("webb internal error son")

        except:
            print "Something f****d up. Bailing out"
            raise web.internalerror("webb internal error son")
        print "Saved to ORM"
        raise web.seeother('/')
Ejemplo n.º 10
0
def manage_api():
    while True:
        print '''\033[34;1m管理接口提供的功能有:
1 解锁商城用户或信用卡用户
2 添加商城用户或信用卡用户
3 删除商城用户或信用卡用户
4 信用卡账单邮件
0 输入0返回上级菜单\033[0m
'''
        num = raw_input("\033[32;1m请输入您需要的功能:\033[0m")
        if num == '1':
            ulocak_user = raw_input("\033[34;1m请输入您要解锁的类型:1、为解锁商城用户   2、解锁信用卡用户:\033[0m")
            if ulocak_user == '1':
                user_lockli = [] #定义一个空列表存储被锁用户的信息
                with open('user_info','rb') as d:  #打开文件并用json把字符串转换为数据类型
                    user_info = json.load(d)
                for k,v in user_info.items(): #循环查找字典中的用户状态
                    if v['login_num'] == '3':  #如果用户处于被锁状态的话加入到列表中
                        lock_user = v['username']
                        print u'\033[31;1m%s用户已被锁定' % lock_user  #打印被锁用户信息
                        user_lockli.append(lock_user)  #把被锁用户追加到列表中
                if user_lockli: #判断如果列表不为空,如果有内容说明有被锁用户
                    user_unlock = raw_input("\033[32;1m请输入您要解锁的用户名:\033[0m") #获取用户要解锁的用户
                    if user_unlock in user_lockli: #判断,如果用户存在
                        user_info[user_unlock]['login_num'] = int(0)  #把user_info转换为数字类型
                        neirong = "%s用户已解锁" % user_unlock
                        yonghu = ulocak_user
                        youxiang = user_info[user_unlock]['mail']
                        zhuti = '账户解锁通知'
                        mail.email(neirong,yonghu,youxiang,zhuti)
                        with open('user_info','wb') as f:  #把新的用户状态写入user信息中
                            json.dump(user_info,f)
                        print "\033[32;1m\033[32;1m%s\033[0m\033[31;1m用户已被解锁\033[0m" % user_unlock

                    else:
                        print "\033[31;1m\033[32;1m%s\033[0m\033[31;1m用户不存在\033[0m" % user_unlock  #不能存在提示用户不存在!
                else:
                    print "\033[31;1m没有账户被锁定\033[0m"
            if ulocak_user == '2':
                card_lockli = [] #定义一个空列表存储被锁用户的信息
                with open('card_info','rb') as d:  #打开文件并用json把字符串转换为数据类型
                    card_info = json.load(d)
                for k,v in card_info.items(): #循环查找字典中的用户状态
                    if v['login_num'] == '3': #如果用户处于被锁状态的话加入到列表中
                        lock_card = k
                        print u'\033[31;1m%s用户已被锁定' % lock_card  #打印被锁用户信息
                        card_lockli.append(lock_card)
                if card_lockli: #判断如果列表不为空,如果有内容说明有被锁用户
                    card_id = raw_input("\033[32;1m请输入您要解锁的卡号:\033[0m")  #获取用户解锁账号
                    if card_id in card_lockli:  #判断用户输入的账号是否在被锁账号中
                        card_info[card_id]['login_num'] = int(0)  #存在替换账号信息并发送邮件
                        neirong = "%s卡号已解锁" % card_id
                        yonghu = card_id
                        youxiang = card_info[card_id]['mail']
                        zhuti = '卡号解锁通知'
                        mail.email(neirong,yonghu,youxiang,zhuti)  #用户解锁完成后调用发送邮件函数,发送邮件!
                        with open('card_info','wb') as f:
                            json.dump(card_info,f)
                        print  "\033[32;1m\033[32;1m%s\033[0m\033[31;1m卡号已被解锁\033[0m" % card_id
                    else:
                        print "\033[31;1m\033[32;1m%s\033[0m\033[31;1m卡号不存在\033[0m" % card_id #不存在提示卡号不存在!
                else:
                    print "\033[31;1m没有卡号被锁定\033[0m"
        elif num == '2':
            user_add = raw_input('\033[34;1m请选择您要添加的账户类型1、添加商城用户 2、信用卡用户:\033[0m')
            if user_add == '1':
                with open('user_info','rb') as d: #读取原有的用户信息
                    user_infos = json.load(d) #把原有的用户信息由字符串转换为数据类型
                add_name = raw_input('\033[32;1m请输入你要添加的用户:\033[0m') #获取用户输入的用户名
                if not user_infos.get(add_name): #判断原文件中是否有相同的用户名,如果有提示用户已存在,如果没有添加!
                    add_pass = raw_input("\033[32;1m请输入您添加用户的密码:\033[0m")  #获取用户的密码并加密
                    add_mail = raw_input("\033[32;1m请输入您添加用户的邮箱:\033[0m") #获取用户的邮箱
                    hash = hashlib.md5()
                    hash.update(add_pass)
                    add_pass = hash.hexdigest()

                    user_infos[add_name] = {'username':add_name,'mail':add_mail,'login_num': 0,'password':add_pass,'credit_money':15000}  #添加用户信息
                    with open('user_info','wb') as e:
                        json.dump(user_infos,e)
                    print "\033[32;1m%s用户添加完成\033[0m" % add_name

                    neirong = "%s用户注册成功" % add_name
                    yonghu = add_name
                    youxiang = user_infos[add_name]['mail']
                    zhuti = '用户注册成功'
                    mail.email(neirong,yonghu,youxiang,zhuti)  #调用发送邮件函数发送邮件
                else:
                    print "\033[31;1m用户已存在\033[0m"
            if user_add == '2':
                with open('card_info','rb') as d:  #读取用户原有信息
                    card_info = json.load(d)
                add_name = raw_input('\033[32;1m请输入你要添加的卡号:\033[0m')
                if not card_info.get(add_name): #判断原文件中是否有相同的用户名,如果有提示用户已存在,如果没有添加!
                    add_pass = raw_input("\033[32;1m请输入您添加卡号的密码:\033[0m") #获取用户的密码并加密
                    add_mail = raw_input("\033[32;1m请输入您添加卡号的邮箱:\033[0m") #获取用户的邮箱
                    hash = hashlib.md5()
                    hash.update(add_pass)
                    add_pass = hash.hexdigest()
                    card_info[add_name] = {'username':add_name,'mail':add_mail,'login_num': 0,'password':add_pass}
                    with open('card_info','wb') as e:  #把新增的内容写入文件
                        json.dump(card_info,e)
                    print "\033[32;1m%s卡号添加完成\033[0m" % add_name

                    neirong = "%s卡号注册成功" % add_name
                    yonghu = add_name
                    youxiang = card_info[add_name]['mail']
                    zhuti = '卡号注册成功'
                    mail.email(neirong,yonghu,youxiang,zhuti)  #调用邮件函数发送邮件
                else:
                    print "\033[31;1m用户已存在\033[0m"
            else:
                print "\033[31;1m请输入正确的功能项目\033[0m"
        elif num == '3':
            delete_user = raw_input("\033[34;1m请输入您要删除的类型:1、删除商城用户   2、删除用卡用户:\033[0m")
            if delete_user == '1':
                with open('user_info','rb') as d:  #打开文件并用json把字符串转换为数据类型
                    user_info = json.load(d)
                for k,v in user_info.items():
                    print k
                user_del = raw_input("\033[32;1m请输入您要删除的用户名:\033[0m") #获取用户输入
                if user_info.get(user_del):#判断用户输入的用户是否存在,存在删除
                    user_info.pop(user_del)
                    with open('user_info','wb') as e:  #删除后保存至信息文件中
                        json.dump(user_info,e)
                    print "\033[32;1m您好用户%s删除成功\033[0m" % user_del  #打印用户提示用户已删除
                else:
                    print "\033[31;1m您好您输入的用户不存在\033[0m"
            if delete_user == '2':
                with open('card_info','rb') as d:  #打开文件并用json把字符串转换为数据类型
                    card_info = json.load(d)
                for k,v in card_info.items():
                    print k
                user_del = raw_input("\033[32;1m请输入您要删除的用户名:\033[0m")#获取用户输入
                if card_info.get(user_del):
                    card_info.pop(user_del)
                    with open('card_info','wb') as e:#删除后保存至信息文件中
                        json.dump(card_info,e)
                    print "\033[32;1m您好用户%s删除成功\033[0m" % user_del  #打印用户提示用户已删除
                else:
                    print "\033[31;1m您好您输入的用户不存在\033[0m"


        elif num == '4':
            print '''\033[32;1m30号为账单日发送本月的消费记录通过邮件发送
1 发送账单:请把日期调到30号,并且本月有消费记录!\033[0m'''
            func = raw_input("\033[32;1m请输入选择的功能:\033[0m")
            if func == '1':
                d = datetime.datetime.now()
                daynow = d.day   #获取天的日期
                if daynow == 30: #如果为30号就发送邮件
                    print "\033[32;1m请确保用户这个月有消费记录\033[0m"
                    #循环查找用户,然后匹配用户的信息判断用户消费记录是否存在
                    user_list = [] #添加空列表把用户信息加入到列表中然后获取列表使用发送邮件!
                    mothe_now = time.strftime("%Y%m")  #获取本月日期
                    with open('user_info','rb') as f:  #加载用户信息
                        user_get = json.load(f)
                    for k,v in user_get.items():
                        user_list.append(k)  #获取用户列表
                    for i in user_list:
                        file_name = mothe_now+i  #取出消费记录的文件名称
                        print file_name
                        if os.path.exists(file_name): #如果消费列表文件存在打开,然后发送账单!
                            with open(file_name,'rb') as f: #打开消费列表
                                cost_list = json.load(f)
                            cost_all = 0
                            cost_info = []
                            for m in cost_list:
                                cost_liebiao = m[0]
                                cost_all += m[1]   #计算消费额度
                                cost_info.append(cost_liebiao) #把消费列表中的商品加入到列表中

                            neirong = "您本月的消费列表为:%s您本月的消费总额为:%d,请在下个月10号前还款" % (cost_info,cost_all)
                            yonghu = i
                            youxiang = user_get[i]['mail']
                            zhuti = '消费记录'
                            mail.email(neirong,yonghu,youxiang,zhuti)  #调用邮件函数发送邮件
                else:
                    print "\033[31;1m请把日期设置为本月的30号并且有消费记录\033[0m"
        elif num == '0':
            break
        else:
            print "\033[31;1m请输入正确的功能项目\033[0m"
Ejemplo n.º 11
0
            identify.TakePhoto("unknow.jpg")
            x = identify.COMPARE("owner.jpg", "unknow.jpg")
            if x == 0:
                time.sleep(2)
                continue
            else:
                l = locker()
                l.lock_workstation()
        else:  #lock
            with Listener(on_press=press) as listener:
                listener.join()
            identify.TakePhoto("unknow.jpg")
            x = identify.COMPARE("owner.jpg", "unknow.jpg")
            if x == 0:
                l = locker()
                l.unlock_workstation()
                flag = 0
                time.sleep(1)
            else:
                os.system("notify-send 'Wrong!'")
                l = locker()
                l.lock_workstation()
                time.sleep(1)
                flag = flag + 1
                if flag > 4:
                    Work_Encrypt("/home/foenix/test")
                    Email = email("./mailViaPython/account.txt")
                    Email.sendMail()
                    break
                continue
Ejemplo n.º 12
0
            assert today_is_special_day(age) == outcome, ERROR_MSG.format(
                age, outcome)

    def test_days_till_special_day():
        """
        Tests for range of values how many days till next special date
        """
        test_days = (1, 50, 100, 101, 200, 305, 365, 400, 499, 730, 800, 850)
        test_outcomes = (99, 50, 100, 99, 100, 60, 35, 100, 1, 70, 100, 50)
        for age, outcome in zip(test_days, test_outcomes):
            assert days_till_special_day(age) == outcome, ERROR_MSG.format(
                age, outcome)

    test_today_is_special_day()
    test_days_till_special_day()

    print('{} is {} days old'.format(PYBITES, AGE_DAYS))
    print('Does {} have a birthday today?'.format(PYBITES))

    if today_is_special_day():
        print('Yes! Sending celebration email')
        whatday = 'birthday' if AGE_DAYS % DAYS_IN_YEAR == 0 else 'celebration day'
        subject = 'Happy {}!'.format(whatday)
        message = '{} exists {} days today, go celebrate!'.format(
            PYBITES, AGE_DAYS)
        from mail import email
        email(subject, message)
    else:
        print('No ... days till next birtday: {}'.format(
            days_till_special_day()))
Ejemplo n.º 13
0
    hour = time.localtime().tm_hour
    if hour >= 23 or hour < 6:
        time.sleep(3600)  # 一小时
    else:
        time.sleep(300)  # 5分钟

    if hour >= 23 or hour < 7:  # 交易时间外不进行查票
        continue

    query_begin_time = time.time()

    # 获取数据
    try:
        result = requests.get(url, verify=False, timeout=600)  # 不用验证证书
    except socket.timeout:
        mail.email('服务停止,12306返回超时')
        logging.error('timeout')
        break
    except requests.exceptions.ReadTimeout:
        mail.email('服务停止,12306返回超时')
        logging.error('timeout')
        break

    # 转换json格式
    try:
        info = result.json()
    except ValueError:
        mail.email('服务停止,12306返回了奇怪的结果, json无法解析:' + str(result))
        logging.error('ValueError: No JSON object could be decoded, value=' +
                      str(result))
        break
def abstractData(x):
    data = pd.read_csv(x + '.txt', sep=",", header=None, error_bad_lines=False)
    data.columns = ["movie_name", "genre", "year", "rating"]
    top_five = data.sort('rating', ascending=False).head(5)
    print(top_five)
    m.email("*****@*****.**", str(top_five))
Ejemplo n.º 15
0
parser.add_argument('-e', '--email', help='Email From Address', required=True)
parser.add_argument('-t', '--to', help='Email To Address', required=True)
parser.add_argument('-s', '--smtp', help='SMTP Server', required=True)
parser.add_argument('-st', '--token', help='SLACK Token', required=True)
parser.add_argument('-sc', '--channel', help='SLACK Channel Id', required=True)

args = parser.parse_args()

try:

    response = requests.get(args.url, timeout=5)
    response.raise_for_status()

except requests.exceptions.HTTPError as e:
    print('Http Error:', e)
    email(args.url, 'Http Error', args.email, args.to, str(e), args.smtp)
    slack(args.token, args.channel, str(e))
except requests.exceptions.Timeout as e:
    print('Timeout Error:', e)
    email(args.url, 'Timeout Error', args.email, args.to, str(e), args.smtp)
    slack(args.token, args.channel, str(e))
except requests.exceptions.ConnectionError as e:
    print('Error Connecting:', e)
    email(args.url, 'Error Connecting', args.email, args.to, str(e), args.smtp)
    slack(args.token, args.channel, str(e))
except requests.exceptions.RequestException as e:
    print('Something went wrong trying to fulfill the request -->', e)
    email(args.url, 'Something went wrong trying to fulfill the request -->',
          args.email, args.to, str(e), args.smtp)
    slack(args.token, args.channel, str(e))
Ejemplo n.º 16
0
from mail import email
from manejadormail import manejador
if __name__=='__main__':
    nombre=input("ingrese su nombre: ")
    mail1=input("ingrese su mail: ")
    e=email()
    e.crearCuenta(mail1)
    print("estimado {} te enviaremos tus mensajes a la direccion {}".format(nombre,e.Retornaemail()))
    control=input("desea cambiar su contraseña? ")
    if(control=="si"):
        pass1=input("ingrese su contraseña actual (por defecto 1234): ")
        e.controlpass(pass1)
    test=email()
    test.crearCuenta("*****@*****.**")
    test2=manejador()
    test2.testmail()
    dominio=input("ingrrese un dominio")
    print("la cantidad de mails con ese dominio es de : {}".format(test2.calculodom(dominio)))