July 12, 2014
Sometimes you need to execute various commands on a Mikrotik automatically from a Server. Surely it is possible to store the password in the script, but there is a better way – it is called Public Key authentication for SSH. Basically a pair of files is generated and the public one is copied to the Mikrotik and the private key stays on the PC. If you encrypt this key on the PC (which is useful if not a script does use it but a person) you get a 2-factor authentication. An attacker needs that private file and the password to decrypt it to administer the router. There are two types supported by SSH RSA and DSA. RSA is more commonly used but Mikrotik does only support DSA so we need to create a DSA key pair.
The first step is to generate the key pair as the user on the Linux system which is than used to access it. If it is a script it maybe a separate user just for this purpose is a good idea.
$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/<user>/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_dsa.
Your public key has been saved in id_dsa.pub.
The key fingerprint is:
If you just press enter on the file question, the default one will be used. If you want to use some separate directory that’s fine, you just need to provide the location later at the ssh call. If you press just enter for the passphrase the private key will not be encrypted. Now we copy the public key (
.pub extension) to the Mikrotik:
scp /home/<user>/.ssh/id_dsa.pub [email protected]:
And after that we need to import the key. If we choose the user admin, which we use our self to login, no password login will be possible anymore for that user. So if you don’t like that you should create a special user for the script. As my script needs only to read stuff I’m okay with the group “read” and create a user like this:
/user add name=scriptUser group=read comment="user for our readonly scripts" disabled=no
Now we import that public key to the scriptUser with following command:
/user ssh-keys import public-key-file=id_dsa.pub user=scriptUser
We’re done .. just testing is open …. if you used not the default directory to store the key files you need to provide them via the
-i parameter, if its the default location you don’t need to provide it. This command logs into the router and gets you some basic data without entering a password.
$ ssh -i <pathTo/id_dsa> scriptUser@
xxx.xxx.xxx.xxx “/system resource print”
You should also try to login as this user without the key file (e.g. from an other computer) and it should not be possible.