Log number of keyboard hits

How can I log a keyboard hit via shell script?
My aim is to log the number of keyboard hits of a login session on my Ubuntu system.

Note: I do not want to log the keystrokes itself, only the number of hits. So in the end it says:

94853 hits today.
Asked By: Shlomo


Monitoring in X11 (Graphical Desktop) Session Only

In you’re using the XInput layer (you probably are, if you’re running a modern X) then xinput test «keyboard-id» (from the xinput package on Debian) will give pey press and release events. You can get the keyboard ID by running xinput list. You can also use the name.

xinput test 'AT Translated Set 2 keyboard' | grep -c 'key press'

Note that when you pipe xinput, it has a fairly large buffer. So you may lose some keystrokes, unfortunately. You could use the XI2 API directly to avoid that, but that’s not easy from shell.

You can fairly easily start your script as one of the login scripts in your desktop environment or from your .xsession file, depending. The xinput should exit when you log out, because it’ll lose its X11 connection. So it’s really easy to track when your session starts and ends.

Monitoring System-wide (All Sessions, Even Text Mode)

Alternatively, if you want to monitor all keystrokes on the system, not just those in your X11 session, you can use the input-events (part of the input-utils package on Debian, at least). This must run as root. Use lsinput to find the right input device (happens to be 0 on my system) and then:

input-events 0 | grep -c 'EV_KEY.*pressed'

If you go this way, you’ll have to figure out when your sessions start and end some way (e.g., peterph’s dbus suggestion).

Answered By: derobert

As Derobert mentioned, xinput can be used (xinput --test-xi2 should work – you would need to count the lines containing RawKeyPress). However, you’d need to run your script as soon as your session starts and stop once it ends – so you’d probably want to watch a dbus session too.

Additionally, you would miss anything typed on virtual consoles – for that I’m afraid you’d need to write a kernel module, that would export its statistics somewhere in /proc or /sys – but it would include pretty much everything that goes into the computer.

Answered By: peterph
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.