Select column item in Python

Asked

Viewed 220 times

0

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

I did it that 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 IP MAC address, in which case it goes out that way.

Example:

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

How can I take, for example, all the content that is on the bottom line, like line 1, 2 or 3. Like I want to pick up AA:BB:CC:DD:EE:01 and put it into a variable.

  • It wasn’t clear what you want to do. What exactly would "pick up the bottom line content"? Down from what? What lines?

1 answer

0

  1. Don’t use the os.popen. To run subprocesses in python always use the module subprocess, as recommended in the documentation of popen.

  2. Always pass the execution parameters as list, so you avoid problems with quotes and shell special characters.

  3. Your question is a bit confusing. It seems like you want to store all the mac address associated with an ip, so I did a function that does just that. As it may come repeated mac address in the result of the command, I used a set (set) to store them, thus you will only have once 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)

Addresses are in the variable resultado, when using the print will be on the screen:

set(['AA:BB:CC:DD:EE:00', 'AA:BB:CC:DD:EE:01'])

Browser other questions tagged

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