How to bind mouse buttons to keys?

The xbindkeys and xte can help you.

For example my .xbindkeysrc file looks like this:

# close the window under the mouse cursor
"xte 'mouseclick 1' && xte 'keydown Alt_L' 'key F4' 'keyup Alt_L'"
  b:8+Release

# double click
"xte 'mouseclick 1' 'mouseclick 1'"
  b:9

Thanks to everyone for the solution. Here is a more foolproof/combined guide (done on Xubuntu 18.04).

  1. Open a terminal (like xterm/terminal/terminator), become root (sudo su -) or use sudo in front of the command:

    apt install xbindkeys xautomation
    
  2. Check the button mapping with xev, for this you don't need root permission so exit the root session (with exit) or open another terminal as user.

    xev | grep button
    
  3. A small window will appear. You have to move the mouse into that window and press the button you want to remap. An example output in the terminal will be:

    state 0x0, button 8, same_screen YES
    

    This is the 2nd side button on my mouse which I want to use as PAGE_DOWN.

    state 0x0, button 9, same_screen YES
    

    This is the 1st (yes, the order is reversed) side button I want to use as PAGE_UP.

  4. When you have all buttons you want to remap you can close the small xev window. Open your favorite editor (gedit/vi/nano for example) and edit the configuration file.

    vi .xbindkeysrc
    
  5. If you already have some content in the file, look if there is already a binding like it (unlikely, not by default) and add at the end.

    #Pagedown press
    "xte 'keydown Next'"
    b:8
    
    #Pagedown release
    "xte 'keyup Next'"
    b:8 + Release
    
    #Pagedup press
    "xte 'keydown Prior'"
    b:9
    
    #Pageup release
    "xte 'keyup Prior'"
    b:9 + Release
    

    Note: you need two entries, one for the button press and one for the release.

  6. The buttons 8+9 will be mapped to the keys "Next" (which is PAGE_DOWN) and "Prior" (PAGE_UP). If you want to map different keys you can find the keysymbol with xev.

    xev | grep keysym
    
  7. Like before, start it in a terminal, move the mouse to the small window and press the wanted key.

    state 0x0, keycode 117 (keysym 0xff56, Next), same_screen YES,
    
  8. Save and kill xbindings.

    killall xbindkeys ; xbindkeys
    

You can now use the additional side buttons on the mouse. The setting will be loaded automatically on next reboot/login. You only need the killall [...] command from above if you change the settings.