怎么用脚本获取网络配置

wen 实用脚本 2

本文目录导读:

怎么用脚本获取网络配置

  1. Linux Shell 脚本
  2. Python 脚本
  3. Windows PowerShell 脚本
  4. 跨平台 Python 脚本(Windows + Linux)
  5. 简单的命令行快捷方式

Linux Shell 脚本

获取基础网络配置

#!/bin/bash
echo "=== 网络接口信息 ==="
ifconfig -a 2>/dev/null || ip addr show
echo -e "\n=== 路由表 ==="
route -n 2>/dev/null || ip route show
echo -e "\n=== DNS配置 ==="
cat /etc/resolv.conf
echo -e "\n=== 当前IP地址 ==="
hostname -I 2>/dev/null || ip addr show | grep 'inet ' | awk '{print $2}'

获取详细的IP配置

#!/bin/bash
echo "=== 活跃网络接口详情 ==="
for interface in $(ls /sys/class/net/ | grep -v lo); do
    echo "接口: $interface"
    echo "  MAC地址: $(cat /sys/class/net/$interface/address)"
    echo "  IP地址: $(ip addr show $interface | grep 'inet ' | awk '{print $2}')"
    echo "  状态: $(cat /sys/class/net/$interface/operstate)"
    echo "---"
done

Python 脚本

使用 socket 库

import socket
import subprocess
import json
def get_network_config():
    config = {}
    # 获取主机名和IP
    hostname = socket.gethostname()
    ip_addr = socket.gethostbyname(hostname)
    config['hostname'] = hostname
    config['ip'] = ip_addr
    # 获取所有网络接口信息
    interfaces = []
    try:
        result = subprocess.run(['ip', 'addr', 'show'], 
                              capture_output=True, text=True)
        interfaces = result.stdout.split('\n')
    except:
        pass
    config['interfaces'] = interfaces
    return config
# 使用
config = get_network_config()
print(json.dumps(config, indent=2))

使用 psutil 库(更友好)

import psutil
import socket
def get_nic_config():
    # 获取网络接口信息
    addrs = psutil.net_if_addrs()
    stats = psutil.net_if_stats()
    for interface_name, interface_addrs in addrs.items():
        print(f"\n接口: {interface_name}")
        print(f"状态: {'UP' if stats[interface_name].isup else 'DOWN'}")
        for addr in interface_addrs:
            if addr.family == socket.AF_INET:
                print(f"  IPv4: {addr.address}")
                print(f"  掩码: {addr.netmask}")
                print(f"  广播: {addr.broadcast}")
            elif addr.family == socket.AF_INET6:
                print(f"  IPv6: {addr.address}")
    # 获取路由信息
    print("\n=== 路由信息 ===")
    routes = psutil.net_connections()
    # 获取DNS服务器(Linux)
    try:
        with open('/etc/resolv.conf', 'r') as f:
            print("\n=== DNS 配置 ===")
            for line in f:
                if 'nameserver' in line:
                    print(line.strip())
    except:
        pass
get_nic_config()

Windows PowerShell 脚本

# 获取网络配置
Write-Host "=== IP 配置 ===" -ForegroundColor Green
Get-NetIPAddress -AddressFamily IPv4 | 
    Format-Table InterfaceAlias, IPAddress, PrefixLength, 
        @{L='Mask';E={(([System.Net.IPAddress]::Parse('255.255.255.255')) -shr (32-$_.PrefixLength)) }},
        @{L='Gateway';E={(Get-NetIPConfiguration -InterfaceIndex $_.InterfaceIndex).IPv4DefaultGateway.NextHop}} -AutoSize
Write-Host "`n=== 网卡信息 ===" -ForegroundColor Green
Get-NetAdapter | Format-Table Name, Status, MacAddress, LinkSpeed -AutoSize
Write-Host "`n=== DNS 配置 ===" -ForegroundColor Green
Get-DnsClientServerAddress -AddressFamily IPv4 |
    Where-Object {$_.ServerAddresses} |
    Format-Table InterfaceAlias, ServerAddresses -AutoSize
# 导出到文件
$config = Get-NetIPConfiguration | Select-Object InterfaceAlias, 
    @{N='IPv4';E={$_.IPv4Address.IPAddress}},
    @{N='Gateway';E={$_.IPv4DefaultGateway.NextHop}},
    @{N='DNS';E={$_.DNSServer.ServerAddresses -join ', '}}
$config | Export-Csv -Path "network_config.csv" -NoTypeInformation

跨平台 Python 脚本(Windows + Linux)

import platform
import subprocess
import re
import os
def get_network_info():
    system = platform.system()
    info = {}
    if system == "Windows":
        # Windows 使用 ipconfig
        result = subprocess.run(['ipconfig', '/all'], 
                              capture_output=True, text=True)
        info['raw_output'] = result.stdout
    else:
        # Linux/Mac 使用 ifconfig/ip
        try:
            result = subprocess.run(['ifconfig', '-a'], 
                                  capture_output=True, text=True)
            info['raw_output'] = result.stdout
        except:
            result = subprocess.run(['ip', 'addr'], 
                                  capture_output=True, text=True)
            info['raw_output'] = result.stdout
    # 解析IP地址
    ip_pattern = r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
    info['ip_addresses'] = re.findall(ip_pattern, info['raw_output'])
    # 获取网关
    if system == "Windows":
        route_result = subprocess.run(['route', 'print'], 
                                    capture_output=True, text=True)
        info['route_info'] = route_result.stdout
    else:
        route_result = subprocess.run(['route', '-n'], 
                                    capture_output=True, text=True)
        info['route_info'] = route_result.stdout
    return info
# 执行
info = get_network_info()
print("系统: ", platform.system())
print("IP地址列表: ", info['ip_addresses'][:10])  # 显示前10个

简单的命令行快捷方式

Linux/Mac 一行命令

# 获取所有IP
hostname -I
# 获取网关
ip route | grep default
# 获取DNS
cat /etc/resolv.conf | grep nameserver
# 获取MAC和IP
ip -brief address
# 完整信息
ip addr && ip route && cat /etc/resolv.conf

Windows 一行命令

:: 获取IP配置
ipconfig /all
:: 获取网关
ipconfig | findstr /i "gateway"
:: 获取DNS
nslookup localhost %COMPUTERNAME%

选择哪个脚本取决于您的需求:

  • 快速查看: 使用命令行快捷方式
  • 简单脚本: 使用 Shell/PowerShell
  • 复杂分析: 使用 Python + psutil
  • 跨平台: Python 脚本更合适

需要我详细解释某个脚本的实现或定制功能吗?

抱歉,评论功能暂时关闭!