Skip to content

Instantly share code, notes, and snippets.

@GIJack
Last active October 24, 2023 06:35
Show Gist options
  • Save GIJack/d8577e4b52aacce6af5a8ae39eb3b951 to your computer and use it in GitHub Desktop.
Save GIJack/d8577e4b52aacce6af5a8ae39eb3b951 to your computer and use it in GitHub Desktop.
get drive/disk information in python
import json
import subprocess
def byte2str(in_string):
'''convert bytes into string'''
output = str(in_string.strip())
output = output.lstrip("b")
output = output.strip("\'")
return output
def get_drive_tables():
'''get lsblk data and return it as a structured dict{}'''
list_drives_cmd = "lsblk -J -o +LABEL"
list_drives = subprocess.Popen(list_drives_cmd, shell=True, stdout=subprocess.PIPE)
drive_table, err = list_drives.communicate()
drive_table = byte2str(drive_table)
drive_table = drive_table.replace('\\n','\n')
drive_table = json.loads(drive_table)
return drive_table
@j77h
Copy link

j77h commented Oct 24, 2023

Thanks for that.
I needed a quick listing of UFDs (USD Flash Drives),
and starting with your code, ended up with the code below.

Now I can put a UFD in every port (usually 6~8 ports available),
then run another script that catalogs what's on them (into SQLite)
without any manual mounting etc.

Note: I use prefixes to keep track of data-types, e.g. d for dict, l for list, bs for bytestring.

# list_usb_drives.py

import json
import subprocess

def get_drive_info():
   cmd = "lsblk -J -o name,label,fstype,tran"   # NB: use name; if kname, no children !
   subproc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE )
   bs_json, err = subproc.communicate()
   s_json = str(bs_json.strip()).lstrip("b").strip("\'").replace('\\n','\n')
   return json.loads( s_json )   # a dict

def list_usb_drives( d_drives ):
   l_devs = d_drives['blockdevices']
   l_usb_drives = []
   for d_dev in l_devs :
      if d_dev['tran'] == 'usb' :            # tran is transport; we leave out sata, scsi, etc
         l_children = d_dev.get('children')   # children means partitions
         if l_children :
            for d_child in l_children :
               l_usb_drives.append( ( d_child['name'], d_child['label'] ) )
         else :
            print(f"{d_dev['name']} has no partitions")
   return l_usb_drives

if __name__ == '__main__':
   d_drives = get_drive_info()
   l_usb_drives = list_usb_drives( d_drives )
   print( l_usb_drives )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment