I am not a power user of Mikrotik devices so far, judging by the fact that I am not using terminal there as much as I am using web interface (or WebFig as they call it). But Mikrotik, being a powerful platform can help me understand what I am doing.

One of the things I figured out recently goes something like this:

  1. do some changes in router config (via UI or terminal)
  2. export config into human readable file (not binary)
  3. commit the file into git repository under same filename
  4. take a look at what changed

This approach provides not one but at least two benefits, so far:

  • my router config is safely stored in case something happens
  • the human readable format is actually commands themselves, so I can learn how to call them

By observing what commands are stored in the config, I can experiment with them and maybe one day become a power user too. So how did I automate it?

SSH into Mikrotik#

To prevent script from asking password, we can login via ssh public key. But it first has to be put into the router, via plain old password authentication:

scp ~/.ssh/my-public-key.pub [email protected]:pubkey.txt

ssh [email protected]
/user ssh-keys import public-key-file=pubkey.txt user=username-i-chose

It can also be done via WebFig, for completeness:

  1. Go to System → Users
  2. Select your user
  3. Go to SSH Keys tab
  4. Click '+' and paste your public key

Note the pubkey file will then probably be removed from the filesystem.

The script#

After I make changes I just manually run this script. It could be automated to do it periodically, but I did not want to compromise security even more, so I just kept it simple like this so far:

#!/bin/bash

# Configuration
ROUTER_IP="192.168.1.1"
ROUTER_USER="username-i-chose"
FILENAME="config.rsc"

# Create backup and download using SSH key authentication
ssh $ROUTER_USER@$ROUTER_IP "/export file=$FILENAME"
sleep 2
scp $ROUTER_USER@$ROUTER_IP:$FILENAME "$FILENAME"

# Add and commit if there are changes
git add "$FILENAME"
if git diff --staged --quiet; then
    echo "No changes to commit"
else
    git commit -m "update config"
    git push origin main  # Assuming 'main' branch and 'origin' remote is set up
fi

Note that it requires quite a lot of permissions on the router's user to to this, so you have been warned. Enjoy!