Python References
Base de script
from sys import exit
def main():
return 0
# Vérification que le script est lancé en executant ce fichier de script
if __name__ == '__main__':
exit(main())
Base de parsing
Fichier d'état d'un service
#!/usr/bin/python3
from sys import exit
from os import walk
from time import sleep, time
from collections import namedtuple
# I used the classmethod decorator to be able to stock and access data without having
# the need to have access to a specific instance of the object
class IfaceObject:
tpl = ['iface',
'd_total_bytes', 'd_total_packets', 'd_err', 'd_drop', 'd_fifo',
'd_frame', 'd_compressed', 'd_multi',
'u_total_bytes', 'u_total_packet', 'u_err', 'u_drop', 'u_fifo', 'u_collision',
'u_carrier', 'u_compressed',
't_timestamp']
data = {}
history_len = 10
stats = {}
divisor = 1024
def __init__(self, raw_iface_data):
raw_iface_data.append(round(time(), 4))
if self.data is None or raw_iface_data[0] not in self.data:
self.data[raw_iface_data[0]] = []
if self.stats is None or raw_iface_data[0] not in self.stats:
self.stats[raw_iface_data[0]] = {'up': 0, 'down' : 0}
tmp = dict(zip(self.tpl, raw_iface_data))
self.data[raw_iface_data[0]].append(tmp)
if len(self.data[raw_iface_data[0]]) > self.history_len:
del self.data[raw_iface_data[0]][0]
@classmethod
def inst_rate(cls):
result = []
iface_dict = dict(iface = "", up = 0, down = 0)
for iface in IfaceObject.data.keys():
if len(IfaceObject.data[iface]) > 1:
now = IfaceObject.data[iface][-1]
prev = IfaceObject.data[iface][-2]
delta_time = int(prev['t_timestamp']) - int(now['t_timestamp'])
delta_down = int(prev['d_total_bytes']) - int(now['d_total_bytes'])
delta_up = int(prev['u_total_bytes']) - int(now['u_total_bytes'])
rate_up = round(int(delta_up/delta_time) / IfaceObject.divisor, 3)
if rate_up > IfaceObject.stats[iface]['up']:
IfaceObject.stats[iface]['up'] = rate_up
rate_down = round(int(delta_down/delta_time) / IfaceObject.divisor, 3)
if rate_down > IfaceObject.stats[iface]['down']:
IfaceObject.stats[iface]['down'] = rate_down
iface_res = iface_dict.copy()
iface_res.update(iface = iface,
up = rate_up,
down = rate_down)
result.append(iface_res)
return result
class NetworkData:
dev_path = "/sys/class/net"
data_path = "/proc/net/dev"
def __init__(self, blacklist):
self.blacklist = blacklist
for root, dirs, files in walk(self.dev_path):
self.available_ifaces = dirs
self.mon_ifaces = list(i for i in self.available_ifaces if i not in self.blacklist)
def instance_loop(self):
# [2:] ignore the last two char of the line
for raw_data in open(self.data_path).readlines()[2:]:
current_iface_data = [list(filter(lambda raw_data: raw_data, rd.split(" ")))
for rd in [raw_data]][0]
#enpxs0 [:-1] ignore last char of the string
current_iface_data[0] = current_iface_data[0][:-1]
current_iface_data[-1] = current_iface_data[-1][:-1]
if current_iface_data[0] in self.mon_ifaces:
IfaceObject(current_iface_data)
format_down = "{interface} down"
blacklist = ['lo']
interval = 1
divisor = 1024
width = 6
def unit_translation(value, width):
units = ['K', 'M', 'G']
for i in range(len(units)):
reducedRate = int(value / (1024 ** i))
if len(str(reducedRate)) < (width - 1) :
res_len = len(str(reducedRate))
result = round(float(reducedRate), max(0, width - res_len))
result = int(result) if result.is_integer() else result
return f"{result:{width + 2}}{units[i]}"
return -1
def printBar(ifacesData):
result = f""
for ifaceData in ifacesData:
result += f"|{ifaceData['interface']} : {ifaceData['up']} {ifaceData['down']}|"
# adding end="\r" to print() on the same line over and over
print(result, end="\r")
def main():
networkData = NetworkData(blacklist)
while True:
networkData.instance_loop()
formatValue = []
for rates in IfaceObject.inst_rate():
interface = rates['iface']
up = f"up : {unit_translation(rates['up'], width)}"
down = f"down : {unit_translation(rates['down'], width)}"
ifaceData = dict(interface=interface, up=up, down=down)
formatValue.append(ifaceData)
printBar(formatValue)
sleep(interval)
return 0
if __name__ == '__main__':
try:
exit(main())
except KeyboardInterrupt:
print('\nBye', end="\n")
exit(0)