Skip to main content

Automating Mikrotik Backup using Python

When you have so many Mikrotik devices on your network, configuring all of them at once would be a difficult task. I have about 400 devices on my network and today I wanted to make a backup from them so I wrote the following python script for backup. you can do any command with this. I hope this is useful to you.

The project can be downloaded from GitHub:
https://github.com/pooriaghaedi/mikback/blob/master/mikback.py


requirements
I used python3.6 for this script.
you need to install Paramiko package and re for regular expression if you need.
   pip3.6 install Paramiko

Here we have 3 functions, connect, backup and generate_file_name.

Connect
     the connect function initiates a new ssh connection.

Generate_file_name
     it gets the Mikrotik's hostname from system identity and adds its IP to the end of it.

Backup
     creates a backup file with the name generated from the previous function and then download it using same ssh connection.
import paramiko
import socket
import os
import re
import datetime


class mikssh():
    def connect(self, address, username, password):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((address, int(22)))
            s.shutdown(2)
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(hostname=address, username=username, password=password)
            remote = self.ssh.invoke_shell()
            return (remote)
        except paramiko.AuthenticationException:
            print("Authentication failed when connecting to {}".format(address))
        except Exception as e:
            print(e)

    def backup(self, name):
        try:
            rfile = '{}.backup'.format(name)
            stdin, stdout, stderr = self.ssh.exec_command(
                "/system backup save name={} dont-encrypt=yes".format(name) + "\n")
            print("------------")
            ftp_client = self.ssh.open_sftp()
            ftp_client.get('/{}'.format(rfile), '/Users/Mikback/{}.backup'.format(name))
            ftp_client.close()
        except Exception as e:
            print(e)

    def generate_file_name(self, address):
        try:
            stdin, stdout, stderr = self.ssh.exec_command("/system identity print" + "\n")
            output = stdout.read()
            print(re.search(r'name:.*', str(output)).group())
            identity = str(output).split('name: ')[1]
            name = identity[:12] + '-' + str(address)
            return (name)
        except Exception as e:
            print(e)



Comments

  1. should i create address file where Mikrotik devices address will write ?

    ReplyDelete

Post a Comment

Popular posts from this blog

Removing not running containers

It might occurred to you that you want to delete all docker containers that are not running any more. you can do it one by one or if they are a lot it might be time consuming. first of all we use following command to list all containers. then we want to delete containers with exited or created status: docker rm $(docker ps -a | grep 'Exited\|Created' | cut -d" " -f1) let me explain it a little bit, when we use docker ps -a we list all containers with "| grep 'Exited\|Created'" we grep for Exited or Created status, then we pick the container ID with cut command and finally we remove them all. keep that in mind that we are giving $(docker ps -a | grep 'Exited\|Created' | cut -d" " -f1) as Argument to the docker command.