Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import socket
import re
import time
import subprocess
socket_path = "./tmp/sock"
def get_kpi_value():
hostname = "8.8.8.8"
count = 1
wait = 5
total_pings = 0
successful_pings = 0
try:
# Run the ping command and capture the output
result = subprocess.check_output(["ping", "-W", str(wait), "-c", str(count), hostname], universal_newlines=True)
response_time = float(re.findall(r"time=([0-9.]+) ms", result)[0])
successful_pings += 1
except subprocess.CalledProcessError as e:
response_time = -1
total_pings += 1
moving_loss_ratio = round(((total_pings - successful_pings) / total_pings * 100), 2)
print("Packet loss: {}%".format(moving_loss_ratio))
print("Latency: {} ms".format(response_time))
return response_time
def main():
try:
while True:
start_time = time.time()
# Ping and capture latency and packet loss
data = str(get_kpi_value())
# Write results in socket
try:
client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client_socket.connect(socket_path)
client_socket.send(data.encode())
client_socket.close()
except Exception as e:
print(e)
# Calculate the time taken by get_kpi_value()
execution_time = time.time() - start_time
# Wait the rest of the time
wait_time = max(0, 6 - execution_time)
time.sleep(wait_time)
except KeyboardInterrupt:
print("Script terminated.")
if __name__ == "__main__":
main()