Wednesday, May 8, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 2429  / 1 Year ago, mon, march 6, 2023, 10:25:37

I want to retrieve the daily internet usage from my Ubuntu machine in Json format using Vnstat.
To fetch the daily usage in terminal I use following command:



vnstat -d -i wlp2s0


the output will be:



wlp2s0  /  daily

day rx | tx | total | avg. rate
------------------------+-------------+-------------+---------------
,ۋ6� 60 KiB | 27 KiB | 87 KiB | 0.01 kbit/s
,ۋ6� 333.00 MiB | 170.16 MiB | 503.16 MiB | 47.71 kbit/s
,ۋ6� 626.23 MiB | 39.64 MiB | 665.87 MiB | 63.13 kbit/s
,ۋ6� 172.47 MiB | 177.32 MiB | 349.79 MiB | 33.16 kbit/s
,ۋ6� 11.88 MiB | 1.66 MiB | 13.54 MiB | 1.28 kbit/s
,ۋ6� 0 KiB | 0 KiB | 0 KiB | 0.00 kbit/s
,ۋ6� 380.47 MiB | 21.22 MiB | 401.69 MiB | 38.09 kbit/s
,ۋ6� 173.32 MiB | 14.71 MiB | 188.03 MiB | 17.83 kbit/s
,ۋ6� 0 KiB | 0 KiB | 0 KiB | 0.00 kbit/s
,ۋ6� 0 KiB | 0 KiB | 0 KiB | 0.00 kbit/s
,ۋ6� 17.49 MiB | 4.33 MiB | 21.82 MiB | 2.07 kbit/s
,ۋ6� 70 KiB | 73 KiB | 143 KiB | 0.01 kbit/s
,ۋ6� 15.12 MiB | 1.95 MiB | 17.07 MiB | 1.62 kbit/s
,ۋ6� 18.45 MiB | 5.86 MiB | 24.31 MiB | 3.55 kbit/s
------------------------+-------------+-------------+---------------
estimated 27 MiB | 7 MiB | 34 MiB |


So how to retrieve Only the total, rx and tx value that is estimated 27 MiB | 7 MiB | 34 MiB |from the above output in Json format
in the form:



{"daily_usage":{"rx":27,"tx":7,"total":34}}


Actually I am trying to pass this json format to python script later
Thaks in advance!!


More From » command-line

 Answers
7

vnstat has options to output in machine-readable formats. From man vnstat:



--json mode
Show database content for selected interface or all interfaces
in json format. All traffic values in the output are in KiB. An
optional mode parameter can be used for limiting the output to
only selected information. Everything is shown by default.
Setting mode to 'h' will output only hours, 'd' days, 'm' months
and 't' the top 10.

--xml mode
Show database content for selected interface or all interfaces
in xml format. All traffic values in the output are in KiB. An
optional mode parameter can be used for limiting the output to
only selected information. Everything is shown by default.
Setting mode to 'h' will output only hours, 'd' days, 'm' months
and 't' the top 10.


Just do vnstat -i wlp2s0 --json d and parse it in Python to get whichever field you need. The -d is not needed, and will be ignored, since the --json option takes the mode argument.


[#9967] Tuesday, March 7, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
olltea

Total Points: 238
Total Questions: 115
Total Answers: 107

Location: Moldova
Member since Tue, Feb 7, 2023
1 Year ago
;