I’m trying to inject keystrokes into the input daemon so as to simulate typing from a Bash script. Is this possible, and if so, how can I make it happen?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use the uinput driver. I don’t think there’s a utility for that; you’re going to have to write or adapt a bit of C code. In a nutshell:
#include <fcntl.h>
#include <ioctl.h>
#include <unistd.h>
#include <linux/input.h>
#include <linux/uinput.h>
/* Set up a fake keyboard device */
fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK); // or /dev/input/uinput
ioctl(fd, UI_SET_EVBIT, EV_KEY);
struct uinput_user_dev uidev = …;
write(fd, &uidev, sizeof(uidev));
ioctl(fd, UI_DEV_CREATE);
/* Send an event */
struct input_event ev = …;
write(fd, &ev, sizeof(ev));
/* Clean up */
ioctl(fd, UI_DEV_DESTROY);
close(fd);
More complete references:
- Using uinput driver in Linux-2.6.x to send user input, by Mehul Patel
- Gettig started with uinput, by Gregory Thiemonge
Method 2
If you are operating at the X level (as in Gilles’ question), then use xdotool like so:
xdotool key KEYSTROKE_SPECIFIER
Where KEYSTROKE_SPECIFIER can be something like “a” or “F2” or “control+j”
EDIT: I missed your response to Gilles’ question, sorry. I’ll leave this response here as a solution for the X-case.
Method 3
If you’re NOT working with X programs with windows that can be sent keys, you are probably looking for expect, a handy and very configurable program for running other interactive shell programs as if a user were controlling the terminal. You can setup programatic responses to respond to various output with different inputs.
Method 4
I wrote some Python code that does that. You can find it in my open source project.
http://code.google.com/p/pycopia/source/browse/trunk/core/pycopia/OS/Linux/event.py
If you run that module as a script as root you can see a demo in action.
This basic functionality was extended for another project, powerdroid, that provides more concrete implementation for an embedded system (Android).
http://code.google.com/p/powerdroid/source/browse/trunk/src/droid/devices.py
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0