An educational Python script demonstrating keyboard event capture and file logging using the pynput library.
Educational & Authorized-Use Disclaimer: This project is provided strictly for educational purposes, defensive security learning, and authorized testing on systems you own or have explicit permission to monitor. Capturing keystrokes on any device or network without clear authorization may violate applicable laws and organizational policies.
keylogger.py registers a synchronous keyboard listener via pynput.keyboard.Listener and appends captured key presses to a local text file (key_log.txt) in the current working directory.
- Printable Key Capture: Logs character keys using
key.charinside theon_presscallback. - Special Key Handling: Catches
AttributeErrorfor non-character keys (such asKey.shift,Key.enter,Key.space, etc.) and writes them in the format{key}. - Persistent File Appending: Appends all captured keystrokes to
key_log.txtas events arrive.
- Language: Python 3
- Dependency:
pynput
python-keylogger/
├── keylogger.py # Keyboard listener and key_log.txt writer
└── README.md # Project documentation
-
Clone the repository:
git clone https://github.com/Ravindra4158/python-keylogger.git cd python-keylogger -
Install the dependency:
pip install pynput
-
Run the script:
python keylogger.py
-
Stop the script:
Press
Ctrl+Cin the terminal where the script is running. Recorded keystrokes are saved tokey_log.txtin the current working directory.
keylogger.pydefineslog_file = "key_log.txt"and anon_press(key)handler.- On each key press,
on_pressopenskey_log.txtin append mode ("a"):- Attempts to write
key.charfor standard character keys. - Falls back to writing
{key}whenAttributeErroris raised for special keys.
- Attempts to write
Listener(on_press=on_press)starts the keyboard hook andlistener.join()keeps the script running until interrupted.
- Foreground Execution: The script blocks on
listener.join()and runs in the active terminal rather than daemonizing in the background. - No Built-in Exit Hotkey or Rotation: There is no
on_releasestop key handler, log rotation, or encryption; output is written as plain text tokey_log.txtin the working directory. - Platform Permissions: Depending on your operating system and display server (for example, macOS Input Monitoring / Accessibility permissions or Linux input/X11 permissions),
pynputmay require elevated privileges or explicit OS permissions to observe global keyboard events. - Repository Packaging: No
requirements.txtorLICENSEfile is currently included in the repository.
- GitHub: @Ravindra4158
- LinkedIn: @Ravindrachoudhary


