怎么用脚本获取网络连接名称

wen 实用脚本 1

本文目录导读:

怎么用脚本获取网络连接名称

  1. Windows (PowerShell)
  2. Windows (CMD/Batch)
  3. Linux (Bash)
  4. macOS (Bash)
  5. Python (跨平台)
  6. 保存结果到变量(以PowerShell为例)
  7. 实用脚本示例:显示当前活跃连接

Windows (PowerShell)

# 方法1:获取所有网络适配器名称
Get-NetAdapter | Select-Object Name, Status | Format-Table -AutoSize
# 方法2:仅获取已连接的网络名称
Get-NetAdapter | Where-Object Status -eq "Up" | Select-Object Name
# 方法3:获取更详细的信息
netsh interface show interface

Windows (CMD/Batch)

@echo off
REM 方法1:获取所有网络连接
netsh interface show interface | findstr /v "..........................."
REM 方法2:仅获取已连接的
for /f "tokens=3*" %%a in ('netsh interface show interface ^| find "已连接"') do echo %%b

Linux (Bash)

#!/bin/bash
# 方法1:使用ip命令
ip -o link show | awk -F': ' '{print $2}'
# 方法2:仅显示已启用的(状态为UP)
ip link show | grep "state UP" | awk '{print $2}' | sed 's/://'
# 方法3:显示网络接口名称和状态
nmcli device status | awk 'NR>1 {print $1, $2}'
# 方法4:使用ifconfig(可能需要安装net-tools)
ifconfig -a | grep "^[a-z]" | awk '{print $1}'

macOS (Bash)

#!/bin/bash
# 方法1:显示所有网络服务
networksetup -listallnetworkservices | grep -v "An asterisk"
# 方法2:仅显示活跃的网络接口
ifconfig | grep "^[a-z]" | awk -F: '{print $1}'
# 方法3:显示详细网络信息
system_profiler SPNetworkDataType | grep "BSD Device Name:" | awk '{print $4}'

Python (跨平台)

import subprocess
import sys
def get_network_names():
    """获取网络连接名称(跨平台)"""
    system = sys.platform
    if system.startswith('win'):
        # Windows
        import wmi
        c = wmi.WMI()
        adapters = c.Win32_NetworkAdapter(NetEnabled=True)
        return [a.Name for a in adapters if a.Name]
    elif system.startswith('linux') or system.startswith('darwin'):
        # Linux/macOS
        result = subprocess.run(['ip', 'link', 'show'], 
                                capture_output=True, 
                                text=True)
        lines = result.stdout.split('\n')
        names = []
        for line in lines:
            if ':' in line and line[0].isalpha():
                name = line.split(':')[1].strip()
                names.append(name)
        return names
    return []
# 使用示例
networks = get_network_names()
for name in networks:
    print(name)

保存结果到变量(以PowerShell为例)

# 将网络名称保存到变量
$networkName = (Get-NetAdapter | Where-Object Status -eq "Up").Name
Write-Host "当前使用的网络连接: $networkName"
# 保存所有网络名称到数组
$allNetworks = @()
Get-NetAdapter | ForEach-Object { $allNetworks += $_.Name }
$allNetworks

实用脚本示例:显示当前活跃连接

Windows PowerShell脚本:

# 显示当前活跃的WiFi连接
$wifi = netsh wlan show interfaces | Select-String "SSID" | ForEach-Object { 
    $_ -replace ".*:\s+", "" 
}
Write-Host "当前WiFi: $wifi"
# 显示以太网连接
$ethernet = Get-NetAdapter | Where-Object {
    $_.Status -eq "Up" -and $_.MediaType -eq "802.3"
} | Select-Object -ExpandProperty Name
Write-Host "以太网连接: $ethernet"

选择什么方法取决于你的操作系统和使用场景,PowerShell 在 Windows 下最强大,而 Linux/macOS 使用 bash 更直接,Python 脚本则适合跨平台需求。

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