How can a Bluetooth keyboard that requires a code entry be paired in the terminal?

You can try running bluetoothctl from the command line, make sure your device is on / ready to be discovered:

$ bluetoothctl
[NEW] Controller AA:BB:CC:DD:EE:FF device-name [default]

Any other bluetooth devices will be listed here. You'll then be inside a [bluetooth] prompt.

First, turn bluetooth power on (if your device is off):

[bluetooth]# power on
Changing power on succeeded

Then, make sure your agent is registered:

[bluetooth]# agent on
Agent registered

[bluetooth]# default-agent 
Default agent request successful

Now you can scan for devices from the console:

[bluetooth]# scan on
Discovery started
[CHG] Controller AA:BB:CC:DD:EE:FF Discovering: yes
[NEW] Device FF:EE:DD:CC:BB:AA Someone's Keyboard

You can manually pair from here as well:

[bluetooth]# pair FF:EE:DD:CC:BB:AA 
Attempting to pair with FF:EE:DD:CC:BB:AA 
[CHG] Device C8:E0:EB:04:52:55 Connected: yes

At this point, you should be prompted to enter a pin code for pairing:

Request PIN code
[agent] Enter PIN code: 12345

Enter a number (eg. 12345), and you will be prompted to input the same number from the device:

[Someone's Keyboard]# 12345

You should then be notified that your keyboard has paired:

[CHG] Device FF:EE:DD:CC:BB:AA Paired: yes

Hopefully this works for you, was trying to solve this for a while before I found any reference to bluetoothctl.


EDIT: The Ubuntu Touch OTA9 release includes Bluez 5, enabling pairing with the ThinkPad keyboards. Here's the little BQ Aquaris E4.5 acting almost as a palmtop.


Followed the steps by 1nfiniti on Ubuntu 16.04 amd64 and it worked great with Logitech MX5000 keyboard and mouse combo. But when I rebooted the computer, the keyboard didn't type again. It showed as connected but not paired on Bluetooth Settings. However, the mouse worked fine.

Having a look at bluetoothctl reference (https://wiki.archlinux.org/index.php/bluetooth#Bluetoothctl) realized that a 'trust' command was used after 'pair' command to allow some devices to successfully reconnect.

So I started bluetoothctl, disconnected and unpaired the keyboard, connected and paired it again, and issued

[bluetooth]# trust [keyboard MAC Address]

Then I was notified that your keyboard has been trusted

Trusted

And that did the trick, now the keyboard connects flawlessly every time I start/restart the computer.