'How can I add my ssh public key to a Mikrotik router device using the command line?

Mikrotik doesn't support ssh-copy-id which copies ~/.ssh/id_rsa.pub into the .ssh/authorized_keys file of a host on almost all Linux devices.

Is there an equivalent way to authorize a key on a Mikrotik RouterOS device so that I don't have to type a password, and for automatic login with a key or an unlocked key and ssh-agent instead?



Solution 1:[1]

Mikrotik RouterOS only allows you to import a key from a file that you copied over - but you can create this file from the command line. Here is a one-liner that should work from any Linux host:

 ssh 192.168.88.1 "/file print file=mykey; file set mykey contents=\"`cat ~/.ssh/id_rsa.pub`\";/user ssh-keys import public-key-file=mykey.txt;/ip ssh set always-allow-password-login=yes"

That is all you need to do.

Explanation

The line-by-line version of the above:

 $ ssh user@router
 [user@router] > /file print file=mykey;
 [user@router] > /file set mykey contents="copy and paste contents of ~/.ssh/id_rsa.pub here";
 [user@router] > /user ssh-keys import public-key-file=mykey.txt
 [user@router] > /ip ssh set always-allow-password-login=yes"

This will allow you to simply ssh without being prompted for a password by the router. Note that if your private key is password protected, you will be prompted for your private key file password, but that password will not be sent to the router. You can use ssh-agent and ssh-add to cache your private key on the host, if it is password protected - which is highly recommended - otherwise anyone with a copy will be able to access all your routers that allow your key.

Speed up initial connection

Another usability tip for ssh in general - if you add the following to /etc/ssh/ssh_config then connections will be kept open - and reused - which greatly speeds up logging in on devices where you log in a lot:

 ControlMaster auto
 ControlPath ~/.ssh/socket-%r@%h-%p
 ControlPersist 600

The only snag is that if the connection times out, connecting will hang if you reconnect within that timeout. You can of course manually delete the socket, which you can find with find .ssh/sock*

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1