For start, I will assume that SSH user with appropriate rights is already configured as described in one previous blog post. From there getting Mikrotik’s configuration is easy: [pre] ssh backup@192.168.88.1 “/export” [/pre]
However, there are a few things wrong with it. First of all, all lines end with CRLF instead of more conventional LF (at least in the world of Linux/Unix). Fortunately this is easily fixed: [pre] ssh backup@192.168.88.1 “/export” | tr -d ‘\r’ [/pre]
Next you will notice that exported config has a line continuation character (\) on its longer lines. While this is nice for viewing config, if we are to automatically process result with diff
it is better to have each configuration line on its own. Getting Mikrotik to stop wrapping lines under all terminals is pretty much impossible, even using the +t4200w trick. However, sed
can do wonders with enough cryptic code:
ssh backup@192.168.88.1 "/export" \
| tr -d '\r' \
| awk '{sub(/^ +/, "", $0); if (sub(/\\$/,"")) printf "%s", $0; else print $0}'
And finally, you might notice there is a time on top of the exported script. This, usually a handy information, will cause any automatic diff to always find a difference. So, removing it is in order:
ssh backup@192.168.88.1 "/export" \
| tr -d '\r' \
| awk '{sub(/^ +/, "", $0); if (sub(/\\$/,"")) printf "%s", $0; else print $0}' \
| sed "s/^#.* by RouterOS/# RouterOS/"
With this we have a nice, repeatable, and diff-friendly configuration exported.
PS: If you are wondering why I am not using dos2unix
, it is because I wanted code to run on NAS4Free that has quite restricted command line.