I wrote this piece of code that displays the arp table on a network and it displays the information on multiple lines for each device on the network. I wanted to know if there was a way I can extract the IP Address and Physical Address for each device and as they are the only parts I need. Here are the codes I used to get the ARP table:
for device in os.popen('arp -a'):
print(device)
I am fairly new to Python so I need help on how to get that information from the table we get when these codes are run.
CodePudding user response:
You can split the line on white space and keep the parts that interest you.
for device in os.popen('arp -a'):
# example output: xxxx (192.168.1.254) at xx:xx:xx:xx:xx:xx [ether] on wlp..
_, ip, _, phy, _ = device.split(maxsplit=4)
# remove the paranthesis around the ip address
ip = ip.strip('()')
print(ip, phy)