Find string fields with python regular expressions

Asked

Viewed 43 times

0

I am logging into a device and giving an ifconfig on it, the generated information is:

['ifconfig']
['>ifconfig']
['br0       Link encap', 'Ethernet  HWaddr A4:33:D7:53:5E:08  ']
['          inet addr', '192.168.15.1  Bcast:192.168.15.255  Mask:255.255.255.0']
['          inet6 addr', ' 2804:431:c7c7:6528:a633:d7ff:fe53:5e08/64 Scope:Global']
['          inet6 addr', ' fe80::a633:d7ff:fe53:5e08/64 Scope:Link']
['          UP BROADCAST RUNNING ALLMULTI MULTICAST  MTU', '1500  Metric:1']
['          RX packets', '6563071 errors:0 dropped:0 overruns:0 frame:0']
['          TX packets', '7874170 errors:0 dropped:0 overruns:0 carrier:0']
['          collisions', '0 txqueuelen:0 ']
['          RX bytes', '714777540 (681.6 MiB)  TX bytes:886124155 (845.0 MiB)']
['']
['br0', '0     Link encap:Ethernet  HWaddr A4:33:D7:53:5E:08  ']
['          inet addr', '192.168.249.1  Bcast:192.168.249.3  Mask:255.255.255.252']
['          UP BROADCAST RUNNING ALLMULTI MULTICAST  MTU', '1500  Metric:1']

Inside these fields I need to search only some information.

I did so, but it’s not working:

for chave in saida:
    #print(chave)
    aux = chave.split(":",1)
    print(aux)
    if aux[0] == 'br0       Link encap':
        saida_json['MAC'] = aux[1].strip()
    elif aux[0] == '          inet6 addr':
        saida_json['IPV6'] = aux[1].strip()

1 answer

1

Expensive if you want to get the IP address and the MAC from a device, recommend using a tool that does this. Example to lib like the netifaces, need to install it with pip, an example

import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
mac = ni.ifaddresses('eth0')[ni.AF_LINK][0]['addr']

Or if you still prefer to use regex, I think a better approach would be

import os
import re

ipv4 = re.search(re.compile(r'(?<=inet )(.*)(?=\/)', re.M), os.popen('ip addr show eth0').read()).groups()[0]
ipv6 = re.search(re.compile(r'(?<=inet6 )(.*)(?=\/)', re.M), os.popen('ip addr show eth0').read()).groups()[0]
  • 1

    I liked the resosta (+1) but it seems to me that there will not always be "eth0"...

  • 1

    I agree that it is a very simple example. But in his statement he uses tbm hardcoded to br0. With the netifaces to list all interfaces, simply netifaces.interfaces() which returns a list of intercafes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.