python 获取linux 网卡IP地址和mac地址
时间: 2024-11-09 21:21:49 浏览: 31
Python获取本机所有网卡ip,掩码和广播地址实例代码
在Python中,你可以使用内置模块如`ipifaces`、`netifaces`或者第三方模块`psutil`来获取Linux系统的网卡IP地址和MAC地址。这里以`netifaces`为例,这是一个广泛用于网络配置信息查询的库:
```python
import netifaces
def get_ip_address_and_mac(interface_name='eth0'):
try:
# 获取指定网卡的信息
ifi = netifaces.ifaddresses(interface_name)
# 对于IPv4地址
ip_address =ifi[netifaces.AF_INET][0]['addr']
# 对于MAC地址(通常在IFADDRS层)
mac_address = ifi[netifaces.AF_LINK][0]['addr']
return ip_address, mac_address
except Exception as e:
print(f"Failed to get IP and MAC address for {interface_name}: {e}")
return None, None
# 使用示例
ip, mac = get_ip_address_and_mac()
if ip and mac:
print(f"Interface {interface_name} has IP address: {ip}, MAC address: {mac}")
else:
print("No valid network interface found.")
```
阅读全文