简体   繁体   English

使用python列出所有USB大容量存储磁盘

[英]Listing all usb mass storage disks using python

I have few USB disks inserted in my system. 我的系统中插入了几个USB磁盘。 I would like to list all of them like:- 我想列出所有这些人:

/dev/sdb
/dev/sdc
.... ans so on..

Please remember that I don't want to list partitions in it like /dev/sdb1 . 请记住,我不想像/dev/sdb1这样列出分区。 I am looking for solution under Linux. 我正在寻找Linux下的解决方案。 Tried cat /proc/partitions . 尝试过cat /proc/partitions

major minor  #blocks  name

   8        0  488386584 sda
   8        1   52428800 sda1
   8        2   52428711 sda2
   8        3          1 sda3
   8        5   52428800 sda5
   8        6   15728516 sda6
   8        7  157683712 sda7
   8        8  157682688 sda8
  11        0    1074400 sr0
  11        1      47602 sr1
   8       32    3778852 sdc
   8       33          1 sdc1
   8       37    3773440 sdc5

But it list all the disks and unable to figure which one is USB storage disks. 但是它列出了所有磁盘,无法确定哪一个是USB存储磁盘。 I am looking for a solution which does not require an additional package installation. 我正在寻找不需要额外安装软件包的解决方案。

/dev列出正确的路径:

ls -l /dev/disk/by-path/*-usb-* | fgrep -v part

You can convert Klaus D.'s suggestion into Python code like this: 您可以将Klaus D.的建议转换为Python代码,如下所示:

#!/usr/bin/env python

import os

basedir = '/dev/disk/by-path/'

print 'All USB disks'

for d in os.listdir(basedir):
    #Only show usb disks and not partitions
    if 'usb' in d and 'part' not in d:
        path = os.path.join(basedir, d)
        link = os.readlink(path)
        print '/dev/' + os.path.basename(link)

path contains info in this format: path包含以下格式的信息:
/dev/disk/by-path/pci-0000:00:1d.7-usb-0:5:1.0-scsi-0:0:0:0
which is a symbolic link, so we can get the pseudo-scsi device name using os.readlink() . 这是一个符号链接,因此我们可以使用os.readlink()获得伪scsi设备名称。
But that returns info in this format: 但这会以以下格式返回信息:
../../sdc
so we use os.path.basename() to clean it up. 因此我们使用os.path.basename()进行清理。

Instead of using 而不是使用
'/dev/' + os.path.basename(link)
you can produce a string in the '/dev/sdc' format by using 您可以使用以下命令生成'/dev/sdc'格式的字符串
os.path.normpath(os.path.join(os.path.dirname(path), link))
but I think you'll agree that the former technique is simpler. 但我认为您会同意前一种技术更简单。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM