· last year · Aug 02, 2024, 09:30 AM
1import requests
2import json
3from prometheus_client import start_http_server, Gauge
4import time
5
6# API endpoints
7login_url = "http://1.24.44.33/api/login"
8status_url = "http://1.24.44.33/api/wireless/interfaces/status"
9device_status_url = "http://1.24.44.33/api/system/device/status"
10interface_status_url = "http://1.24.44.33/api/interfaces/status"
11
12# Login credentials
13login_payload = {
14 "username": "admin",
15 "password": "admin"
16}
17
18# Prometheus metrics
19frequency_gauge = Gauge('wireless_interface_frequency', 'Frequency of wireless interfaces', ['interface'])
20signal_gauge = Gauge('wireless_interface_signal', 'Signal strength of wireless interfaces', ['interface'])
21tx_rate_gauge = Gauge('wireless_interface_tx_rate', 'TX rate of wireless interfaces', ['interface'])
22rx_rate_gauge = Gauge('wireless_interface_rx_rate', 'RX rate of wireless interfaces', ['interface'])
23macaddr_gauge = Gauge('wireless_interface_macaddr', 'MAC address of clients', ['interface', 'macaddr'])
24ipaddr_gauge = Gauge('wireless_device_ipaddr', 'IP address of the device', ['interface', 'mask', 'ipaddr'])
25
26def get_token():
27 """Perform the login POST request and retrieve the token."""
28 response = requests.post(login_url, json=login_payload)
29 if response.status_code == 200:
30 response_json = response.json()
31 with open("response.json", "w") as f:
32 f.write(json.dumps(response_json, indent=4)) # Write the response JSON to a file
33 print("Login response JSON:")
34 print(response_json)
35 token = response_json.get('token')
36 if not token:
37 print("Available keys in the response:", response_json.keys())
38 for key in response_json.keys():
39 if isinstance(response_json[key], dict):
40 token = response_json[key].get('token')
41 if token:
42 break
43 print(f"Extracted token: {token}")
44 return token
45 else:
46 print(f"Login failed: {response.status_code}")
47 print(response.text)
48 return None
49
50def fetch_device_status(token):
51 """Fetch the device status and update the IP address metric."""
52 headers = {
53 "Authorization": f"Bearer {token}"
54 }
55 device_status_response = requests.get(device_status_url, headers=headers)
56 if device_status_response.status_code == 200:
57 device_status_data = device_status_response.json()
58 print("Device Status:")
59 print(device_status_data)
60 ipv4_addresses = device_status_data.get('ipv4-address', [])
61 for ipv4 in ipv4_addresses:
62 mask = ipv4.get('mask')
63 address = ipv4.get('address')
64 if mask is not None and address is not None:
65 ipaddr_gauge.labels(interface="device", mask=mask, ipaddr=address).set(1)
66 return device_status_data
67 else:
68 print(f"Failed to get device status: {device_status_response.status_code}")
69 print(device_status_response.text)
70 return {}
71
72def fetch_and_update_metrics(token):
73 """Fetch wireless interface status and update Prometheus metrics."""
74 headers = {
75 "Authorization": f"Bearer {token}"
76 }
77 status_response = requests.get(status_url, headers=headers)
78 if status_response.status_code == 200:
79 status_data = status_response.json()
80 print("Wireless Interfaces Status:")
81 print(status_data)
82 # Update metrics with the status data
83 interfaces = status_data.get('data', [])
84 for interface in interfaces:
85 interface_name = interface.get('ifname')
86 frequency = interface.get('freq')
87 signal = interface.get('signal')
88
89 # Extract tx_rate, rx_rate, and macaddr for clients
90 clients = interface.get('clients', [])
91 for client in clients:
92 tx_rate = client.get('tx_rate')
93 rx_rate = client.get('rx_rate')
94 macaddr = client.get('macaddr')
95
96 if tx_rate is not None:
97 tx_rate_gauge.labels(interface=interface_name).set(tx_rate)
98 if rx_rate is not None:
99 rx_rate_gauge.labels(interface=interface_name).set(rx_rate)
100 if macaddr is not None:
101 macaddr_gauge.labels(interface=interface_name, macaddr=macaddr).set(1) # Setting it to 1 to indicate presence
102
103 if interface_name == "wlan0-1":
104 if frequency is not None:
105 frequency_gauge.labels(interface=interface_name).set(frequency)
106 if signal is not None:
107 signal_gauge.labels(interface=interface_name).set(signal)
108
109 return status_data
110 else:
111 print(f"Failed to get status: {status_response.status_code}")
112 print(status_response.text)
113 return {}
114
115def fetch_interface_status(token):
116 """Fetch the interface status and update the IP address metric for br-lan."""
117 headers = {
118 "Authorization": f"Bearer {token}"
119 }
120 interface_status_response = requests.get(interface_status_url, headers=headers)
121 if interface_status_response.status_code == 200:
122 interface_status_data = interface_status_response.json()
123 print("Interfaces Status:")
124 print(interface_status_data)
125
126 # Extract the 'data' section from the 'interfaces_status'
127 interfaces = interface_status_data
128 data = interfaces['data']
129
130 # Iterate through the list of interfaces
131 for interface in data:
132 ifname = interface['ifname']
133 # Check if the interface name matches 'br-lan'
134 if ifname == 'br-lan':
135 # Print the address from the 'ipv4-address' section
136 for ip4 in interface['ipv4-address']:
137 print(f"Address: {ip4['address']}")
138 mask = ip4.get('mask')
139 address = ip4.get('address')
140 if mask is not None and address is not None:
141 ipaddr_gauge.labels(interface=ifname, mask=mask, ipaddr=address).set(1)
142
143 return interface_status_data
144 else:
145 print(f"Failed to get interface status: {interface_status_response.status_code}")
146 print(interface_status_response.text)
147 return {}
148
149def main():
150 # Start the Prometheus exporter
151 start_http_server(8000)
152 print("Prometheus exporter started on port 8000")
153
154 while True:
155 token = get_token()
156 if token:
157 wireless_status = fetch_and_update_metrics(token)
158 device_status = fetch_device_status(token)
159 interface_status = fetch_interface_status(token)
160
161 # Combine all data into a single JSON object
162 combined_data = {
163 "wireless_interfaces_status": wireless_status,
164 "device_status": device_status,
165 "interfaces_status": interface_status
166 }
167
168 # Print the combined data as a JSON string
169 print(json.dumps(combined_data, indent=4))
170
171 # Sleep for 60 seconds before fetching the data again
172 time.sleep(60)
173
174if __name__ == "__main__":
175 main()