Esempio n. 1
0
def login():
    auth = request.authorization
    if not auth:
        return jsonify({'message': 'Authotization Not Provided!'}), 400
    else:
        username = auth.username
        password = auth.password

        for user in users_list:
            if username == user.name and password == user.password:
                token = jwt.encode(
                    {
                        'name':
                        user.name,
                        'exp':
                        datetime.datetime.utcnow() +
                        datetime.timedelta(minutes=15)
                    }, os.environ['SECRET_KEY'])

                mail = Mail(
                    user.mail, 'Login',
                    'http://0.0.0.0:50/user-login?token={}'.format(
                        token.decode('utf-8')))
                mail.send()
                sms = SMS(user.phone, 'Someone Logged into your account')
                sms.send()
                return jsonify({'token': token.decode('utf-8')}), 200
            else:
                return jsonify({'message':
                                'Username or Password is Invalid'}), 400
        return jsonify({'message': 'Username or Password is Invalid'}), 400
Esempio n. 2
0
	def click_toolbtnEnviar(self, widget, data=None):

		self.datos = Data('mails/mail.txt')
		self.datos.file_to_open()
		texto = self.datos.read_to_file()
		texto = texto.replace("\n",",")
		sMail = Mail("*****@*****.**","[email protected],"+texto,"Hola mundo de leo","Si hola mundo de leo.")
		sMail.connect_to_mail("*****@*****.**","*****@*****.**")
		sMail.send_to_mail()
Esempio n. 3
0
def init_test_set():
    with open('test/desired/index.csv') as csvfile:
        desired_mail_reader = csv.reader(csvfile,
                                         delimiter=',',
                                         quotechar='\"')
        for row in desired_mail_reader:
            test_set.append(Mail(row))
    with open('test/junk/index.csv') as csvfile:
        junk_mail_reader = csv.reader(csvfile, delimiter=',', quotechar='\"')
        for row in junk_mail_reader:
            test_set.append(Mail(row, True))
Esempio n. 4
0
    def _send(self, df):
        body = """<html>
                  <head><style  type="text/css" > th {border: 1px solid black;width: 65px;} td 
                  {border: 1px solid black;} table {border-collapse: collapse;border: 1px solid black;}
                  </style>
                  </head>
                  <body>"""

        body += df.to_html(index=False)
        body += "</body></html>"
        Mail.send(body, subject='Konfliktplan', to=self.mailto)
Esempio n. 5
0
def init_training_set():
    with open('res/desired/index.csv') as csvfile:
        desired_mail_reader = csv.reader(csvfile,
                                         delimiter=',',
                                         quotechar='\"')
        for row in desired_mail_reader:
            desired_training_set.append(Mail(row, False))

    with open('res/junk/index.csv') as csvfile:
        junk_mail_reader = csv.reader(csvfile, delimiter=',', quotechar='\"')
        for row in junk_mail_reader:
            junk_training_set.append(Mail(row, True))
Esempio n. 6
0
def resend_activation():
    """
    Resend the activation token in the user's email.
    returns: 403 if any errors occur. 200 if successful, and user get the
             activation mail resent to him.
    """
    req = request.get_json()

    try:
        user = (User.query
                .filter(User.email == req['email'])
                .one())

        if user.is_active:
            return Error("User is already active", 403)()

        serializer = URLSafeSerializer(app.config['SECRET_KEY'])
        activation_token = serializer.dumps(user.email)

        activation_url = url_for('User.activate_user',
                                 activation_token=activation_token,
                                 _external=True)

        Mail(req['email'],
             subject_data={'name': user.full_name},
             html_data={'token': activation_url},
             text_data={'name': user.full_name},
             template_root=SIGNUP_ACTIVATION
             ).send()

        return ""
    except NoResultFound:
        return Error("User with that email doesnt exist", 403)()
Esempio n. 7
0
def forgot_password():
    """
    Sends Reset Password link to User's email address. User can change
    his/her password through the link mentioned in the Email. It won't be an
    endpoint, it will be a webpage
    :return: 403 if any errors, else return 200
    """
    req = request.get_json()

    serializer = URLSafeSerializer(app.config['SECRET_KEY'])

    try:
        user = User.query \
            .filter(User.email == req['email']) \
            .filter(User.is_active) \
            .one()

        token = serializer.dumps(req['email'])
        reset_password_link = f"{request.url_root}reset_password?token={token}"

        Mail(user.email,
             subject_data={'name': user.full_name},
             html_data={'token': reset_password_link},
             text_data={'token': reset_password_link},
             template_root=FORGOT_PASSWORD
             ).send()

        return ""
    except NoResultFound:
        return Error('Invalid Email Address', 403)()
Esempio n. 8
0
def getMail(time):
    safe = random.choice([-1, 0, 1])
    if safe == 1:
        return (Mail(
            random.choice(email_names) + '@' + random.choice(email_ats),
            random.choice(subject_safe), random.choice(body_safe), time,
            None), safe)
    if safe == -1:
        return (Mail(
            random.choice(email_names) + '@' + random.choice(email_ats),
            random.choice(subject_malitious), random.choice(body_malitious),
            time, None), safe)
    else:
        return (Mail(
            random.choice(email_names) + '@' + random.choice(email_ats),
            random.choice(subject_safe + subject_malitious),
            random.choice(body_safe + body_malitious), time, None), safe)
Esempio n. 9
0
def PredictionProcess(logs, waitTime, logType):

    currTime = datetime.now() - timedelta(seconds=10) + timedelta(hours=4)
    startDate = currTime.strftime('%Y-%m-%dT%H:%M:%S')

    while True:

        uniqueAttacks = []
        endDate = datetime.now() - timedelta(seconds=5) + timedelta(hours=4)
        endDate = endDate.strftime('%Y-%m-%dT%H:%M:%S')
        failStr = logType + ": No Data for the time period " + startDate + " - " + endDate + ".\n"

        #For sanity print that the process is running
        print(logType + " is running for time range: " + startDate + " - " +
              endDate + ".")
        if logType is "DB":
            initdf = logs.DatabaseLogs.MySQLLogs(startDate, endDate)
            if initdf is not None:
                df = logs.DatabaseLogs.Transform(initdf)
                model = Model('DB')
                predictedDF, uniqueAttacks = IdentifyAttacks(model, df)

            else:
                print(failStr)

        elif logType is "IIS":
            initdf = logs.WebLogs.IISLog(startDate, endDate)
            if initdf is not None:
                df = logs.WebLogs.Transform(initdf)
                model = Model('IIS')
                predictedDF, uniqueAttacks = IdentifyAttacks(model, df)
            else:
                print(failStr)

        if uniqueAttacks:
            print(logType + " has detected the following attacks: " +
                  " ".join(uniqueAttacks) + "\n")
            notif = Mail(
                "ALERT! " + logType + " has detected attacks.",
                logType + " has detected the following attacks: " +
                " ".join(uniqueAttacks) + "\n")
            notif.send()

        startDate = endDate
        t.sleep(waitTime)
Esempio n. 10
0
def contact_us():
    """
    Receives query message and sends it to the email in the request,
    and also "*****@*****.**"

    """
    req = request.json
    del req['captcha_token']
    email = req['email']

    Mail([email, '*****@*****.**', '*****@*****.**'], req, req, req,
         CONTACT_US).send()
class SessionTokenLib(Base):
	''' kargs key from config resource must be exactly same as request attribute name
	    rtkey as attribute from config resource will return request string istead of return response string
	'''
	def __init__(self,url):
		Base.__init__(self, url)
		self.url = url
		self.mail = Mail(url)
	
	def __getKey(self):
		key = 'This is insecure, change'
		encryptedKey = hashlib.sha512(key).hexdigest()
		encryptedKey = encryptedKey.decode('hex')
		return encryptedKey[0:16]
	
	def __decrypt(self, encrypedToken): 
		obj = AES.new(self.__getKey(), AES.MODE_ECB)
		decode_hex = encrypedToken.decode('hex')
		crypt = obj.decrypt(decode_hex)
		return crypt

	def __encrypt(self, originToken):
		BS = 16
		pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
		#unpad = lambda s : s[0:-ord(s[-1])]
		obj = AES.new(self.__getKey(), AES.MODE_ECB)
		cryptToken = obj.encrypt(pad(originToken))
		return cryptToken.encode('hex')
		
	def api_call_emptyfolder(self,**kargs):
		try:
			emptyFolderRes = self.mail.empty_folder(**kargs)
			domain = re.findall('http://(.*):', kargs['host'])[0]
			originToken = self.client.session.cookies._cookies[domain]['/']['webtoptoken'].value
			token = self.__decrypt(originToken)
			origin_expired_time = re.findall(',([0-9]+),', token)[0]
			return self.client.session.cookies._cookies[domain]['/']['webtopsessionid'].value + ' | ' + origin_expired_time
		except Exception,e:
			if 'AUTHENTICATION_REQUIRED' in str(e):
				return 'AUTHENTICATION_REQUIRED'
			else:
				raise e
 def compararArchivos(self, button):
     archivo1 = self.Campos["File1"].GetEntryText()
     archivo2 = self.Campos["File2"].GetEntryText()
     with open(archivo1) as f1:
         f1_text = f1.read()
     with open(archivo2) as f2:
         f2_text = f2.read()
     comparacion = filecmp.cmp(archivo1, archivo2)
     if comparacion:
         self.Campos["Texto"].SetTextViewText("No hay diferencias")
         return
     d = Differ()
     result = list(d.compare(f1_text.splitlines(1), f2_text.splitlines(1)))
     self.Campos["Texto"].SetTextViewText(''.join(result))
     mail = self.Campos["Email"].GetEntryText()
     if mail != "":
         Mail().send(
             mail, "Diferencia entre archivos",
             "Diferencia entre los archivos " + archivo1 + " y " +
             archivo2 + "\n\n" + ''.join(result))
Esempio n. 13
0
    def __init__(self):
        Tk.__init__(self)
        self.mail = Mail()
        self.source_var = StringVar()

        i = 0
        while (i < 4):
            j = 0
            while (j < 5):
                Label(self, text="  ").grid(row=i, column=j)
                j = j + 1
            i = i + 1

        label = Label(self, text="Nom Campagne").grid(row=1, column=2)
        #source = Label(self, text="fichier.csv").grid(row=2, column=2)
        self.source = Entry(self, textvariable=self.source_var).grid(row=2,
                                                                     column=2)
        action = Button(self,
                        text="Fetch",
                        command=lambda: self.actionListener_action()).grid(
                            row=2, column=3)
Esempio n. 14
0
def send_old_msg(path):

    l_files = ls1(path)
    if (len(l_files) <= 1): return
    else:
        m = Mail(TO_EMAIL, "Fallas remanentes")
        m.create_initialize_server()
        m.login()
        if (ARCH_DIA in l_files):
            l_files.remove(ARCH_DIA)

        for f in l_files:
            m.attach_file(f)
            remove(path + f)

        m.send_mail()
        m.quit_server()
Esempio n. 15
0
def reply_comands(para, asunto = "Comando recibido"):

	m = Mail(para, asunto)
	m.create_initialize_server()
	m.login()
	if (asunto == "INFO"): m.attach_file()
	m.send_mail()
	m.quit_server()
Esempio n. 16
0
# Call this routine if the info file has changed
def on_file_change():
    event.set()
    logging.debug('on_file_changed called')

# Read the configuration file for mail and logfile settings
parser = SafeConfigParser()
parser.read(CONFIG_FILENAME)

logger = logging.basicConfig(filename=parser.get('logging', 'logfile'),
                             level=logging.DEBUG)

# Prepare in case we need to send a mail if failure
mail = Mail(parser.get('mail', 'to'),
            parser.get('mail', 'username'),
            parser.get('mail', 'password'),
            parser.get('mail', 'smtpserver'),
           )

# Setup a file event handler
event_handler = MyEventHandler(logger, on_file_change, file2change = 'nisse.txt')
observer = Observer()
observer.schedule(event_handler, FILEWATCH_DIR, recursive=True)
observer.start()

# FIXME : Create a data object
io = NewLoopDataObject()

# FIXME : Create a protocol
protocol = Protocol(io)
Esempio n. 17
0
 def sendLog(filename):
     body = MailLog.__readLogFile(filename)
     Mail.sendMail(body)
	def __init__(self,url):
		Base.__init__(self, url)
		self.url = url
		self.mail = Mail(url)
Esempio n. 19
0
 def __init__(self, url):
     Mail.__init__(self, url)
     self.prefs = ''
     self.url = url
Esempio n. 20
0
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders

from Crawler import Crawler
from Mail import Mail

from dotenv import load_dotenv
load_dotenv()

absolute_path = os.path.dirname(os.path.abspath(__file__))
f = open('target_urls', 'r')
urls = f.readlines()
f.close()

mail = Mail()
from_address = os.getenv('FROM_ADDRESS')
to_address = os.getenv('TO_ADDRESS')

for url in urls:
    site_name = re.sub('http(s)?://', '', url).replace('/', '').rstrip()

    current_file_path = os.path.join(absolute_path,
                                     'image/' + site_name + '/current')
    previous_file_path = os.path.join(absolute_path,
                                      'image/' + site_name + '/previous')

    current_file_name = current_file_path + '/screen.png'
    previous_file_name = previous_file_path + '/screen.png'

    utils.mkdir(current_file_path)
Esempio n. 21
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import smtplib
import time
import imaplib
import sys
import email
from Mail import Mail
from manejador_salidas import Manejador_Salidas


FROM_EMAIL  = '*****@*****.**'
TO_EMAIL = '*****@*****.**'
FROM_PWD    = 'edi@pru01'
SMTP_SERVER = 'imap.gmail.com'


m = Mail(TO_EMAIL, "Fallas" + " " + time.strftime("%d/%m/%y"))
m.create_initialize_server()
m.login()
m.attach_file()
m.send_mail()
m.quit_server()
Esempio n. 22
0
 def __sendMail(self):
     from Mail import Mail
     fileName = ntpath.basename(self.filePath)
     mail = Mail(self.allMails, self.allPhones, fileName)
     mail.CreateGUI()
Esempio n. 23
0
def main(args):
    mail = Mail('*****@*****.**', '*****@*****.**', 'hoppa2lo',
                'smtp.gmail.com')

    mail.send('from pi', 'Sylvia Wrethammar', [])
 def __init__(self, url):
     Mail.__init__(self, url)
     self.prefs = ""
     self.url = url
Esempio n. 25
0
from Mail import Mail
import re
import sys

fh = open('emails.txt', 'r')

list_of_addr = []

for line in fh:
    if re.match('^\w+(\.\w+)*@[a-zA-Z_]+?\.[a-zA-Z_]{2,6}$',
                line.rstrip()) != None:
        print line.rstrip(), ' is a valid address'
        list_of_addr.append(line.rstrip())
    else:
        print line.rstrip(), ' is NOT a valid address'

print list_of_addr

#sys.exit(42)

mail = Mail(
    list_of_addr,
    'dummy_user',
    'dummy_passwd',
    'mail01.ad.bolagsverket.se',
)
mail.send('test mail for jenkins')
Esempio n. 26
0
from Mail import Mail

DEST = '<DESTINATION-EMAIL>'
FROM = '<YOUR-EMAIL>'
PWD = '<YOUR-PASSWORD>'
SMTP = '<YOUR-SMTP-SERVER>'
PORT = 25

# Open File
myfile = open('SynFB.py')

# Lock the file
fcntl.flock(myfile, fcntl.LOCK_EX | fcntl.LOCK_NB)

# New Mail() instance
MM = Mail()

# Get hostname
host = socket.gethostname()

# Create log file
logging.basicConfig(filename="logs/log.txt", level=logging.INFO, format='%(asctime)s:%(message)s')
while 1 == 1:
    res = os.popen("netstat -ano | grep SYN_RECV |  awk {'print $4,$5'} | awk -F: {'print $1,$2'} | sort -k 3 | uniq -c | sort -k 1 | tail -1").read()
    if res != "":
        str = res.rstrip()
        logging.info(str)
        # Transform a string into an array
        arr = str.split()
        # If the first element of array it's >= 50 SynFB alert the admin mail configured at the top of this script.
        if int(arr[0]) >= 50:
Esempio n. 27
0
            scraping.check_Info()

            logging.info("The scrapping is completed for the item '" +
                         str(item[0]) + "'")
            logging.info("Old price : " + str(item[2][len(item[2]) - 1]) +
                         "\nNew price : " + str(scraping.price))
        except Exception as error:
            logging.warning("Error in the scrapper ->")
            logging.warning(error)

        if (scraping.price == 'Épuisé' & scraping.price !=
                item[2][len(item[2]) - 1]):
            print('no')
            logging.info('Price is sold out')

            mail = Mail(item[5])
            mail.send_mail(item[4], str(item[2][len(item[2]) - 1]), 'SOLD OUT',
                           item[3])

            scraping.price = 0.0

            logging.info("Updating of the price for " + str(item[0]) +
                         " in the database...")

            query = ("UPDATE item " + "SET prix = array_append(prix, " +
                     str(scraping.price) + ")" + ", date_up = CURRENT_DATE" +
                     " WHERE id_item = " + str(item[0]))
            cur.execute(query)

        elif (float(scraping.price) < float(
                item[2][len(item[2]) - 1])) & (float(scraping.price) != 0):
Esempio n. 28
0
def sonoff():
    print("sonoff")
    try:
        global state
        while True:
            r = requests.post(
                f"https://maker.ifttt.com/trigger/{sonoff_event[state]}/with/key/{YOUR_IFTTT_KEY}"
            )
            if r.status_code == 200:
                break
        state = not state
    except Exception:
        print("UNABLE TO SEND COMMAND TO SONOFF\n")


mail = Mail()


def email():
    print("email")
    mail.send()


cap = cv2.VideoCapture(
    'http://192.168.0.101:8000/stream.mjpg')  # IP of the Raspberry_Camera


def start_stream():
    cv2.namedWindow('Video', cv2.WND_PROP_FULLSCREEN)
    cv2.setWindowProperty('Video', cv2.WND_PROP_FULLSCREEN,
                          cv2.WINDOW_FULLSCREEN)