Thursday, July 29, 2010

Getting USB storage device (Pen Drive) serial from mount label in Linux

As I have described in my last post, retrieving USB storage device serial in Linux is a bit tricky if you want to find out serial of a given device.

In this post I will describe how to get this.

Your pen drive is mounted automatically as soon as you insert. (You can also mount manually; if not). By default it mounts in /media. To see:

# ls /media

Output can be like this

Disk MyDisk Disk2

"Disk", "MyDisk", "Disk2" is your device's mount labels.

And now run the script given in the last of this post using following command:

# sh '/media/Disk'

Notice the command line argument. It's your devices path where it is mounted. Give the path of the device which serial you want. "" is the name of the shell script given below (To run it with .sh extension ).


# This script takes the mount label as command line argument
# and print the serial of the USB mass storage device
# Author: Vishwesh Kumar Yadav
# Date: 28/05/2010

#Step1- Get mount Label of target device

echo "Mount Label is : $label"

#Step2- Set device name in variable retrieved from df -h or /proc/mounts

sd=`df -h | grep "$label" | cut -d ' ' -f 1 | cut -d '/' -f 3`
echo "Device is : /dev/$sd"

#Step3- Get SCSI channel id

#I use rev command as in some OS like ubuntu and suse one extra
# parameter before every line exist in dmesg command.
#So I was unable to correctly cut exact field count.

sid=`dmesg | grep -nA 1 ": $sd" | tail -1 | cut -d ':' -f 1 | rev | cut -d ' ' -f 1`
echo "SCSI ID : $sid"

#Step4-Get Serial from /proc/scsi/usb-storage/

serial=`cat "/proc/scsi/usb-storage/$sid" | grep Serial | cut -d ':' -f 2`
echo "Serial is : $serial"


Above script is tested on following linux distros:

Ubuntu 10.04
Fedora 8,11 and 13
openSUSE 11.3
Mandriva Linux 2010.1
Linux Mint 9
PCLinuxOS 2010.07
CentOS 5.5

Please let me know, your experiences of getting serial. And your feedback on this post. Also please share if you test it on other unix/linux flavours.


No comments: