python实现键盘和鼠标监控

一、安装pynput

1
pip install pynput

二、使用pynput

监控键盘

1
2
3
4
5
6
7
8
9
10
11
12
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()

监控鼠标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()

将监控记录到日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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()