Skip to content

Commit 382033b

Browse files
authored
Add function to get default network interface (#142)
* Add function to get default network interface * Change byte conversion thresholds from 1024 to 1000
1 parent cc5d095 commit 382033b

1 file changed

Lines changed: 51 additions & 15 deletions

File tree

sysmonitor_common/sensors.py

Lines changed: 51 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,21 @@
3030
B_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB']
3131
cpu_load = []
3232

33-
33+
def get_default_iface():
34+
try:
35+
out = subprocess.check_output(
36+
"ip route show default",
37+
shell=True
38+
).decode()
39+
40+
for line in out.splitlines():
41+
parts = line.split()
42+
if "dev" in parts:
43+
return parts[parts.index("dev") + 1]
44+
45+
except Exception:
46+
return None
47+
3448
def bytes_to_human(num):
3549
for unit in B_UNITS:
3650
if abs(num) < 1000.0:
@@ -590,21 +604,42 @@ def get_value(self, sensor_data):
590604
return self._fetch_net()
591605

592606
def _fetch_net(self):
593-
"""It returns the bytes sent and received in bytes/second"""
594-
current = [0, 0]
595-
for _, iostat in list(ps.net_io_counters(pernic=True).items()):
596-
current[0] += iostat.bytes_recv
597-
current[1] += iostat.bytes_sent
598-
dummy = copy.deepcopy(current)
607+
rx = 0
608+
tx = 0
609+
610+
iface = get_default_iface()
611+
612+
if not iface:
613+
iface = "enp3s0"
614+
615+
net = ps.net_io_counters(pernic=True)
616+
617+
if iface in net:
618+
iostat = net[iface]
619+
rx = iostat.bytes_recv
620+
tx = iostat.bytes_sent
621+
622+
current = [rx, tx]
623+
624+
if self._last_net_usage == [0, 0]:
625+
self._last_net_usage = copy.deepcopy(current)
626+
return "↓0K ↑0K"
627+
628+
speed_rx = current[0] - self._last_net_usage[0]
629+
speed_tx = current[1] - self._last_net_usage[1]
630+
631+
self._last_net_usage = copy.deepcopy(current)
599632

600-
current[0] -= self._last_net_usage[0]
601-
current[1] -= self._last_net_usage[1]
602-
self._last_net_usage = dummy
603633
mgr = SensorManager()
604-
current[0] /= mgr.get_interval()
605-
current[1] /= mgr.get_interval()
606-
# 把current[0]和current[1],转为KB,不要小数点。
607-
def bytes_to_human_custome(n):
634+
interval = mgr.get_interval()
635+
636+
if interval <= 0:
637+
interval = 1
638+
639+
speed_rx /= interval
640+
speed_tx /= interval
641+
642+
def bytes_to_human(n):
608643
if n < 1000:
609644
return "{}B".format(int(n))
610645
elif n < 1000 * 1000:
@@ -615,7 +650,8 @@ def bytes_to_human_custome(n):
615650
return "{}G".format(int(n / 1000 / 1000 / 1000))
616651

617652
return "↓{:>2s} ↑{:>2s}".format(
618-
bytes_to_human_custome(current[0]), bytes_to_human_custome(current[1])
653+
bytes_to_human(speed_rx),
654+
bytes_to_human(speed_tx)
619655
)
620656

621657
class BatSensor(BaseSensor):

0 commit comments

Comments
 (0)