SSH Keyboard Input Capture
sshkeyboard is a small, cross-platform Python library designed for capturing key presses and releases, primarily intended for use within SSH sessions but also functional in local terminal environments. It provides simple callback mechanisms for handling key events, enabling interactive command-line applications. The current version is 2.3.1, with ongoing maintenance for bug fixes and compatibility.
Common errors
-
ModuleNotFoundError: No module named 'sshkeyboard'
cause The `sshkeyboard` library has not been installed in the current Python environment.fixInstall the library using pip: `pip install sshkeyboard` -
The `until` condition is not stopping the `listen_keyboard` function when running locally.
cause When `sshkeyboard` is used outside of an SSH session, the `until` parameter relies on `pynput` for local key detection. `pynput` is likely not installed.fixInstall the optional dependency `pynput`: `pip install pynput` -
Keys are not being detected or unexpected characters are outputted when pressing certain keys (e.g., F1, arrow keys, Ctrl+Shift+C).
cause This is often an issue with the terminal emulator or operating system, which may intercept or interpret special keys differently before `sshkeyboard` can capture them. It's not always a library bug.fixTry using a different terminal emulator (e.g., Alacritty, Kitty, Windows Terminal, xterm). Ensure your terminal settings are not remapping or consuming these key events. In some cases, configuring `stty` or `terminfo` might be necessary, especially for older SSH servers.
Warnings
- gotcha The `until` parameter in `listen_keyboard` relies on the `pynput` library when running `sshkeyboard` locally (not over SSH). If `pynput` is not installed, the `until` condition might not function as expected, or the program might block indefinitely.
- gotcha Capturing certain special keys (e.g., function keys, Ctrl+C, Alt+combinations) can be inconsistent across different operating systems and terminal emulators. This is due to variations in how key events are transmitted and interpreted.
- gotcha Running `sshkeyboard` applications with `sudo` can lead to unexpected behavior, including a complete failure to detect key presses. This often occurs due to privilege separation and differences in how the root environment handles terminal input.
Install
-
pip install sshkeyboard
Imports
- listen_keyboard
from sshkeyboard import listen_keyboard
Quickstart
from sshkeyboard import listen_keyboard
import time
def on_press(key):
print(f"Key '{key}' pressed")
def on_release(key):
print(f"Key '{key}' released")
print("Listening for 5 seconds... Press any key.")
# Listens for key presses and releases for a duration of 5 seconds
listen_keyboard(on_press=on_press, on_release=on_release, until='5 seconds')
print("Finished listening.")