怎么用脚本获取已连接设备

wen 实用脚本 2

本文目录导读:

怎么用脚本获取已连接设备

  1. Windows 环境(PowerShell / CMD)
  2. Linux / macOS 环境(Bash / Zsh)
  3. Python 跨平台脚本(推荐)
  4. 手机/无线设备(ADB / 蓝牙)
  5. 注意事项

获取已连接设备的方式取决于你所在的操作系统和具体需求(局域网设备、USB设备、蓝牙设备等),以下提供几种常见场景的脚本获取方法,涵盖 Windows、macOS/Linux 和 Python 跨平台方案。


Windows 环境(PowerShell / CMD)

获取局域网内所有设备(IP/MAC)

使用 arp -a 命令查看 ARP 缓存表(显示与本机通信过的设备)。

PowerShell 脚本:

# 获取所有ARP条目,过滤出动态条目
$devices = arp -a | Select-String "动态" | ForEach-Object {
    $line = $_ -split '\s+'
    [PSCustomObject]@{
        IP   = $line[0]
        MAC  = $line[1]
        Type = $line[2]
    }
}
$devices | Format-Table -AutoSize

CMD 批处理(简单输出):

@echo off
arp -a
pause

获取当前网络连接的详细信息(IP/网关/DNS)

Get-NetIPConfiguration | Select-Object InterfaceAlias, IPv4Address, IPv4DefaultGateway, DNSServer

获取 USB 已连接设备

Get-PnpDevice | Where-Object {$_.Class -eq "USB" -and $_.Status -eq "OK"}

Linux / macOS 环境(Bash / Zsh)

获取局域网活跃设备(通过 ARP 表)

#!/bin/bash
arp -a | awk '{print $1, $2}' | sed 's/[()]//g' | column -t

获取所有网络接口的 IP 和 MAC

#!/bin/bash
ip -o link show | awk -F': ' '{print $2}' | while read iface; do
    ip addr show $iface 2>/dev/null | grep -E "inet |link/ether" | awk '{print $2}' | paste -d' ' - -
done

扫描局域网所有设备(需要 nmap)

#!/bin/bash
# 先获取本机网关(假设 /24 子网)
gateway=$(route -n | grep 'UG[ ]' | awk '{print $2}')
subnet=$(echo $gateway | cut -d. -f1-3)".0/24"
echo "正在扫描 $subnet ..."
nmap -sn $subnet | grep "Nmap scan report" | awk '{print $5}'

获取 USB 设备列表

lsusb
# 或更详细
lsusb -v | grep -E "iManufacturer|iProduct|iSerial"

Python 跨平台脚本(推荐)

Python 通过第三方库可以统一获取局域网设备,且易于扩展。

安装依赖

pip install python-nmap netifaces

获取本机 IP 和子网内的活跃设备

import nmap
import netifaces
def get_local_subnet():
    # 获取默认网关对应的接口和IP
    gateways = netifaces.gateways()
    default_gateway = gateways['default'][netifaces.AF_INET]
    iface = default_gateway[1]
    addr = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]
    ip = addr['addr']
    netmask = addr['netmask']
    # 简单计算子网CIDR(假设C类)
    subnet = '.'.join(ip.split('.')[:3]) + '.0/24'
    return subnet
def scan_network(subnet):
    nm = nmap.PortScanner()
    print(f"正在扫描子网 {subnet} ...")
    nm.scan(hosts=subnet, arguments='-sn')  # -sn 为ping扫描
    devices = []
    for host in nm.all_hosts():
        if nm[host].state() == 'up':
            mac = nm[host]['addresses'].get('mac', 'N/A')
            devices.append({'ip': host, 'mac': mac})
    return devices
if __name__ == '__main__':
    subnet = get_local_subnet()
    devices = scan_network(subnet)
    print("\n已连接的设备(本子网内活跃):")
    for d in devices:
        print(f"IP: {d['ip']:15} MAC: {d['mac']}")

获取本机 USB 设备(跨平台,需 pyusb)

pip install pyusb
import usb.core
import usb.util
devices = usb.core.find(find_all=True)
for dev in devices:
    print(f"USB设备: VID={dev.idVendor:04x}, PID={dev.idProduct:04x}")
    try:
        product = usb.util.get_string(dev, dev.iProduct)
        print(f"  产品名: {product}")
    except:
        pass

手机/无线设备(ADB / 蓝牙)

Android 设备通过 ADB 连接

# 列出已连接的Android设备
adb devices
# 获取设备详细信息
adb -s <device_id> shell ip addr show wlan0

蓝牙已配对/已连接设备(Linux)

# 列出已配对的设备
bluetoothctl devices
# 列出当前连接的设备
bluetoothctl info <MAC地址> | grep "Connected: yes"

注意事项

  1. ARP 表局限性arp -a 只显示本机近期通信过的设备,无法覆盖全部局域网设备。
  2. 权限:网络扫描(如 nmap)可能需要 root/管理员权限。
  3. 防火墙:某些设备可能因防火墙设置无法被扫描到。
  4. 动态 IP:设备 IP 可能变化,建议用 MAC 地址唯一标识。

根据你的实际需求(仅本机接口、局域网扫描、USB/蓝牙),选择合适的方案,如果需要进一步定制(如输出到文件、持续监控),可以告诉我具体场景,我帮你调整脚本。

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