I need to create a Python script that queries the network interfaces and returns me the name of the host, the IP address, and the mac address.
#!/usr/bin/env python3
import netifaces
x = netifaces.interfaces()
i = x[0]
for i in x:
if i != 'lo':
print(i)
face = netifaces.ifaddresses(i)
print(face)
i += i
else:
continue
This is one version of the program I am working with. This seems to grab all the data that I need but I cannot get it to print clean or correctly! I am looking for something like: "Nic: wlan0, ipaddr: 10.0.0.1, mac: 4651168584541"
I am new to programming and very new to python so please any help is appreciated!
Please check the links:
@camflan's response in Getting MAC Address
How to get the physical interface IP address from an interface
import netifaces x = netifaces.interfaces() for i in x: if i != 'lo': print(i) print("mac:" + netifaces.ifaddresses(i)[netifaces.AF_LINK][0]['addr'] + " ipaddr:" + netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr']) i += i else: continue
So this was a little tricky at first but this format should allow you to grab data from the results of netifaces.
import netifaces
x = netifaces.interfaces()
for i in x:
if i != 'lo':
print('\nInterface: ' + i)
mac = netifaces.ifaddresses(i)[netifaces.AF_LINK][0]['addr']
print('Mac addr: ' + mac)
try:
ip = netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr']
print('IP addr: {0} '.format(ip))
except KeyError:
print('NO IP')
continue
Output will look as follows:
Interface: eth0
Mac add: eo:ie:9:38:ri
No IP
Interface: wlan0
Mac addr: 34:po:iu:66
IP addr: 10.0.0.1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.