378 lines
14 KiB
Python
378 lines
14 KiB
Python
#!/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() |