Select item from a column in Python

1

I have managed to filter the items I want, but they are in a kind of column.

I did it this way:

import os

cmd = os.popen('arping -I enp1s0 -c 2 192.168.0.1')  
arr = cmd.read().split('\n')  
for line in arr:  
        if 'Unicast' in line:  
                a = line.split()  
                b = a[4]  
                c = b[1:18]  
                print c    

The result of print c , is the MAC address of the IP, in which case it exits that way.

Example:

AA:BB:CC:DD:EE:00  
AA:BB:CC:DD:EE:00  
AA:BB:CC:DD:EE:01

How can I get all the content on the bottom line, such as line 1, 2 or 3. I want to get AA:BB:CC:DD:EE:01 and put it in a variable.

    
asked by anonymous 11.10.2018 / 16:43

1 answer

0
  • Do not use os.popen . To run subprocesses in python always use the subprocess module, as recommended at popen .

  • Pass the execution parameters always as a list, so you avoid problems with quotes and special characters in the shell.

  • Your question is confusing. It seems like you want to store all mac addresses associated with an ip, so I did a function that does just that. As it may be that there are repeated mac addresses in the output of the command, I used a set (set) to store them, so you will have only one time each mac address:

    def arping(interface, ip):
        p =  subprocess.check_output(['arping', '-I', interface, '-c', '2', ip])
        enderecos = set()
        for line in p.splitlines():
            if line.startswith('Unicast'):
                mac = line.split()[4].strip('[]')
                enderecos.add(mac)
        return enderecos
    
  • To use the function:

    resultado = arping('enp1s0', '192.168.0.1')
    print(resultado)
    

    The addresses are in the resultado variable, while using print will exit the screen:

    set(['AA:BB:CC:DD:EE:00', 'AA:BB:CC:DD:EE:01'])
    
        
    11.10.2018 / 17:40