0

So I am writing a small script which needs to capture only the RX/TX packets/errors/bytes from "ifconfig" and translate it into dictionary/json format

It should look something like this:

{
         'rx_packets': 'value',
         'tx_packets': 'value',
         'rx_bytes': 'value',
         'tx_bytes': 'value',
         'rx_errors': 'value',
         'tx_errors': 'value',
        
    }

I am not sure how to extract the output off the regex so it becomes a dictionary.

This is the script:

ifconfig=subprocess.Popen('ifconfig', shell=True, stdout=subprocess.PIPE,).communicate()[0]
    
pattern = re.compile(br'\s+(?P<type>RX|TX)\s(packets|errors)\s+(\d+)\s+(bytes|dropped)\s+(\d+)', re.MULTILINE)

prnt=(re.findall(pattern, ifconfig))

for match in prnt:
    print (match)

The current output is:

(b'RX', b'packets', b'2197707', b'bytes', b'2500953222')
(b'RX', b'errors', b'0', b'dropped', b'74419')
(b'TX', b'packets', b'700405', b'bytes', b'148862473')
(b'TX', b'errors', b'0', b'dropped', b'0')
(b'RX', b'packets', b'61522', b'bytes', b'10087739')
(b'RX', b'errors', b'0', b'dropped', b'0')
(b'TX', b'packets', b'61522', b'bytes', b'10087739')
(b'TX', b'errors', b'0', b'dropped', b'0')
(b'RX', b'packets', b'0', b'bytes', b'0')
(b'RX', b'errors', b'0', b'dropped', b'0')
(b'TX', b'packets', b'0', b'bytes', b'0')
(b'TX', b'errors', b'0', b'dropped', b'0'
Sunfl0wa
  • 1
  • 3
  • Use the `encoding` argument to `subprocess.Popen()` to make it return text strings instead of byte strings. – Barmar Feb 15 '21 at 22:57
  • Although this was part of my question, I removed it so it becomes more clear on what I need help with. Thank you for the similar topic link. – Sunfl0wa Feb 15 '21 at 23:03
  • Use a dictionary comprehension to create a dictionary from the output. – Barmar Feb 15 '21 at 23:08

1 Answers1

0

Use the encoding option to get the output as strings rather than bytes. Then create the desired dictionary entries in the loop.

ifconfig=subprocess.Popen('ifconfig', shell=True, stdout=subprocess.PIPE, encoding='utf-8')
output=ifconfig.communicate()[0]

pattern = re.compile(r'\s+(?P<type>RX|TX)\s(packets|errors)\s+(\d+)\s+(bytes|dropped)\s+(\d+)', re.MULTILINE)

prnt=(re.findall(pattern, output))

result = {}
for rxtx, type1, count1, type2, count2 in prnt:
    rxtx = rxtx.lower()
    result[f'{rxtx}_{type1}'] = int(count1)
    result[f'{rxtx}_{type2}'] = int(count2)

print(result)
Barmar
  • 741,623
  • 53
  • 500
  • 612