Control Keyboard and Mouse using Xdotool

Credits to this website:

In some conditions, it is useful to control the keyboard or mouse automatically. In this page, I will talk about the xdotool where we can control or simulate the keyboard or mouse. We also can program it by using python.

Install xdotool

Command line tool

Step 1: Type the command below:

sudo apt-get install xdotool

Step 2: Check whether you have installed the program or not

which xdotool

It will return the path to the executable.

Commands Avalaibles

There’s a lot of things you can do with xdotool. Let’s just focus on the command line tool for now. To get a list of available commands, please type:

xdotool -h

Most of the commands have a self-explanatory name.

Mouse Control Example

  • Move the mouse
    • Absolute position: 
      • xdotool mousemove 200 400 – Move the mouse pointer to the position 200 400 (point 0 0 is the top left corner)
    • Relative position: 
      • xdotool mousemove_relative 100 50 – Move the mouse by 100 on the x axis and 50 on the y axis, relative to its current position. To move by a negative amount, use xdotool mousemove_relative — -20 10. This will move the mouse -10 on the x axis and +10 on the y axis.
    • Get the current mouse location: 
      • xdotool getmouselocation – Gives the current x and y location of the mouse pointer, with the screen and current window ID

Keyboard Control Example

  • Simulate a key press:  xdotool key A – Type the letter ‘A’.
  • Hold a key down: xdotool keydown B  and xdotool keyup B . For example you can simulate a user pressing on a key for 1 second and releasing it:  xdotool keydown B sleep 1 keyup B . To get a list of supported options for this command, use xdotool keydown.
  • Typing a string: xdotool type “Hello” – Type a whole string.