Fun with MikroTik put all commands and router's ip in a text file and run the script.
It's really boring work to do some specific same configuration that need to do in all the mikrotik. Like creating user, creating queue, creating filter rules, mangle rules, address list adding, raw filter, ip pool, log configure, time zone, ntp etc much more. Individually need to login a mikrotik router via winbox/ssh/telnet.
Python gives us better solution.
Demo given below and script Google drive download link: Script Drive Link
Just download and install python version 3.10.0. And install netmiko packege/module verision 4.3.0 using pip command. See python documentation or my previous blogpost.
Create a new folder name Mikrotik Automation. inside folder create files like below
In command_file.txt please put all the command that you want to execute in all the mikrotik router. I have added some commands
2. PPPoE Profile
3. Firewall mange rule
4. Firewall Filter rule for invalid syn,fin,ack, Filter rule for drop Brute Force Attack, port scanner, ssh attack, address list,
5. User Creation
6. Ip services configure
7. Log Configure
8. Queue type and Simple Queue configure
9. Clock, Time zone, Traffic-flow
10. Graphing
Command_file.txt contains 91 of command that will execute like below
In the host_file.txt add all the mikrotik router loopback ip's. I have added some ip address of my lab mikrotik router
Almost Eleven router there i will automate the above configuration. In host_file contains like this.
In Fun-with-mikrotik.py file paste below code and save
import time
def main():
username = input('Please Enter Username: ')
password = input('Please Enter Password: ')
# Define device parameters
with open('host_file.txt', 'r') as file:
host_addresses = file.readlines()
# Read commands from the text file
with open('command_file.txt', 'r') as file:
commands = file.readlines()
mikrotik = {
'device_type': 'mikrotik_routeros',
'username': username,
'password': password,
}
# Establish SSH connection
for host in host_addresses:
mikrotik['host'] = host.strip()
try:
with open('log.txt', 'a') as log_file: # Open log file in append mode
with ConnectHandler(**mikrotik) as net_connect:
# Send commands to the router
output = net_connect.send_config_set(commands)
time.sleep(10)
print(f'Commands executed at: {host.strip()}')
log_file.write(f'Commands executed at: {host.strip()}\n')
except Exception as e:
with open('log.txt', 'a') as log_file: # Open log file in append mode
log_file.write(f'Error executing commands at: {host.strip()}\n')
print("An error occurred:", e)
if __name__ == "__main__":
main()
input('Press enter to close.')
Don't worry those ip's are not reachable the script will notify you by loggin all the log in log.txt file. Contains all the log like below