Exemplo n.º 1
0
def main():
    sensor = BME280(t_mode=BME280_OSAMPLE_8,
                    p_mode=BME280_OSAMPLE_8,
                    h_mode=BME280_OSAMPLE_8)
    print "Initialized sensor"
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                              LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
    strip.begin()
    print "Initialized strip"
    send_flag = 0

    while (True):
        degrees = sensor.read_temperature()
        degrees = sensor.read_temperature()
        pascals = sensor.read_pressure()
        hectopascals = pascals / 100
        humidity = sensor.read_humidity()

        if degrees < 30.0:
            colorWipe(strip, Color(255, 0, 0))
            if send_flag == 0:
                send_flag = 1
                print "everything is normal"
        else:
            colorWipe(strip, Color(0, 255, 0))
            if send_flag == 1:
                send_flag = 0
                sendemail(
                    '*****@*****.**',
                    '*****@*****.**', '', 'ATTENTION!!!!!',
                    'Your dog is overheating, currently {0:0.3f} deg C'.format(
                        degrees), '*****@*****.**', 'TMSBausses')
                print "HEAT!!!!!!"
    colorWipe(strip, Color(0, 0, 0), 10)
Exemplo n.º 2
0
def sendEmail(message):

    usermessage = message.content

    #得到用户的邮箱
    email = re.search("\w.*.com", usermessage)
    if email:
        email = str(email.group())
        #得到用户想发的内容,规定格式为:发邮件到[email protected],内容叉叉叉,这个是为了找到 .con 的索引
        index = usermessage.find("com")
        # [index+4:] 其中,index+4代表 'com,' 这四个字符串,也就是说,这四个字符串后面开始算是内容

        content = str(usermessage[index + 4:])
        if email[:4] == "我的邮箱":
            try:

                #因为不会用正则匹配出文字中的邮箱,所以设置成第五个字符开始
                send_email.sendemail(email[4:], content)
            except:
                return "发送失败"
            return "发送成功"
        else:
            return ("请输入‘我的邮箱’‘email地址’以逗号分隔发送内容")
    else:
        # 非发邮件状态下,返回的文字
        return "this is tulip"
Exemplo n.º 3
0
def contact():
    """Render the website's contact page."""
    if request.method=='GET':
        return render_template('contact.html')
    if request.method=='POST':
        name=request.form['name']
        email=request.form['email']
        subject=request.form['subject']
        message=request.form['message']
        sendemail(name,email,subject,message)
        
        return "Message was sent"
Exemplo n.º 4
0
def send_email2person():
    #发送email给指定的收件人
    to = email_regex.get_email(request.form['to'])
    title = request.form['title']
    text = request.form['text']
    if (to != None) and (to != ''):
        try:
            send_email.sendemail(to, title, text)
            return render_template('email-form.html',
                                   message='sent',
                                   signin=is_sign())

        except:
            return render_template('email-form.html',
                                   message='failed',
                                   signin=is_sign())
    else:
        return render_template('email-form.html',
                               message='bad email address',
                               signin=is_sign())
Exemplo n.º 5
0
def send_daily_email():

    title = 'Greet in the morning!'
    msg = """\
    <html>
      <head></head>
      <body>
        <p>Hi!<br><br>
           How are you?<br>
           Are you ready today?<br>
           Are you one step closer to your dream?<br>
           Here is the <a href="http://www.python.org">link</a> you wanted.<br><br>

           Thanks,<br>
           Yiming
        </p>
      </body>
    </html>
    """

    sendemail(title, msg, bcclst=[
        '*****@*****.**',
    ])
Exemplo n.º 6
0
 def return_thread(self):
     """读取返回值队列,根据返回值处理相应操作,删除开关,删除返回值列表的值"""
     while (not self.return_queue.empty()):  # 判断队列是否为空
         data_dict = self.return_queue.get()  # 获取队列数据
         if data_dict["data"]:  # 更新订单状态
             self.automysql.autoExecute(
                 "update order_info set oi_status=2 where id=%s",
                 data_dict["id"])
             # 发送邮件提醒
             resp = sendemail(
                 data_dict["data"]["email"],
                 data_dict["data"]["from"] + "-" + data_dict["data"]["to"])
             print resp
         else:  # 更新结束状态
             self.automysql.autoExecute(
                 "update order_info set oi_status=4 where id=%s",
                 data_dict["id"])
         self.switch_lock.acquire()  # 删除开关数据
         del self.thread_switch_dict[str(data_dict["id"])]
         self.switch_lock.release()
Exemplo n.º 7
0
def run_dnsqueries_and_compare_with_legitimate_list():

    ###DNS LIB SETTINGS###

    resolver = dns.resolver.Resolver()
    resolver.timeout = 1.0
    resolver.lifetime = 1.0

    ###END OF DNS LIB SETTINGS###

    ips_resolved = []
    resolvedby = defaultdict(list)
    resolvedby.default_factory
    success = 0

    for i in read_dnsresolvers(
    ):  ##gets resolvers csv as input to perform dns queries
        i = i.replace("[", "").replace("]", "").replace("'", "")
        resolver.nameservers = [str(i)]

        try:
            b = resolver.query(domain, 'A')
            for j in b:
                success += 1
                ips_resolved.append(
                    j.to_text()
                )  ##collect ip resolveds by dns servers and stores as array ips_resolved
                resolvedby[j.to_text()].append(i)
                a = ("Resolved {0} with success {1} {2}/{3}").format(
                    str(domain), str(i), str(success), sum_dnsresolvers)
                print(a)
        except Exception as e:
            print(i, e,
                  "Try increasing resolver DNS timeout&lifetime settings")

##wl stands for whitelist

    valid_checked_ips = []
    for resolved_ip in ips_resolved:
        for wl in read_legitimateips():
            wl = wl.replace("[", "").replace("]", "").replace("'", "")
            if (ipaddress.ip_address(resolved_ip)
                    in ipaddress.ip_network(wl)) == True:
                valid_checked_ips.append(resolved_ip)
                break

    comparison = [x for x in ips_resolved if x not in valid_checked_ips]
    '''the above comparison it is very critical to continue to run. 
	It will check if any resolved IP is not recognized by you. 
	If so, will start to make whois queries and generate alerts.'''
    '''General logging below'''

    with open(
            os.getcwd() + "/logs/DNS_Pharming_Detection." +
            datetime.now().strftime("%Y-%m") + ".log", "a") as log:
        log.write("[*]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                  "|message=Started dnspharming.py\n")
        log.write("[*]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                  "|message=Loaded successfully " + resolvers +
                  " file containing a total of " + sum_dnsresolvers +
                  " DNS Resolvers servers.\n")
        log.write("[*]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                  "|message=Picked " + domain +
                  " as the domain to be resolved\n")

    if not comparison:

        with open(
                os.getcwd() + "/logs/DNS_Pharming_Detection." +
                datetime.now().strftime("%Y-%m") + ".log", "a") as log:
            log.write(
                "[*]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                "|message=[*] =========SUCCESSFULLY COMPLETED=====. DNS Queries Ratio of (success/total): ("
                + str(success) + "/" + sum_dnsresolvers + ")\n")
            log.write(
                "[*]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                "|message=No divergence was found. It seems the queried DNS Servers are safe.\n"
            )

        return (
            "[*] No divergence was found. It seems the queried DNS Servers are safe."
        )
    else:
        try:
            # Create logs Directory
            os.mkdir("logs")
        except FileExistsError:
            pass

        final_detection_dict = defaultdict(list)
        final_detection_dict.default_factory
        whois_query = defaultdict(list)
        whois_query.default_factory
        for i in set(
                comparison
        ):  ##set is used because one ip can be resolved by by multiple dns resolvers, so every ip will count only once.
            final_detection_message = (
                "[!]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                "|message=It seems that your monitored domain {0} is resolving the IP: {1} (which is not in your whitelist)"
                + " when querying the following {2} DNS server(s): {3} " +
                "raising a potencial indicator of a DNS Pharming Attack." +
                "|domain={0}|resolvedip={1}|totaldnsserver={2}|resolvedby={3}\n"
            ).format(str(domain), str(i), str(len(resolvedby[i])),
                     ', '.join(resolvedby[i]))
            final_detection_dict[i].append(', '.join(resolvedby[i]))
            for j in resolvedby[i]:
                try:
                    whoisa = whois.whois(j)
                    whois_query[j].append(whoisa['nets'][0]['description'])
                    whois_query[j].append(whoisa['nets'][0]['country'])
                    whois_query[j].append(whoisa['nets'][0]['emails'])
                    whois_query[j].append(whoisa['nets'][0]['created'])
                except Exception as e:
                    print(j, e)

            with open(
                    os.getcwd() + "/logs/DNS_Pharming_Detection." +
                    datetime.now().strftime("%Y-%m") + ".log", "a") as log:
                log.write(final_detection_message)
        with open(
                os.getcwd() + "/logs/DNS_Pharming_Detection." +
                datetime.now().strftime("%Y-%m") + ".log", "a") as log:
            log.write("[*]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                      "|message=Resolvers Whois DATA|" +
                      str(dict(whois_query)) + '\n')
            log.write(
                "[*]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                "|message=[*] =========SUCCESSFULLY COMPLETED=====. DNS Queries Ratio of (success/total): ("
                + str(success) + "/" + sum_dnsresolvers + ")\n")
        print(
            "[*] =========SUCCESSFULLY COMPLETED===== DNS Queries Ratio (success/total) of ("
            + str(success) + "/" + sum_dnsresolvers + ")")

        if enabled_email == str(
                1):  ##Check if SMTP notifications are turned on.

            ###E-mail template using jinja2

            t = Template("""
				<h3 style=\"color: #5e9ca0;\">New detection for {{ domain }} </h3>

	<table border="1">
	<table bgcolor="#F2F2F2">
	<table class="blueTable">
	<thead>
	<tr>
	<th>Resolved IP</th>
	<th>DNS Servers IPs</th>
	</tr>
	</thead>
	<tfoot></tfoot>
	<tbody>
				{% for n, g in final_detection_dict %} <tr><td>{{n}}</td><td>{{g}}
				{% endfor %}


	</tbody>
	</table>
	</table>
	</table>
	<p>
  
  <h4 style=\"color: #5e9ca0;\">Whois Data
  
</p>
	<table border="1">
	<table bgcolor="#F2F2F2">
	<table class="blueTable">
	<thead>
	<tr>
	<th><th align="center">DNS Server IP</th>
	<th><th align="center">Organization</th>
	<th><th align="center">Country</th>
    <th><th align="center">E-mail</th>
    <th><th align="center">Creation Date</th>
    	<tfoot></tfoot>
	<tbody>
				{%for key, value in whois_query.items()%}
				<tr>
				<td><td align="center">{{key}}</td>
				<td><td align="center">{{value[0]}}</td>
				<td><td align="center">{{value[1]}}</td>
				<td><td align="center">{{value[2]}}</td>
				<td><td align="center">{{value[3]}}</td>
				{% endfor %}
    </table>
    </table>
    </table>
    </table>
	<h4 style=\"color: #5e9ca0;\">Check /logs directory for more details. </h4>

	""")

            email_message = t.render(
                domain=domain,
                final_detection_dict=final_detection_dict.items(),
                whois_query=whois_query)

            try:
                send_email.sendemail(email_message)
                print("[!] An email alert has been sent to: " + str(emailto))
                with open(
                        os.getcwd() + "/logs/DNS_Pharming_Detection." +
                        datetime.now().strftime("%Y-%m") + ".log", "a") as log:
                    log.write(
                        "[!]|" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                        "|message=An email alert has been sent to: emailto=%s\n"
                        % str(emailto))
            except Exception as e:
                print("Error when sending email ", e)

    return final_detection_dict
Exemplo n.º 8
0
def run_task(filename):
    test.rpt()
    send_email.sendemail(filename)
    print 'send successfully on'.format(sched_Timer)
Exemplo n.º 9
0
            ### Comparison takes place
            if rtr_stored[Device_name] < rtr_current[Device_name]:

                ###  get the current time
                Time = str(datetime.now())

                ### create the subject and body of the email
                subject = '%s running config has changed at %s' % (Device_name,
                                                                   Time)
                message = '''
						Hello Sebastian\n 

						Router %s running configuration has changed to %s .\n
		

						Regards\n
						Sebastian''' % (Device_name, current_Run_Last_Changed)

                ### send email to myself or other account
                sendemail(from_addr, to_addr_list, '', subject, message, Login,
                          password)

                ### update the stored snmp value and save it into a prior pickle file
                rtr_stored[Device_name] = rtr_current[Device_name]
                with open('Database.pickle_v2', 'wb') as Temp:
                    pickle.dump(rtr_stored, Temp)

    except TypeError as e:
        print e
Exemplo n.º 10
0
    f=open("Eye.txt","a")
    a = datetime.datetime.now()
    f.write("\n"+str(cont)+" "+fname+ " " + str(a) +"\n")
    nb_classes = len(np.unique(y_test))
    x_train , x_test, y_train, y_test = preprocessing(x_train , x_test, y_train, y_test)
    x_train = x_train.reshape(x_train.shape +(1,1))
    x_test = x_test.reshape(x_test.shape + (1,1))
    input_shape = x_train.shape[1:]
    for i in range(10):
        c =Classifier_RESNET(input_shape,nb_classes)
        print("\n[" +fname+"]Treinando a rede ",i+1,"° vez")
        hist = c.fit(x_train,y_train,x_test,y_test)
        e = str(len(hist.history['loss']))
        print("Parou em "+e+" epocas")

        score = c.model.evaluate(x_test,y_test)
        scores.append(round(score[1]*100,2))
        print("%s: %.2f%%"%(c.model.metrics_names[1],score[1]*100))

    avg = round(sum(scores)/len(scores),2)
    print(avg)
    f.write("AVG Acc %.2f%%:"%(avg))
    f.write("\n")
    f.close()
    cont=cont+1
    filewriter.writerow([fname]+scores+[avg])
csvfile.close()

nameNetwork='resnet'
s.sendemail("*****@*****.**","Treino "+nameNetwork,"Terminou!!")
Exemplo n.º 11
0
 def notify_owner(self):
     """Send an email to self.owner.
     """
     sendemail('*****@*****.**', self.owner.email, 'You\'ve Got Mail!', 'Please check your mailbox, ' + self.owner.name + '.', \
          mail_auth['login'], mail_auth['password'])
     self.lastnotification = arrow.utcnow()
Exemplo n.º 12
0
from spyrk import SparkCloud
from mail_authentication import spark_auth, mail_auth
from time import sleep
from send_email import sendemail

spark = SparkCloud(spark_auth['accesstoken'])
core = spark.RE_core1

sensorvalue = core.analogRead()
# getsensorfunction()
print sensorvalue
if sensorvalue > 1500:
    sendemail(mail_auth['login'], '[EMAIL_TO]', 'You\'ve Got Mail!', 'Dear Valued Customer,\nYou\'ve got mail in your mailbox. You\'re very lucky.\nSincerely,\nme', mail_auth['login'], mail_auth['password'])
else:
    print "No mail for you!"