|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Keylogger for monitoring script keytaps. |
| 4 | +Logs all keypresses to a timestamped text file in logsk/ directory. |
| 5 | +Press Esc to stop logging and exit. |
| 6 | +""" |
| 7 | + |
| 8 | +import platform |
| 9 | +from pynput import keyboard |
| 10 | +from pathlib import Path |
| 11 | +from datetime import datetime |
| 12 | + |
| 13 | +# Platform detection |
| 14 | +PLATFORM = platform.system().lower() |
| 15 | +print(f"Running on platform: {PLATFORM}") |
| 16 | + |
| 17 | +# Create logs directory if it doesn't exist |
| 18 | +LOGS_DIR = Path("logsk") |
| 19 | +LOGS_DIR.mkdir(exist_ok=True) |
| 20 | + |
| 21 | +# Create timestamped log file |
| 22 | +def timestamp(): |
| 23 | + """Generate timestamp string for filenames.""" |
| 24 | + return datetime.now().strftime("%Y%m%d_%H%M%S") |
| 25 | + |
| 26 | +LOG_FILE = LOGS_DIR / f"keylog_{timestamp()}.txt" |
| 27 | +print(f"Logging keypresses to: {LOG_FILE}") |
| 28 | + |
| 29 | +# Global flag for stopping |
| 30 | +running = True |
| 31 | + |
| 32 | +def format_key(key): |
| 33 | + """Format key for logging.""" |
| 34 | + try: |
| 35 | + # Regular character keys |
| 36 | + return key.char |
| 37 | + except AttributeError: |
| 38 | + # Special keys |
| 39 | + key_str = str(key).replace("Key.", "") |
| 40 | + return f"[{key_str}]" |
| 41 | + |
| 42 | +def on_press(key): |
| 43 | + """Handle key press events.""" |
| 44 | + global running |
| 45 | + |
| 46 | + # Stop on Esc |
| 47 | + if key == keyboard.Key.esc: |
| 48 | + print("\nEsc pressed - stopping keylogger...") |
| 49 | + running = False |
| 50 | + return False |
| 51 | + |
| 52 | + # Format and log the key |
| 53 | + key_formatted = format_key(key) |
| 54 | + |
| 55 | + # Write to file |
| 56 | + with open(LOG_FILE, "a") as f: |
| 57 | + f.write(key_formatted) |
| 58 | + |
| 59 | + # Also print to console for real-time monitoring |
| 60 | + print(key_formatted, end="", flush=True) |
| 61 | + |
| 62 | +def main(): |
| 63 | + """Main keylogger loop.""" |
| 64 | + print("Keylogger started. Press Esc to stop.") |
| 65 | + print("-" * 50) |
| 66 | + |
| 67 | + # Write header to log file |
| 68 | + with open(LOG_FILE, "w") as f: |
| 69 | + f.write(f"Keylogger started at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") |
| 70 | + f.write("-" * 50 + "\n") |
| 71 | + |
| 72 | + # Start keyboard listener |
| 73 | + with keyboard.Listener(on_press=on_press) as listener: |
| 74 | + listener.join() |
| 75 | + |
| 76 | + # Write footer |
| 77 | + with open(LOG_FILE, "a") as f: |
| 78 | + f.write(f"\n{'-' * 50}\n") |
| 79 | + f.write(f"Keylogger stopped at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") |
| 80 | + |
| 81 | + print(f"\n{'-' * 50}") |
| 82 | + print(f"Log saved to: {LOG_FILE}") |
| 83 | + print("Keylogger stopped.") |
| 84 | + |
| 85 | +if __name__ == "__main__": |
| 86 | + main() |
0 commit comments