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.
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)
should i create address file where Mikrotik devices address will write ?
ReplyDelete