python - 如何使用 python 或 cmd 从 windows 获取连接的 USB 设备列表
问题描述
我需要使用 python 或 cmd 从 windows 获取连接的 USB 设备列表。
对于 python 我正在尝试这个。
import win32com.client
def get_usb_device():
try:
usb_list = []
wmi = win32com.client.GetObject("winmgmts:")
for usb in wmi.InstancesOf("Win32_USBHub"):
print(usb.DeviceID)
print(usb.description)
usb_list.append(usb.description)
print(usb_list)
return usb_list
except Exception as error:
print('error', error)
get_usb_device()
结果我得到了这个:
['USB Root Hub (USB 3.0)', 'USB Composite Device', 'USB Composite Device']
但我没有得到一个有意义的全名。
对于 cmd 我也在尝试这个:
wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value
再一次,我没有得到任何有意义的全名连接的 USB 设备。
当我通过 USB 连接鼠标、键盘、笔式驱动器或打印机时,我想要这种名称。像“a4tech 鼠标”或者即使我得到“鼠标”也可以。这种类型的名称出现在 Windows 10 设置的设备部分。但我得到“USB Root Hub (USB 3.0)”、“USB 复合设备”,实际上没有任何意义。用python可以吗?
如果有人知道这个答案,请帮助。它对我来说非常重要。
解决方案
不确定它是否是您要查找的内容,但是在带有pywin32的 Windows 10 上使用 Python 3 ,您可以使用它来获取所有驱动器号和类型:
import os
import win32api
import win32file
os.system("cls")
drive_types = {
win32file.DRIVE_UNKNOWN : "Unknown\nDrive type can't be determined.",
win32file.DRIVE_REMOVABLE : "Removable\nDrive has removable media. This includes all floppy drives and many other varieties of storage devices.",
win32file.DRIVE_FIXED : "Fixed\nDrive has fixed (nonremovable) media. This includes all hard drives, including hard drives that are removable.",
win32file.DRIVE_REMOTE : "Remote\nNetwork drives. This includes drives shared anywhere on a network.",
win32file.DRIVE_CDROM : "CDROM\nDrive is a CD-ROM. No distinction is made between read-only and read/write CD-ROM drives.",
win32file.DRIVE_RAMDISK : "RAMDisk\nDrive is a block of random access memory (RAM) on the local computer that behaves like a disk drive.",
win32file.DRIVE_NO_ROOT_DIR : "The root directory does not exist."
}
drives = win32api.GetLogicalDriveStrings().split('\x00')[:-1]
for device in drives:
type = win32file.GetDriveType(device)
print("Drive: %s" % device)
print(drive_types[type])
print("-"*72)
os.system('pause')
您的 USB 设备具有该类型win32file.DRIVE_REMOVABLE
- 所以这就是您要寻找的。if
您可以插入一个仅处理此类可移动设备的条件,而不是打印所有驱动器和类型。
请注意: SD 卡和其他可移动存储介质具有相同的驱动器类型。
!
2020 年 7 月 13 日更新:
要获取有关已连接设备的更多信息,请查看 Python 的 WMI 模块。
检查此示例输出,它们列出了有关设备的不同信息,包括制造商描述、序列号等:
import wmi
c = wmi.WMI()
for item in c.Win32_PhysicalMedia():
print(item)
for drive in c.Win32_DiskDrive():
print(drive)
for disk in c.Win32_LogicalDisk():
print(disk)
os.system('pause')
要访问此输出中列出的特定信息,请使用显示的条款进行直接访问。例子:
for disk in c.Win32_LogicalDisk():
print(disk.Name)
推荐阅读
- python - 在从 Dockerhub 拉取图像后,我正在标记图像
- python - 在这种情况下,我们可以形成一个 Python 列表理解吗?
- python - 如何在 python 中对海龟进行碰撞检测?
- python - 如何使用 get_context_data 在 Django 的基于类的视图中检查用户身份验证
- html - 当孩子进行变换旋转时,背面可见性停止工作
- scala - 使用 PureConfig 将空属性解析为空 Map
- javascript - 使用 AJAX 在 JSON 中搜索
- laravel - 我收到错误 array_merge 预期参数 2 在 laravel 8 工厂?
- express - EJS 中的手风琴问题
- sql - 在 DB2/400 上使用 CONNECT_BY_ROOT 进行分层查询