我目前需要查明any网络接口(在RHEL上)是否配置为使用python(最好是python2,但如果有使用python3的解决方案,我想听听)使用动态IP(DHCP)。
我不想抛出 bash 子进程,只解析来自
ip route
或 nmcli
的响应。
到目前为止我们尝试/发现的内容:
/sys/class/net
上可以看到接口,上面有很多属性,但似乎没有一个能提供我们想要的。也许还有另一个 Linux 界面可以给我们这个?!/etc/sysconfig/network-scripts/ifcfg-**
上,可以看到每个接口的选项(我猜 NetworkManager 是所有者),并且可以解析 BOOTPROTO=
选项。然而,这并不一定显示当前的连接方法,因为人们可以更改该文件,甚至可以通过nmcli
修改界面,并且只有在界面重新启动(向下/向上)后才会读取注意:抱歉,如果某些特定的网络术语使用不正确,我不是那里的专家:)
有什么想法吗?有什么想法吗?
这是一个仅列出目录/读取配置文件的示例,我只关心真实的IP接口:
import os
import psutil
def get_network_interfaces():
interfaces = psutil.net_if_addrs()
return interfaces
def get_interface_types():
interface_names = os.listdir(r'/etc/network/interfaces.d/')
inet_types = dict()
for inet in interface_names:
# inet: eth0.cfg
interface_file_path = f'/etc/network/interfaces.d/{inet}'
with open(interface_file_path, 'r') as file:
content = file.read().replace('\n', ' ')
inet_types[inet[:-4]] = 'Static' if 'manual' in content else 'DHCP'
return inet_types
def print_network_info():
interfaces = get_network_interfaces()
interfaces_types = get_interface_types()
print("Network Interfaces:")
for interface_name, addresses in interfaces.items():
print(f"Interface: {interface_name}")
for address in addresses:
if str(address.family) == 'AddressFamily.AF_INET':
print(f" IP Address: {address.address}")
print(f" Type: {interfaces_types.get(interface_name)}")
print()
if __name__ == "__main__":
print_network_info()