如何通过shell脚本注入击键?

Naf*_*Kay 27 linux keyboard input shell-script

我正在尝试将击键注入输入守护程序,以模拟从 Bash 脚本输入。这可能吗,如果可以,我该如何实现?

Gil*_*il' 25

使用uinput驱动程序。我不认为这有什么用处。您将不得不编写或改编一些 C 代码。简而言之:

#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);
Run Code Online (Sandbox Code Playgroud)

更完整的参考:


小智 24

如果您在 X 级别操作(如 Gilles 的问题),像这样使用xdotool

xdotool key KEYSTROKE_SPECIFIER
Run Code Online (Sandbox Code Playgroud)

其中 KEYSTROKE_SPECIFIER 可以是“a”或“F2”或“control+j”之类的东西

编辑:我错过了你对吉尔斯问题的回答,抱歉。我将把这个回复留在这里作为 X-case 的解决方案。

  • 我认为 `xte` 在同一级别运行。 (3认同)

Cal*_*leb 11

如果您不使用带有可以发送密钥的窗口的 X 程序,您可能正在寻找expect一个方便且非常可配置的程序,用于运行其他交互式 shell 程序,就像用户正在控制终端一样。您可以设置程序响应以响应具有不同输入的各种输出。


Kei*_*ith 7

我写了一些 Python 代码来做到这一点。你可以在我的开源项目中找到它。

http://code.google.com/p/pycopia/source/browse/trunk/core/pycopia/OS/Linux/event.py

如果您以 root 身份运行该模块作为脚本,您可以看到一个演示。

此基本功能为另一个项目 powerdroid 进行了扩展,该项目为嵌入式系统 (Android) 提供了更具体的实现。

http://code.google.com/p/powerdroid/source/browse/trunk/src/droid/devices.py