import psutil

def get_ip_address(ifname):
    try:
        return socket.gethostbyname(socket.gethostname())
    except:
        return None


def get_network_info():
    network_info = []
    for interface, addrs in psutil.net_if_addrs().items():
        for addr in addrs:
            if addr.family == socket.AF_INET:  # IPv4
                network_info.append({
                    'interface': interface,
                    'ip_address': addr.address,
                    'netmask': addr.netmask,
                    'broadcast_ip': addr.broadcast
                })
            elif addr.family == socket.AF_INET6:  # IPv6
                network_info.append({
                    'interface': interface,
                    'ipv6_address': addr.address,
                    'netmask': addr.netmask
                })
    return network_info


def get_routing_table():
    routing_table = []
    for interface, stats in psutil.net_if_stats().items():
        routing_table.append({
            'interface': interface,
            'is_up': stats.isup,
            'duplex': stats.duplex,
            'speed': stats.speed,
            'mtu': stats.mtu
        })
    return routing_table


# 获取网络接口的详细信息
body+="\r\n"
print("网卡信息配置:")
body += "网卡信息配置:"
body+="\r\n"
network_details = get_network_info()
print(f"{'interface':30} {'ip_address':20} {'netmask':20}")
body += f"{'interface':30} {'ip_address':20} {'netmask':20}"
body+="\r\n"
for info in network_details:
    #print(info)
    if 'ip_address' in info:
        address_name = "ip_address"
    elif 'ipv6_address' in info:
        address_name = "ipv6_address"
    else:
        print("Error")
    print(f"{info['interface']:30} {info[address_name]:20} {info['netmask']:20}")
    body += f"{info['interface']:30} {info[address_name]:20} {info['netmask']:20}"
    body += "\r\n"

# 获取路由表信息
body+="\r\n"
print("路由表配置:")
body += "路由表配置:"
body+="\r\n"
routing_info = get_routing_table()
print(f"{'interface':30} {'is_up':20} {'duplex':20} {'speed':20} {'mtu':20}")
body+=f"{'interface':30} {'is_up':20} {'duplex':20} {'speed':20} {'mtu':20}"
body+="\r\n"
for route in routing_info:
    #print(route)
    print(f"{route['interface']:30} {route['is_up']:20} {route['duplex']:20} {route['speed']:20} {route['mtu']:20}")
    body+=f"{route['interface']:30} {route['is_up']:20} {route['duplex']:20} {route['speed']:20} {route['mtu']:20}"
    body+="\r\n"
最后修改:2024 年 05 月 11 日
如果觉得我的文章对你有用,请随意赞赏