import re import commands class DeviceMap: device_map = "/boot/grub/device.map" host_os = "linux" class Error( Exception): pass def convert_linux(self, os_device): """ Convert an OS device to the corresponding Linux GRUB drive. """ found = re.match( "([sh]d[a-z])([0-9]*)$", os_device) if found: return found.group(1), found.group(2) found = re.match( "(d[0-9]*)p([0-9]*)$", os_device) if found: return found.group(1), found.group(3) found = re.match( "(fd[0-9]*)$", os_device) if found: return found.group(1), "" found = re.match( "(/disk|/part([0-9]*))$", os_device) if found: return "/disc", found.group(2) found = re.match( "(c[0-7]d[0-9]*)(p*)(.*)", os_device) if found: return found.group(1), found.group(3) return os_device, "" def convert_drivemap(self, diskpart): """ Get the drive name """ tmp_drive= commands.getoutput( r"grep -v '^#' '"+self.device_map+"'"+ r"| grep '"+diskpart+" *$'"+ r"| sed 's%.*\(([hf]d[0-9][a-g0-9,]*)\).*%\1%'") # If not found, print an error message and exit. if not tmp_drive: raise DeviceMap.Error( "%s does not have any corresponding BIOS drive."%( diskpart)) return tmp_drive[0].strip() def convert(self, os_device): """ Convert an OS device to the corresponding GRUB drive. This part is OS-specific. """ if "linux" in self.host_os: tmp_disk, tmp_part = self.convert_linux( os_device) tmp_drive= self.convert_drivemap( tmp_disk) if not tmp_part: # If no partition is specified, just print the drive name. return tmp_drive # If a partition is specified, we need to translate it into the # GRUB's syntax. if "linux" in self.host_os: return tmp_drive.replace( ")", ",%i)"%( int(tmp_part) -1))