I'm trying to create a behavioral biometrics tool that uses keyboard usage patterns to identify the user. The idea is to capture how the user types, but not what. I thought about capturing the time it takes for the user to press and release a key, as well as time from one key press to another.
I've been looking into jnativehook but I've only found "keylogger" type of programs and tutorials, same with pynput, which I think it's impossible to use the way I described...
Can someone give me a hint or tutorial to do such a thing?
Thank you.
1 Answer
pynput
can run one function on press
and other on release
and both functions can keep current time in two variables. If you substract them in one function then you should get how long was pressed and if you substract them in other function then you should get how long was released.
In code I check time between any keys and also for every key individually.
from pynput import keyboard
import datetime
# --- data ---
press_time = None
release_time = None
keys_press_time = {}
keys_release_time = {}
# --- functions ---
def press(key):
global press_time
press_time = datetime.datetime.now()
if release_time:
print('how long was released:', press_time - release_time, 'key: ANY')
# --- individual keys ---
keys_press_time[key] = press_time
if key in keys_release_time:
print('how long was released:', keys_press_time[key] - keys_release_time[key], 'key:', str(key))
def release(key):
global release_time
release_time = datetime.datetime.now()
if press_time:
print('how long was pressed :', release_time - press_time, 'key: ANY')
# --- individual keys ---
keys_release_time[key] = release_time
if key in keys_press_time:
print('how long was pressed :', keys_release_time[key] - keys_press_time[key], 'key:', str(key))
# --- main ---
with keyboard.Listener(on_press=press, on_release=release) as listener:
# ... other code ...
listener.join()
The only problem is when you keep some key longer and system starts repeating key (it generates release
events) and then it gives shorter times. It would need to turn off "repeating" in system or it would need to more complex code to reduce this problem.
BTW: I think you could do the same with jnativehook
in very similar way.
-
This is exactly what I was looking for! Thank you so much for your help! I can now understand better how listeners work, thank you so much!– ForkFeb 10, 2021 at 21:59
-
I solved the repeating keys problem using set() to save a key when it was firstly pressed and removed it when it was released, in case someone ever need it.– ForkMay 9, 2021 at 16:36
pynput
? Did you try to do it withpynput
? It can execute one functionon press
and other functionon release
and you can usetime
ordatetime
in both to get current time - when you substract twodatetime
values then you gettimedelta
with values which you expect. I think you could do the same withjnativehook
. But you have to try to do it.