summaryrefslogtreecommitdiff
path: root/usbguid2sd
blob: b84fec7e15805519bb396803f6f652d0c81ef8d3 (plain)
  1. #!/usr/bin/perl
  2. # Found here: http://greenfly.org/tips/usb_drive.html
  3. ######################################################################
  4. #
  5. # usb2guid and sd2usbguid: by greenfly <greenfly@greenfly.org>
  6. #
  7. # This function gets passed the $PRODUCT environment variable for a usb
  8. # device, and returns which scsi hard drive that GUID was assigned to
  9. #
  10. # it basically is the complement to sd2usbguid
  11. #
  12. # usage: usbguid2sd <usb guid>
  13. #
  14. # example: usbguid2sd 05e30702 (or 5e3/702/02 which is $PRODUCT to hotplug)
  15. # output: sda
  16. #
  17. ######################################################################
  18. use strict;
  19. my $guid = shift;
  20. my $logfile = "/var/log/syslog";
  21. my $procdir = "/proc/scsi/usb-storage-0";
  22. my $scsi_host;
  23. my $scsi_drive;
  24. # change the guid to the format for /proc/scsi/usb-storage-0/
  25. if($guid =~ m#^([A-Za-z0-9]+)/([A-Za-z0-9]+)/(\d+)$#)
  26. {
  27. $guid = sprintf("%04s%04s", $1, $2);
  28. }
  29. $scsi_host = get_scsi_host_from_guid($guid);
  30. $scsi_drive = get_drive_from_scsi_host($scsi_host);
  31. print "$scsi_drive";
  32. ######################################################################
  33. #
  34. # this function gets passed a guid and reads all the files in
  35. # $procdir to determine what scsi host it was assigned
  36. #
  37. sub get_scsi_host_from_guid
  38. {
  39. my $guid = shift;
  40. my $file;
  41. my $scsi_host;
  42. opendir(DIR, $procdir) or die "can't opendir $procdir: $!";
  43. while (defined($file = readdir(DIR)))
  44. {
  45. next if $file =~ /^\.\.?$/; # skip . and ..
  46. open FILE, "$procdir/$file" or die "can't open $procdir/$file: $!";
  47. while(<FILE>)
  48. {
  49. if(/Host (\w+): usb-storage/)
  50. {
  51. $scsi_host = $1;
  52. }
  53. if(/GUID: (\w+)/)
  54. {
  55. return $scsi_host if($1 =~ /^$guid/);
  56. }
  57. }
  58. close FILE;
  59. }
  60. closedir(DIR);
  61. return 0;
  62. }
  63. ######################################################################
  64. #
  65. # this function gets passed a scsi host, such as "scsi1" and reads
  66. # $logfile to determine what drive it was assigned
  67. #
  68. sub get_drive_from_scsi_host
  69. {
  70. my $scsi_host = shift;
  71. my $scsi_device;
  72. open SYSLOG, $logfile or die "Can't open $logfile: $!";
  73. while(<SYSLOG>)
  74. {
  75. if(/kernel: Attached scsi .*disk (\w+) at $scsi_host,/)
  76. {
  77. $scsi_device = $1;
  78. }
  79. }
  80. close SYSLOG;
  81. return "$scsi_device";
  82. }