欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python获取网卡的ip子网掩码和网关

程序员文章站 2022-06-03 23:21:47
...

import netiface
import os

def getNet():

"""获取所有网口名字"""
NetAll = netifaces.interfaces()
vir_net = []
"""vir_net为虚拟网卡列表"""
"""'ls /sys/devices/virtual/net/为所有虚拟网卡的名字"""
command = 'ls /sys/devices/virtual/net/'
r = os.popen(command)
info = r.readlines()
for line in info:
    line = line.strip('\n')
    vir_net.append(line)
data = []
for i in NetAll:
    if i in vir_net:
        continue
    Gateway = read_set(i)
    try:
        ip = netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr']
        Netmask = netifaces.ifaddresses(i)[netifaces.AF_INET][0]['netmask']
    except:
        ip = ""
        Netmask = ""
    msg = {'NicName': i, 'IPAdder': ip, 'IPNetmask': Netmask, 'Gateway': Gateway}
    data.append(msg)
print(data)

#从网卡配置文件读取网关,若没有则为空

def read_set(i):

re_Gateway = '^(GATEWAY).*\d+$'
path = "/etc/sysconfig/network-scripts/ifcfg-" + str(i)
if os.path.exists(path):
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            if re.match(re_Gateway, line):
                len1 = len(line)
                line = line[8:len1-1]
                return line
        return ""
else:
    return ""