3

I need to simulate keystrokes in headless environment.

All xte, xdotool and many C++ designed to work with X11 window

I've tried xdotool, which it throw some error:

xdotool type "aaaaa"
Error: Can't open display: (null)
Failed creating new xdo instance

I know about Xvfb but looking for other possible workaround

Sgaduuw
  • 1,833
  • 12
  • 16
apasajja
  • 167
  • 3
  • 10

1 Answers1

5

In order for an application to receive any keystrokes, it must receive them from somewhere. Usually the only two options are through a window or through a TTY. How to simulate a keystroke depend on which of the two is the case.

Through a window

If the application is receiving keystrokes through a window, in order to simulate them xdotool is the right tool for the job. You just need to set the proper DISPLAY variable, such that xdotool connect to the same X server as the application.

Through a virtual TTY

Lots of programs will invoke a shell within a virtual TTY. xterm, sshd, script, screen are some typical examples. The program which created the virtual TTY can send any keystrokes to the TTY by writing on the controlling end of the virtual TTY.

If it was xterm or any similar terminal emulator, the way to simulate a keystroke would be to do it through the window as described above.

From the rest of the list, the only program I know with a feature to simulate keystrokes is screen. You can send keystrokes to any named window within a screen session like this (actual example, which I often use):

screen -X at alsamixer stuff 2

Here screen -X will connect to a running screen and invoke a command. at alsamixer will cause the rest of the command to be invoked in the window named alsamixer. stuff 2 will simulate pressing 2.

One caveat to notice is that the above only works if the screen session is currently attached from somewhere. I don't know how to make it work on a detached screen.

Through a hardware TTY

You could have hardware send actual keystrokes. If it is a serial line, you can send keystrokes by writing them to the serial port on the computer at the other end of the line. If it is a local console you could have a piece of hardware connecting as a real keyboard (I'm sure it is possible to find USB devices, which can do this.)

In case of Linux, there exist drivers, which can simulate keystrokes on the local console just as if they came from the actual hardware.

kasperd
  • 30,455
  • 17
  • 76
  • 124
  • The `screen -X` was great. Do you know how to simulate presing `Enter` key and arrow down key? Do you have the source of example I can learn? – apasajja Aug 31 '14 at 12:08
  • 1
    I don't know exactly how to simulate Enter, but `stuff '\n'` appears to do the same thing in most cases. I don't know about arrow down either, but in a shell `stuff '\033[B'` does the same as arrow down. – kasperd Aug 31 '14 at 12:20