Monday, April 27, 2015

Python script to map devices with host adapter

#!/bin/env python

import glob
import os,sys
import re

if sys.version_info < (2, 6) and sys.version_info < (2, 7):
        print "This is not valid version"
        sys.exit()

if sys.platform != "linux2":
print "This is not valid OS"
sys.exit()

os.chdir('/sys/block/')

#dev_list = ['sd.*','mmcblk*']


def size(dev):
    nr_sectors = open(dev+'/size').read().rstrip('\n')
    sect_size = open(dev+'/queue/hw_sector_size').read().rstrip('\n')

    # The sect_size is in bytes, so we convert it to GiB and then send it back
    return (float(nr_sectors)*float(sect_size))/(1024.0*1024.0*1024.0)


def device_detail():
        for dev in glob.glob('/sys/block/sd*'):
                vendor_name = open(dev+'/device/vendor','r').read().rstrip('\n')
                Read_link = os.readlink(dev).split('/')[4]
                print ('Device {0}:: Size {1} GB :: Vendor {2}:: Controller {3}'.format(dev, size (dev), vendor_name, Read_link))


if __name__ =='__main__':
        device_detail()


e.g  
Saved file as disk_info.py

[root@oralinux3 tmp]# ./disk_info.py
Device /sys/block/sda:: Size 20.0 GB :: Vendor VMware, :: Controller host2
Device /sys/block/sdc:: Size 1.0 GB :: Vendor VMware, :: Controller host2
Device /sys/block/sdb:: Size 1.0 GB :: Vendor VMware, :: Controller host2
Device /sys/block/sdd:: Size 1.0 GB :: Vendor VMware, :: Controller host2