B-hads
B-hads

Reputation: 77

Tracking the time since last keystroke?

This is my completed keylogger as of right now. I have already posted this question before but it was really hard to iterate myself. On_press and On_release are the two main functions in this. They both track one keystroke. I need to track the time it takes between keystrokes, and I am not totally sure how I would get this done. I had the thought that I could track to see the time in between the string appends. I need to be able to see the time in between keystrokes because if that is longer than a certain period of time (ten seconds), I want the string which houses the keystrokes (keys) to be cleared. Thank y'all!

import pynput
import time 
import os, sys
from pynput.keyboard import Key, Listener
import psutil 

count = 0
keys = []

if (time.time() - lastKeystroke > 10):
   keys =[]

def on_press(key):
    global keys, count
    
    keys.append(str(key).replace("'",'').replace("Key.space", ' ').replace("Key.shift", "").lower())

    print(keys)

    count += 1
def on_release(key):
    if key == Key.esc:
        return False

lastKeystroke = time.time()

with Listener(on_press, on_release =on_release) as listener:
    listener.join()

Upvotes: 4

Views: 747

Answers (1)

furas
furas

Reputation: 142982

It is minimal example to get time between any two pressed keys.

At start it sets previous_time with time.time() and when I press key then it get current_time and compare with previous_time to see time before first press. And later it keep current_time in previous_time to calculate it again when I press next key.

from pynput.keyboard import Key, Listener
import time

# --- functions ---

def on_press(key):
    global previous_time

    # get current time and calculate time between two pressed keys
    current_time = time.time()
    diff_time = current_time - previous_time

    print('seconds:', diff_time)
    
    # save current time for next calculation
    previous_time = current_time
    
    # use this value for something
    if diff_time > 10:
         print("Too late!")

def on_release(key):
    if key == Key.esc:
        return False

# --- main ---

previous_time = time.time() # value as start

with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

Upvotes: 3

Related Questions