This commit is contained in:
2025-07-11 19:06:56 +07:00
parent 8f53e99188
commit 9d07df53d0
23 changed files with 1947 additions and 934 deletions
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""
BGP Prefix Loader Script
Загружает префиксы из файла prefixes.txt в BIRD с настройкой community
"""
import os
import sys
import subprocess
import ipaddress
import logging
from datetime import datetime
from typing import List, Tuple, Optional
# Настройка логирования
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('/var/log/bird/prefix_loader.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class BGPPrefixLoader:
def __init__(self, prefixes_file: str = '/opt/bgp-server/data/prefixes.txt'):
self.prefixes_file = prefixes_file
self.birdc_path = '/usr/bin/birdc'
self.loaded_prefixes = set()
def validate_ip_prefix(self, prefix: str) -> bool:
"""Проверяет корректность IP префикса"""
try:
ipaddress.ip_network(prefix, strict=False)
return True
except ValueError:
return False
def validate_community(self, community: str) -> bool:
"""Проверяет корректность community (формат ASN:value)"""
try:
if ':' not in community:
return False
asn, value = community.split(':', 1)
int(asn)
int(value)
return True
except (ValueError, AttributeError):
return False
def parse_prefixes_file(self) -> List[Tuple[str, str, str]]:
"""Парсит файл prefixes.txt и возвращает список префиксов с community"""
prefixes = []
if not os.path.exists(self.prefixes_file):
logger.error(f"Файл {self.prefixes_file} не найден")
return prefixes
try:
with open(self.prefixes_file, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
# Пропускаем пустые строки и комментарии
if not line or line.startswith('#'):
continue
# Парсим строку: prefix community description
parts = line.split(None, 2)
if len(parts) < 2:
logger.warning(f"Строка {line_num}: неверный формат - {line}")
continue
prefix, community = parts[0], parts[1]
description = parts[2] if len(parts) > 2 else ""
# Валидация
if not self.validate_ip_prefix(prefix):
logger.warning(f"Строка {line_num}: неверный префикс - {prefix}")
continue
if not self.validate_community(community):
logger.warning(f"Строка {line_num}: неверный community - {community}")
continue
prefixes.append((prefix, community, description))
logger.info(f"Добавлен префикс: {prefix} с community {community} - {description}")
except Exception as e:
logger.error(f"Ошибка при чтении файла: {e}")
return prefixes
def execute_birdc_command(self, command: str) -> Tuple[bool, str]:
"""Выполняет команду через birdc"""
try:
result = subprocess.run(
[self.birdc_path] + command.split(),
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
return True, result.stdout
else:
return False, result.stderr
except subprocess.TimeoutExpired:
return False, "Timeout при выполнении команды"
except Exception as e:
return False, str(e)
def add_static_route(self, prefix: str, community: str) -> bool:
"""Добавляет статический маршрут в BIRD"""
# Команда для добавления статического маршрута
command = f"configure 'route {prefix} via 127.0.0.1;'"
success, output = self.execute_birdc_command(command)
if success:
logger.info(f"Добавлен маршрут: {prefix}")
self.loaded_prefixes.add(prefix)
else:
logger.error(f"Ошибка добавления маршрута {prefix}: {output}")
return success
def remove_static_route(self, prefix: str) -> bool:
"""Удаляет статический маршрут из BIRD"""
command = f"configure 'route {prefix} via 127.0.0.1;'"
success, output = self.execute_birdc_command(command)
if success:
logger.info(f"Удален маршрут: {prefix}")
self.loaded_prefixes.discard(prefix)
else:
logger.error(f"Ошибка удаления маршрута {prefix}: {output}")
return success
def get_current_routes(self) -> set:
"""Получает текущие статические маршруты из BIRD"""
success, output = self.execute_birdc_command("show route table bgp_table")
if not success:
logger.error(f"Ошибка получения маршрутов: {output}")
return set()
routes = set()
for line in output.split('\n'):
if 'via' in line and 'static' in line:
# Парсим префикс из строки
parts = line.split()
if len(parts) > 0:
prefix = parts[0]
routes.add(prefix)
return routes
def reload_configuration(self) -> bool:
"""Перезагружает конфигурацию BIRD"""
success, output = self.execute_birdc_command("configure")
if success:
logger.info("Конфигурация BIRD перезагружена")
else:
logger.error(f"Ошибка перезагрузки конфигурации: {output}")
return success
def load_prefixes(self, force_reload: bool = False) -> bool:
"""Основная функция загрузки префиксов"""
logger.info("Начинаем загрузку префиксов...")
# Получаем текущие маршруты
current_routes = self.get_current_routes()
logger.info(f"Текущих маршрутов: {len(current_routes)}")
# Парсим файл с префиксами
prefixes = self.parse_prefixes_file()
logger.info(f"Найдено префиксов в файле: {len(prefixes)}")
if not prefixes:
logger.warning("Нет префиксов для загрузки")
return False
# Создаем временный конфигурационный файл
temp_config = "/tmp/bird_static_routes.conf"
try:
with open(temp_config, 'w') as f:
f.write("# Автоматически сгенерированные статические маршруты\n")
f.write("# Время создания: {}\n\n".format(datetime.now()))
for prefix, community, description in prefixes:
f.write(f"route {prefix} via 127.0.0.1; # {community} - {description}\n")
# Применяем конфигурацию
if force_reload:
success = self.reload_configuration()
else:
success = True
if success:
logger.info(f"Успешно загружено {len(prefixes)} префиксов")
return True
else:
logger.error("Ошибка при применении конфигурации")
return False
except Exception as e:
logger.error(f"Ошибка при создании конфигурации: {e}")
return False
finally:
# Удаляем временный файл
if os.path.exists(temp_config):
os.remove(temp_config)
def show_statistics(self):
"""Показывает статистику загруженных префиксов"""
current_routes = self.get_current_routes()
print(f"\n=== Статистика BGP сервера ===")
print(f"Всего загружено префиксов: {len(current_routes)}")
print(f"Время: {datetime.now()}")
if current_routes:
print("\nЗагруженные префиксы:")
for prefix in sorted(current_routes):
print(f" - {prefix}")
def main():
"""Основная функция"""
import argparse
parser = argparse.ArgumentParser(description='BGP Prefix Loader')
parser.add_argument('--file', '-f',
default='/opt/bgp-server/data/prefixes.txt',
help='Путь к файлу с префиксами')
parser.add_argument('--force', action='store_true',
help='Принудительная перезагрузка конфигурации')
parser.add_argument('--stats', action='store_true',
help='Показать статистику')
args = parser.parse_args()
loader = BGPPrefixLoader(args.file)
if args.stats:
loader.show_statistics()
else:
success = loader.load_prefixes(args.force)
if success:
loader.show_statistics()
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()
+378
View File
@@ -0,0 +1,378 @@
#!/usr/bin/env python3
"""
BGP Monitor Script
Мониторинг BGP сессий, статистики и состояния сервера
"""
import os
import sys
import subprocess
import json
import time
import logging
from datetime import datetime
from typing import Dict, List, Optional
# Настройка логирования
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('/var/log/bird/monitor.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class BGPMonitor:
def __init__(self):
self.birdc_path = '/usr/bin/birdc'
self.bird6c_path = '/usr/bin/bird6c'
def execute_birdc_command(self, command: str, ipv6: bool = False) -> tuple:
"""Выполняет команду через birdc"""
try:
birdc = self.bird6c_path if ipv6 else self.birdc_path
result = subprocess.run(
[birdc] + command.split(),
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
return True, result.stdout
else:
return False, result.stderr
except subprocess.TimeoutExpired:
return False, "Timeout при выполнении команды"
except Exception as e:
return False, str(e)
def get_protocols_status(self, ipv6: bool = False) -> Dict:
"""Получает статус всех протоколов"""
success, output = self.execute_birdc_command("show protocols", ipv6)
if not success:
return {}
protocols = {}
current_protocol = None
for line in output.split('\n'):
line = line.strip()
if not line:
continue
# Находим имя протокола
if line.startswith('name') and 'state' in line:
parts = line.split()
if len(parts) >= 3:
protocol_name = parts[1]
state = parts[2]
protocols[protocol_name] = {
'state': state,
'info': {}
}
current_protocol = protocol_name
# Парсим дополнительную информацию
elif current_protocol and ':' in line:
key, value = line.split(':', 1)
key = key.strip()
value = value.strip()
protocols[current_protocol]['info'][key] = value
return protocols
def get_routes_count(self, ipv6: bool = False) -> Dict:
"""Получает количество маршрутов"""
success, output = self.execute_birdc_command("show route count", ipv6)
if not success:
return {}
routes_info = {}
for line in output.split('\n'):
line = line.strip()
if ':' in line:
key, value = line.split(':', 1)
key = key.strip()
value = value.strip()
routes_info[key] = value
return routes_info
def get_bgp_peers(self, ipv6: bool = False) -> List[Dict]:
"""Получает информацию о BGP пирах"""
protocols = self.get_protocols_status(ipv6)
bgp_peers = []
for name, info in protocols.items():
if name.startswith('bgp') and info['state'] == 'up':
peer_info = {
'name': name,
'state': info['state'],
'remote_ip': info['info'].get('Neighbor address', 'Unknown'),
'remote_as': info['info'].get('Neighbor AS', 'Unknown'),
'uptime': info['info'].get('Uptime', 'Unknown'),
'routes_received': info['info'].get('Routes received', '0'),
'routes_exported': info['info'].get('Routes exported', '0')
}
bgp_peers.append(peer_info)
return bgp_peers
def get_system_stats(self) -> Dict:
"""Получает системную статистику"""
stats = {
'timestamp': datetime.now().isoformat(),
'uptime': self.get_uptime(),
'memory_usage': self.get_memory_usage(),
'cpu_usage': self.get_cpu_usage(),
'disk_usage': self.get_disk_usage()
}
return stats
def get_uptime(self) -> str:
"""Получает время работы системы"""
try:
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.read().split()[0])
days = int(uptime_seconds // 86400)
hours = int((uptime_seconds % 86400) // 3600)
minutes = int((uptime_seconds % 3600) // 60)
return f"{days}d {hours}h {minutes}m"
except:
return "Unknown"
def get_memory_usage(self) -> Dict:
"""Получает использование памяти"""
try:
with open('/proc/meminfo', 'r') as f:
lines = f.readlines()
mem_info = {}
for line in lines:
if ':' in line:
key, value = line.split(':', 1)
key = key.strip()
value = int(value.split()[0])
mem_info[key] = value
total = mem_info.get('MemTotal', 0)
available = mem_info.get('MemAvailable', 0)
used = total - available
usage_percent = (used / total * 100) if total > 0 else 0
return {
'total_mb': total // 1024,
'used_mb': used // 1024,
'available_mb': available // 1024,
'usage_percent': round(usage_percent, 1)
}
except:
return {'error': 'Unable to read memory info'}
def get_cpu_usage(self) -> Dict:
"""Получает использование CPU"""
try:
with open('/proc/loadavg', 'r') as f:
load_avg = f.read().split()
return {
'load_1min': float(load_avg[0]),
'load_5min': float(load_avg[1]),
'load_15min': float(load_avg[2])
}
except:
return {'error': 'Unable to read CPU info'}
def get_disk_usage(self) -> Dict:
"""Получает использование диска"""
try:
result = subprocess.run(
['df', '-h', '/'],
capture_output=True,
text=True
)
if result.returncode == 0:
lines = result.stdout.split('\n')
if len(lines) >= 2:
parts = lines[1].split()
if len(parts) >= 5:
return {
'total': parts[1],
'used': parts[2],
'available': parts[3],
'usage_percent': parts[4]
}
except:
pass
return {'error': 'Unable to read disk info'}
def check_bird_service_status(self) -> Dict:
"""Проверяет статус сервиса BIRD"""
try:
result = subprocess.run(
['systemctl', 'is-active', 'bird'],
capture_output=True,
text=True
)
bird_status = result.stdout.strip()
result = subprocess.run(
['systemctl', 'is-active', 'bird6'],
capture_output=True,
text=True
)
bird6_status = result.stdout.strip()
return {
'bird': bird_status,
'bird6': bird6_status,
'timestamp': datetime.now().isoformat()
}
except:
return {'error': 'Unable to check service status'}
def generate_report(self, output_format: str = 'text') -> str:
"""Генерирует отчет о состоянии BGP сервера"""
report = {
'timestamp': datetime.now().isoformat(),
'system': self.get_system_stats(),
'services': self.check_bird_service_status(),
'ipv4': {
'protocols': self.get_protocols_status(False),
'routes': self.get_routes_count(False),
'bgp_peers': self.get_bgp_peers(False)
},
'ipv6': {
'protocols': self.get_protocols_status(True),
'routes': self.get_routes_count(True),
'bgp_peers': self.get_bgp_peers(True)
}
}
if output_format == 'json':
return json.dumps(report, indent=2)
else:
return self.format_text_report(report)
def format_text_report(self, report: Dict) -> str:
"""Форматирует отчет в текстовом виде"""
output = []
output.append("=" * 60)
output.append("BGP SERVER STATUS REPORT")
output.append("=" * 60)
output.append(f"Time: {report['timestamp']}")
output.append("")
# Системная информация
output.append("SYSTEM INFORMATION:")
output.append("-" * 20)
sys_info = report['system']
output.append(f"Uptime: {sys_info['uptime']}")
if 'memory_usage' in sys_info and 'usage_percent' in sys_info['memory_usage']:
mem = sys_info['memory_usage']
output.append(f"Memory: {mem['used_mb']}MB / {mem['total_mb']}MB ({mem['usage_percent']}%)")
if 'cpu_usage' in sys_info and 'load_1min' in sys_info['cpu_usage']:
cpu = sys_info['cpu_usage']
output.append(f"Load Average: {cpu['load_1min']:.2f} (1min), {cpu['load_5min']:.2f} (5min), {cpu['load_15min']:.2f} (15min)")
output.append("")
# Статус сервисов
output.append("SERVICE STATUS:")
output.append("-" * 15)
services = report['services']
output.append(f"BIRD (IPv4): {services.get('bird', 'Unknown')}")
output.append(f"BIRD (IPv6): {services.get('bird6', 'Unknown')}")
output.append("")
# BGP пиры IPv4
output.append("BGP PEERS (IPv4):")
output.append("-" * 18)
ipv4_peers = report['ipv4']['bgp_peers']
if ipv4_peers:
for peer in ipv4_peers:
output.append(f" {peer['name']}: {peer['remote_ip']} (AS{peer['remote_as']}) - {peer['state']}")
output.append(f" Uptime: {peer['uptime']}, Routes: {peer['routes_exported']} exported")
else:
output.append(" No active BGP peers")
output.append("")
# BGP пиры IPv6
output.append("BGP PEERS (IPv6):")
output.append("-" * 18)
ipv6_peers = report['ipv6']['bgp_peers']
if ipv6_peers:
for peer in ipv6_peers:
output.append(f" {peer['name']}: {peer['remote_ip']} (AS{peer['remote_as']}) - {peer['state']}")
output.append(f" Uptime: {peer['uptime']}, Routes: {peer['routes_exported']} exported")
else:
output.append(" No active BGP peers")
output.append("")
# Статистика маршрутов
output.append("ROUTE STATISTICS:")
output.append("-" * 18)
ipv4_routes = report['ipv4']['routes']
ipv6_routes = report['ipv6']['routes']
if ipv4_routes:
output.append("IPv4 Routes:")
for key, value in ipv4_routes.items():
output.append(f" {key}: {value}")
if ipv6_routes:
output.append("IPv6 Routes:")
for key, value in ipv6_routes.items():
output.append(f" {key}: {value}")
output.append("=" * 60)
return "\n".join(output)
def monitor_continuously(self, interval: int = 60):
"""Непрерывный мониторинг с заданным интервалом"""
print(f"Starting continuous monitoring (interval: {interval}s)")
print("Press Ctrl+C to stop")
try:
while True:
report = self.generate_report('text')
print(report)
time.sleep(interval)
except KeyboardInterrupt:
print("\nMonitoring stopped")
def main():
"""Основная функция"""
import argparse
parser = argparse.ArgumentParser(description='BGP Monitor')
parser.add_argument('--format', '-f', choices=['text', 'json'], default='text',
help='Output format (text or json)')
parser.add_argument('--continuous', '-c', action='store_true',
help='Continuous monitoring')
parser.add_argument('--interval', '-i', type=int, default=60,
help='Monitoring interval in seconds (default: 60)')
args = parser.parse_args()
monitor = BGPMonitor()
if args.continuous:
monitor.monitor_continuously(args.interval)
else:
report = monitor.generate_report(args.format)
print(report)
if __name__ == "__main__":
main()