下面是一个使用 Python 脚本监控 F5 指标,并输出 Prometheus Metrics 标准格式的示例代码:
import paramiko
from io import StringIO
# 设置F5 IP地址和用户名密码
F5_IP = '192.168.1.1'
F5_USER = 'admin'
F5_PASS = 'password'
# 建立SSH连接到F5设备
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(F5_IP, username=F5_USER, password=F5_PASS)
# 获取CPU使用率
stdin, stdout, stderr = ssh_client.exec_command('tmsh show sys cpu | grep "System:" | awk \'{print $2}\'')
cpu_usage = float(stdout.read().decode('utf-8').strip())
# 获取内存使用率
stdin, stdout, stderr = ssh_client.exec_command('tmsh show sys memory | grep "Memory usage" | awk \'{print $3}\'')
mem_usage = float(stdout.read().decode('utf-8').strip())
# 获取流量数据
stdin, stdout, stderr = ssh_client.exec_command(
'tmsh show net interface all-properties | egrep "Net::Interface|ifInOctets|ifOutOctets" | awk \'{print $2,$3}\'')
traffic_stats = [line.strip().split() for line in stdout.readlines()]
in_bytes = sum([float(stat[1]) for stat in traffic_stats if stat[0].startswith('Net::Interface')])
out_bytes = sum([float(stat[2]) for stat in traffic_stats if stat[0].startswith('Net::Interface')])
# 获取连接数信息
stdin, stdout, stderr = ssh_client.exec_command('tmsh show ltm virtual detail | egrep "Virtual server|Current connections"')
connection_stats = [line.strip().split(':')[-1].strip() for line in stdout.readlines()]
current_connections = int(connection_stats[0])
virtual_server_count = len([line for line in connection_stats if line.startswith('Virtual server')])
# 关闭SSH连接
ssh_client.close()
# 输出Prometheus Metrics格式的指标数据
output = StringIO()
output.write('# HELP f5_cpu_usage CPU usage on F5 device\n')
output.write('# TYPE f5_cpu_usage gauge\n')
output.write(f'f5_cpu_usage{{{F5_IP}}} {cpu_usage}\n')
output.write('# HELP f5_mem_usage Memory usage on F5 device\n')
output.write('# TYPE f5_mem_usage gauge\n')
output.write(f'f5_mem_usage{{{F5_IP}}} {mem_usage}\n')
output.write('# HELP f5_in_bytes Inbound traffic on F5 device in bytes\n')
output.write('# TYPE f5_in_bytes counter\n')
output.write(f'f5_in_bytes{{{F5_IP}}} {in_bytes}\n')
output.write('# HELP f5_out_bytes Outbound traffic on F5 device in bytes\n')
output.write('# TYPE f5_out_bytes counter\n')
output.write(f'f5_out_bytes{{{F5_IP}}} {out_bytes}\n')
output.write('# HELP f_count_of_virtual_servers Total number of virtual servers configured \n ')
output.write('# TYPE count_of_virtual_servers gauge \n ')
ouput.writeline(f"f_count_of_virtual_servers{{$F8_IP}} {virtual_server_count} ")
print(output.getvalue())
该脚本通过 Paramiko 模块建立 SSH 连接到 F5 设备,执行命令获取指标数据,并使用 StringIO 将输出写入字符串缓冲区中,最后通过 print() 函数输出字符串缓冲区中的内容。