Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture a key press (key logging) in Linux?

Tags:

python

linux

How can I capture a key press (key logging) in Linux?

For Windows exist pyHook library but I dont know how to do it in Linux.

like image 471
Ed S Avatar asked Aug 07 '16 17:08

Ed S


2 Answers

You can use pyxhook:

#!/usr/bin/env python

import pyxhook

def OnKeyPress(event):
    print (event.Key)


    if event.Ascii == 32:
        exit(0)

hm = pyxhook.HookManager()
hm.KeyDown = OnKeyPress

hm.HookKeyboard()

hm.start()

sudo apt-get install python-xlib https://github.com/JeffHoogland/pyxhook

like image 152
Ed S Avatar answered Nov 06 '22 15:11

Ed S


#!/usr/bin/env python    
import pyxhook
import time

#This function is called every time a key is presssed
def kbevent( event ):
   #print key info
    print event

#If the ascii value matches spacebar, terminate the while loop
if event.Ascii == 32:
    global running
    running = False

#Create hookmanager
hookman = pyxhook.HookManager()
#Define our callback to fire when a key is pressed down
hookman.KeyDown = kbevent
#Hook the keyboard
hookman.HookKeyboard()
#Start our listener
hookman.start()

#Create a loop to keep the application running
running = True
while running:
time.sleep(0.1)

#Close the listener when we are done
hookman.cancel()
like image 31
sarih Avatar answered Nov 06 '22 15:11

sarih