Add IP phones to a separate Pool of IP addresses at Mac address
Hello!
This topic is about how I used Python to write a script that does the following:
Who cares, please welcome under the cat.
To begin with, I decided what tools I will use for this. Since I just started learning Python (as the first PL), I decided to put it into practice. Further I will give an example of a code with its commenting.
In the get_export_file_from_mikrotik () function, I connect to Mikrotik, and using the / ip dhcp-server lease print file = lease_file command, I write all the active poppy addresses into the lease_ftp file and then use FTP to upload it to my script working folder for further work.
Also here I create an empty list for poppy phone addresses. Next is the following code
We have a lot of extra information in the lease_ftp file, and therefore, using the get_all_mac function, I got a list containing only the poppy address of all active devices. With the following script, I pull out from all the poppy addresses, only the necessary ones (in my case, this is the poppy address of the phones):
The following commands will do the following:
The make_mikrotik_script () function creates a script file that Mikrotik can process to add poppies to the pool.
The upload_to_ftp () function uploads the finished script to the Mikrotik FTP server.
And the last function runs the script directly on the router.
As you might have noticed, logging is in progress.
As a result of such simple actions, all the phones are in a separate pool and now, if necessary, it is also convenient for me to work separately with them.
PS Used Python version 3.3
This topic is about how I used Python to write a script that does the following:
- Unloads the list of active poppy addresses from Mikrotik
- Selects poppy IP addresses of phones
- Puts them in a separate pool of IP addresses
Who cares, please welcome under the cat.
To begin with, I decided what tools I will use for this. Since I just started learning Python (as the first PL), I decided to put it into practice. Further I will give an example of a code with its commenting.
import telnetlib
import time
import ftplib
import logging
class MacToPool():
def get_export_file_from_mikrotik(self):
host = "IP адрес микротика"
user = "ваш_логин"
password = "ваш_пароль"
command_1 = '/ip dhcp-server lease print file=lease_file'
command_2 = 'quit'
tn = telnetlib.Telnet(host)
tn.read_until(b"Login: ")
tn.write(user.encode('UTF-8') + b"\n")
tn.read_until(b"Password: ")
tn.write(password.encode('UTF-8') + b"\n")
tn.read_until(b'>')
ftp = ftplib.FTP('IP адрес микротика')
ftp.login('ваш_логин', 'ваш_пароль')
try:
ftp.delete('lease_file.txt')
ftp.delete('script_mac_phone.rsc')
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Файлы удалены: lease_file.txt, script_mac_phone.rsc")
except Exception:
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Файлы для удаления не найдены. Продолжаем работу.")
time.sleep(1)
tn.write(command_1.encode('UTF-8') + b"\r\n")
time.sleep(1)
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Файл конфигурации создан.")
tn.read_until(b'>')
tn.write(command_2.encode('UTF-8') + b"\r\n")
time.sleep(1)
f = open('lease_file.txt', "wb")
ftp.retrbinary("RETR lease_file.txt", f.write)
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Файл конфигурации скопирован на сервер")
lst_mac_phone = []
In the get_export_file_from_mikrotik () function, I connect to Mikrotik, and using the / ip dhcp-server lease print file = lease_file command, I write all the active poppy addresses into the lease_ftp file and then use FTP to upload it to my script working folder for further work.
Also here I create an empty list for poppy phone addresses. Next is the following code
def get_all_mac(self):
self.get_export_file_from_mikrotik(MacToPool)
text = open('lease_file.txt').readlines()
self.all_mac = []
for line in text:
lst_value = line.split(" ")
for symbol in lst_value:
if len(symbol) == 17:
self.all_mac.append(symbol)
return self.all_mac
We have a lot of extra information in the lease_ftp file, and therefore, using the get_all_mac function, I got a list containing only the poppy address of all active devices. With the following script, I pull out from all the poppy addresses, only the necessary ones (in my case, this is the poppy address of the phones):
def find_mac_phone(self):
self.get_all_mac(MacToPool)
mac_phone = open("macphone.txt", "w")
for mac_address in self.all_mac:
if mac_address[0:8] == "00:15:65":
mac_phone.write(mac_address + "\n")
self.lst_mac_phone.append(mac_address)
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Файл с MAC адресами телефонов создан")
The following commands will do the following:
The make_mikrotik_script () function creates a script file that Mikrotik can process to add poppies to the pool.
The upload_to_ftp () function uploads the finished script to the Mikrotik FTP server.
And the last function runs the script directly on the router.
def make_mikrotik_script(self):
###выполнив функцию, получаем скрипт для микротика для добавления маков телефонов в пул IP-Phones###
script_mac_phone = open("script_mac_phone.txt", "w")
script_mac_phone.write("/ip dhcp-server lease \n")
self.find_mac_phone(MacToPool)
for mac_address in self.lst_mac_phone:
script_mac_phone.write("add address=IP-Phones mac-address=" + mac_address + " server=server1" + '\n')
self.upload_to_ftp(MacToPool)
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Создан скрипт script_mac_phone.rsc")
def upload_to_ftp(self):
ftp = ftplib.FTP('IP адрес микротика')
ftp.login('ваш_логин', 'ваш_пароль')
f = open("script_mac_phone.txt", "rb")
ftp.storbinary("STOR script_mac_phone.rsc", f)
f.close()
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("script_mac_phone.rsc перемещен на микротик")
def load_script_to_mikrotik(self):
self.make_mikrotik_script(MacToPool)
host = "IP адрес микротика"
user = "ваш_логин"
password = "ваш_пароль"
command_1 = '/import file-name=script_mac_phone.rsc'
command_2 = 'quit'
tn = telnetlib.Telnet(host)
tn.read_until(b"Login: ")
tn.write(user.encode('UTF-8') + b"\n")
tn.read_until(b"Password: ")
tn.write(password.encode('UTF-8') + b"\n")
tn.read_until(b'>')
tn.write(command_1.encode('UTF-8') + b"\r\n")
time.sleep(1)
logging.basicConfig(filename='log.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Конфигурация загружена. Done!")
tn.read_until(b'>')
tn.write(command_2.encode('UTF-8') + b"\r\n")
time.sleep(1)
As you might have noticed, logging is in progress.
As a result of such simple actions, all the phones are in a separate pool and now, if necessary, it is also convenient for me to work separately with them.
PS Used Python version 3.3