本篇文章小编给大家分享一下利用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()