怎么用Python写个摸鱼监控进程
怎么用Python写个摸鱼监控进程
发布时间:2022-02-21 16:13:09 来源:高防服务器网 阅读:93 作者:iii 栏目:开发技术
本篇内容主要讲解“怎么用Python写个摸鱼监控进程”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用Python写个摸鱼监控进程”吧!
监控键盘
如果公司偷偷在我们的电脑上运行了一个后台进程,来监控我们的键盘事件,最简单的 python 写法大致是这样的:
from pynput import keyboard def on_press(key): print(f'{key} :pushed') def on_release(key): if key == keyboard.Key.esc: return False with keyboard.Listener(on_press=on_press, on_release=on_release) as lsn: lsn.join()
随意敲击键盘,你就会从控制台看到这样的输出:
代码内容就是两个方法,一个是监听按键事件,另一个是监听退出事件——敲击 ESC 按键后释放就退出了。
监控鼠标
如果还要监听鼠标事件,那么上这段代码就行了:
from pynput import mouse def on_click(x, y, button, pressed): if button == mouse.Button.left: print('left was pressed!') elif button == mouse.Button.right: print('right was pressed!') return False else: print('mid was pressed!') # 定义鼠标监听线程 with mouse.Listener(on_click=on_click) as listener: listener.join()
这段代码主要是监听鼠标的左右键点击操作,运行之后操作鼠标,就可以看到控制台打印如下结果:
细心的你一定会发现,每次点击事件,都打印了两次。这是因为按下和松开都会触发鼠标事件。
记录监控日志
键盘事件和鼠标事件都有了,是时候将二者结合起来,把用户的操作记录到日志了。这里我们用 loguru 来记录日志,这个 python 模块我们之前的文章也讲过。
整个代码如下:
from pynput import keyboard, mouse from loguru import logger from threading import Thread # 定义日志文件 logger.add('moyu.log') def on_press(key): logger.debug(f'{key} :pushed') def on_release(key): if key == keyboard.Key.esc: return False # 定义键盘监听线程 def press_thread(): with keyboard.Listener(on_press=on_press, on_release=on_release) as lsn: lsn.join() def on_click(x, y, button, pressed): if button == mouse.Button.left: logger.debug('left was pressed!') elif button == mouse.Button.right: logger.debug('right was pressed!') else: return False # 定义鼠标监听线程 def click_thread(): with mouse.Listener(on_click=on_click) as listener: listener.join() if __name__ == '__main__': # 起两个线程分别监控键盘和鼠标 t1 = Thread(target=press_thread()) t2 = Thread(target=click_thread()) t1.start() t2.start()
运行之后,你就可以在同级目录下的日志文件中,看到这样的内容了:
完整代码
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: 闲欢 """ from pynput import keyboard, mouse from loguru import logger from threading import Thread # 定义日志文件 logger.add('moyu.log') def on_press(key): logger.debug(f'{key} :pushed') def on_release(key): if key == keyboard.Key.esc: return False # 定义键盘监听线程 def press_thread(): with keyboard.Listener(on_press=on_press, on_release=on_release) as lsn: lsn.join() def on_click(x, y, button, pressed): if button == mouse.Button.left: logger.debug('left was pressed!') elif button == mouse.Button.right: logger.debug('right was pressed!') return False else: logger.debug('mid was pressed!') # 定义鼠标监听线程 def click_thread(): with mouse.Listener(on_click=on_click) as listener: listener.join() if __name__ == '__main__': # 起两个线程分别监控键盘和鼠标 t1 = Thread(target=press_thread()) t2 = Thread(target=click_thread()) t1.start() t2.start()
到此,相信大家对“怎么用Python写个摸鱼监控进程”有了更深的了解,不妨来实际操作一番吧!这里是高防服务器网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。
[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[