def check_device(devpath):
    """Given the operating system level path to a device node, set
    the value of self.dev and self.disk.  Return false if an 
    invalid path is given."""
    try:
        parted.getDevice(devpath)
    except parted.DeviceException:
        return False
    return True
示例#2
0
def delete_part(part_path):
    """Delete partiton indicated by path"""
    if "nvme" in part_path:
        device = parted.getDevice(part_path[:-2])
    else:
        device = parted.getDevice(part_path[:-1])
    disk = parted.Disk(device)
    part = disk.getPartitionByPath(part_path)
    disk.deletePartition(part)
    disk.commit()
    def runTest(self):
        # Check that a DiskException is raised for an invalid path
        self.assertRaises(parted.DeviceException, parted.getDevice, None)
        self.assertRaises(parted.IOException, parted.getDevice, "")
        self.assertRaises(parted.IOException, parted.getDevice, "/dev/whatever")

        # Check that we get a parted.Device back
        self.assert_(isinstance(parted.getDevice(self.path), parted.Device))

        # Make sure the device node paths match
        self.assertTrue(parted.getDevice(self.path).path == self.path)
示例#4
0
    def runTest(self):
        # Check that a DiskException is raised for an invalid path
        self.assertRaises(parted.DeviceException, parted.getDevice, None)
        self.assertRaises(parted.IOException, parted.getDevice, "")
        self.assertRaises(parted.IOException, parted.getDevice,
                          "/dev/whatever")

        # Check that we get a parted.Device back
        self.assertIsInstance(parted.getDevice(self.path), parted.Device)

        # Make sure the device node paths match
        self.assertEqual(parted.getDevice(self.path).path, self.path)
 def initFromDisk(self, devicename):
    import parted
    partitions=list()
    dev=parted.getDevice(devicename)
    try:
       dev=parted.getDevice(devicename)
       disk=parted.Disk(dev)
       for part in disk.getPrimaryPartitions():
          partitions.append(part)
    except self.disklabelexception:
       self.log.debug("no partitions found")
    return partitions
def print_handler(opts, args):
    # disks = {devpath:disks}
    disks = {}
    isjson = False
    withfree = False
    for opt in opts:
        op, arg = opt[0], opt[1]
        if op == "-l" or op == "--list":
            disks = None
        elif op == "-h" or op == "--help":
            usage()
            sys.exit(0)
        else:
            usage()
            sys.exit(1)

    for arg in args:
        if arg == "json":
            isjson = True
        elif arg == "free":
            withfree = True
        elif arg == "print" and disks == []:
            if not check_device(args[0]):
                usage()
                sys.exit(1)
            else:
                dev = parted.getDevice(args[0])
                try:
                    disks[dev.path] = parted.disk.Disk(dev)
                except:
                    disks[dev.path] = None
    if isjson:
        print partedprint.parted_print(disks, isjson, withfree)
    else:
        partedprint.parted_print(disks, isjson, withfree)
示例#7
0
    def partition_primary_disk(self):
        """
        Create a partition table on the block device for the installer
        image (rescue disk).
        """
        self.logger.info('Creating partitions')
        device = parted.getDevice(self.path)
        self.logger.debug('created %s', device)
        disk = parted.freshDisk(device, 'msdos')
        self.logger.debug('created %s', disk)

        # create the rescue disk partition - the size has been chosen to d-i's liking, so
        # it doesn't attempt to truncate or override the partition
        partition_size = round(2099249152 / (device.sectorSize))  # 2 GB
        self._new_partition(
            device, disk, 2048, partition_size, True
        )  # 2048 padding is required to make d-i not override the rescue partition

        disk.commit()

        # wait for device nodes
        check_call(['udevadm', 'settle'])

        # create file system and labels
        check_call(['mkfs.ext4', '-F', self.path + '-part1'])
        check_call(['e2label', self.path + '-part1', 'rescue'])
示例#8
0
 def _makeVDisk(self):
     self.parts = [('p1', 'junk')]
     self.image_file = self.path
     os_call(['dd', 'bs=4096', 'count=5000', 'if=/dev/zero',
             'of=' + self.image_file])
     with subprocess.Popen(['sudo', 'losetup', '-f'],
                           stdout=subprocess.PIPE,
                           universal_newlines=True) as lo_list:
         out = lo_list.stdout.read().split('\n')[:-1]
         if len(out) > 0:
             self.path = out[0]
         else:
             self.path = '/dev/loop0'
         self.part_prefix = 'p'
     os_call(['sudo', 'losetup', '-P', self.path, self.image_file])
     self.device = parted.getDevice(self.path)
     disk = parted.freshDisk(self.device, 'msdos')
     geom = parted.Geometry(self.device, start=1,
                            length=self.device.getLength() - 1)
     fs = parted.FileSystem('fat16', geom)
     new_part = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL,
                                 fs=fs, geometry=geom)
     disk.addPartition(partition=new_part,
                       constraint=self.device.getConstraint())
     new_part.setFlag(parted.PARTITION_BOOT)
     try:
         disk.commit()
     except:
         pass
     self.format(mk_vfat(), 0)
     self.parts = self.partitions()
     self.__undoLo = ['sudo', 'losetup', '-d', self.path]
示例#9
0
    def partition(self):
        """
        Create a partition table on the block device.

        The newly created partition will have the following characteristics:
            - a primary partition using 100% of the device capacity
            - optimal alignment given the disk topology information
            - a MS-DOS disk label for simple BIOS booting on PC-type hardware
            - marked as bootable
        """
        self.logger.info('creating primary partition')
        device = parted.getDevice(self.path)
        self.logger.debug('created %s', device)
        disk = parted.freshDisk(device, 'msdos')
        self.logger.debug('created %s', disk)
        geometry = parted.Geometry(device=device,
                                   start=1,
                                   length=device.getLength() - 1)
        self.logger.debug('created %s', geometry)
        filesystem = parted.FileSystem(type='ext3', geometry=geometry)
        self.logger.debug('created %s', filesystem)
        partition = parted.Partition(disk=disk,
                                     type=parted.PARTITION_NORMAL,
                                     fs=filesystem,
                                     geometry=geometry)
        self.logger.debug('created %s', partition)
        disk.addPartition(partition=partition,
                          constraint=device.optimalAlignedConstraint)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.commit()
示例#10
0
    def getDevice(self, input):
        ''' A method which gets information about the specified device.'''
        # Grab the parted device
        device = parted.getDevice(input)

        # And return a disk instance
        return parted.newDisk(device), device
   def createPartitions(self, devicename, partitions, samesize):
      """
      Create the given partitions on the device devicename.
      @param partitions: the partitions to be created
      @type partitions: comoonics.storage.ComPartitions.Partition 
      """
      import parted
      dev=parted.getDevice(devicename)
      try:
         disk=parted.Disk(dev)
         disk.deleteAllPartitions()
      except self.disklabelexception:
         disk=parted.freshDisk(dev, parted.disk.diskType["msdos"])
      for part in partitions:
         partedtype=part.getPartedType()
         size=part.getAttribute("size")
         flags=part.getFlags()
         size=self.getSectorSize(size, dev)
         partedflags=list()
         for flag in flags:
            partedflags.append(flag.getFlagPartedNum())
         self.log.debug("creating partition: size: %i" % size )
         self.add_partition(disk, partedtype, size, flags, samesize=samesize)

      disk.commit()
示例#12
0
文件: mkcard.py 项目: rngadam/mkcard
def create_partitions(device_path, partitions):
    try:
        device = parted.getDevice(device_path)
        disk = parted.Disk(device)

        # prompt user before wiping out disk...
        disk.deleteAllPartitions()
        disk.commitToDevice()
        disk.commitToOS()
    except parted.DiskLabelException:
        print "disk is not initialized, ignoring"

    # create volatile store for new partition information
    # create fat, ext4 and swap partition
    disk = parted.freshDisk(device, _ped.disk_type_get("msdos"))

    constraint = parted.Constraint(device=device)
    max_length_sectors = disk.device.getLength()
    fat32_size = mb_to_sector(disk, partitions[0]['length'])
    swap_size = mb_to_sector(disk, partitions[2]['length'])
    ext4_size = max_length_sectors - (fat32_size+swap_size)
    fat32_geom = parted.Geometry(device=device, start=0, length=fat32_size)
    ext4_geom = parted.Geometry(device=device, start=fat32_size, length=ext4_size)
    swap_geom = parted.Geometry(device=device, start=ext4_size+fat32_size, length=swap_size)
    for part_type, geom in [("fat32", fat32_geom), ("ext4", ext4_geom), ("linux-swap", swap_geom)]:
        print "creating %s with geom: %s" % (part_type, geom)
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geom)
        disk.addPartition(partition,constraint=constraint)
        part_type_ped = _ped.file_system_type_get(part_type)
        partition.getPedPartition().set_system(part_type_ped)
    disk.commitToDevice()
    disk.commitToOS()
示例#13
0
def raw_write(source, target):     
    do_umount(target)       
    bs = 4096
    size=0
    input = open(source, 'rb')
    total_size = float(os.path.getsize(source))
    #print total_size
    
    # Check if the ISO can fit ... :)
    device = parted.getDevice(target)
    device_size = device.getLength() * device.sectorSize
    if (device.getLength() * device.sectorSize) < float(os.path.getsize(source)):
        input.close()
        print "nospace"
        exit(3)
   
    output = open(target, 'wb')
    while True:
	buffer = input.read(bs)
	if len(buffer) == 0:
	  break
	output.write(buffer)
	size = size + len(buffer)
	print size/total_size

    output.flush()    
    #os.fsync(output.fileno())
    input.close()
    output.close()
    if size == total_size:
      print "1.0"
      exit (0)
    else:
      print "failed"
      exit (4)
示例#14
0
def mkfakediskimg(disk_img):
    """Create a fake partitioned disk image

    :param disk_img: Full path to a partitioned disk image
    :type disk_img: str
    :returns: True if it was successful, False if something went wrong

    Include /boot, swap, and / partitions with fake kernel and /etc/passwd
    """
    try:
        mksparse(disk_img, 42 * 1024**2)
        # Make a /boot, / and swap partitions on it
        dev = parted.getDevice(disk_img)
        disk = parted.freshDisk(dev, "gpt")

        # (start, length, flags, name)
        for start, length, flags, name in [
                  (  1024**2,    1024**2, None, "boot"),
                  (2*1024**2,  2*1024**2, parted.PARTITION_SWAP, "swap"),
                  (4*1024**2, 38*1024**2, None, "root")]:
            geo = parted.Geometry(device=dev, start=start//dev.sectorSize, length=length//dev.sectorSize)
            part = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geo)
            part.getPedPartition().set_name(name)
            disk.addPartition(partition=part)
            if flags:
                part.setFlag(flags)
        disk.commit()
        os.sync()
    except parted.PartedException:
        return False

    # Mount the disk's partitions
    loop_devs = kpartx_disk_img(disk_img)

    try:
        # Format the partitions
        runcmd(["mkfs.ext4", "/dev/mapper/" + loop_devs[0][0]])
        runcmd(["mkswap", "/dev/mapper/" + loop_devs[1][0]])
        runcmd(["mkfs.ext4", "/dev/mapper/" + loop_devs[2][0]])

        # Mount the boot partition and make a fake kernel and initrd
        boot_mnt = mount("/dev/mapper/" + loop_devs[0][0])
        try:
            mkfakebootdir(boot_mnt)
        finally:
            umount(boot_mnt)

        # Mount the / partition and make a fake / filesystem with /etc/passwd
        root_mnt = mount("/dev/mapper/" + loop_devs[2][0])
        try:
            mkfakerootdir(root_mnt)
        finally:
            umount(root_mnt)
    except Exception:
        return False
    finally:
        # Remove the disk's mounted partitions
        runcmd(["kpartx", "-d", "-s", disk_img])

    return True
示例#15
0
    def probe(self):
        """ Probe all the drives for juicy information """
        self.drives = list()

        # Cache the current mount points, gonna need it.
        self.mtab = self.dm.get_mount_points()
        self.dm.scan_parts()
        self.probe_lvm2()

        for item in self.dm.devices:
            disk = None
            device = None
            try:
                device = parted.getDevice(item)
                if device.readOnly:
                    print("DEBUG: Skipping read-only device")
                    continue
                size = device.getLength() * device.sectorSize
                if size < MIN_REQUIRED_SIZE:
                    print("DEBUG: Skipping tiny drive: {}".format(device.path))
                    continue
            except Exception as e:
                print("Cannot probe device: {} {}".format(item, e))
                continue
            try:
                disk = parted.Disk(device)
            except Exception as e:
                print("Cannot probe disk: {} {}".format(item, e))

            # Get a system drive
            drive = self.dm.parse_system_disk(device, disk, self.mtab)
            if drive:
                self.drives.append(drive)
示例#16
0
    def maybeCreateLabel(self):
        """Set up an msdos label."""

        self.partedDevice = parted.getDevice(self.device)
        try:
            self.partedDisk = parted.newDisk(self.partedDevice)
            if self.partedDisk.type == 'msdos':
                self.log.info("disk %s is already msdos", self.device)
                return 0
            self.log.warn("disk %s has wrong label %s",
                          self.device, self.partedDisk.type)
        except (DiskException, PartedException) as ex:
            self.log.error("cannot get partition table from %s: %s",
                           self.device, str(ex))
        except Exception:
            self.log.exception("cannot get partition table from %s",
                               self.device)

        self.log.info("clobbering disk label on %s", self.device)
        self.partedDevice.clobber()

        self.log.info("creating msdos label on %s", self.device)
        self.partedDisk = parted.freshDisk(self.partedDevice, 'msdos')

        return 0
示例#17
0
    def probe(self):
        """ Probe all the drives for juicy information """
        self.drives = list()

        # Cache the current mount points, gonna need it.
        self.mtab = self.dm.get_mount_points()
        self.dm.scan_parts()
        self.probe_lvm2()

        for item in self.dm.devices:
            disk = None
            device = None
            try:
                device = parted.getDevice(item)
                if device.readOnly:
                    print("DEBUG: Skipping read-only device")
                    continue
                size = device.getLength() * device.sectorSize
                if size < MIN_REQUIRED_SIZE:
                    print("DEBUG: Skipping tiny drive: {}".format(
                          device.path))
                    continue
            except Exception as e:
                print("Cannot probe device: {} {}".format(item, e))
                continue
            try:
                disk = parted.Disk(device)
            except Exception as e:
                print("Cannot probe disk: {} {}".format(item, e))

            # Get a system drive
            drive = self.dm.parse_system_disk(device, disk, self.mtab)
            if drive:
                self.drives.append(drive)
def delete_part(part_path):
    """Delete partiton indicated by path"""
    device = parted.getDevice(get_drive_path(part_path))
    disk = parted.Disk(device)
    part = disk.getPartitionByPath(part_path)
    disk.deletePartition(part)
    disk.commit()
    def maybeCreateLabel(self):
        """Set up an msdos label."""

        self.partedDevice = parted.getDevice(self.device)
        try:
            self.partedDisk = parted.newDisk(self.partedDevice)
            if self.partedDisk.type == 'msdos':
                self.log.info("disk %s is already msdos", self.device)
                return 0
            self.log.warn("disk %s has wrong label %s",
                          self.device, self.partedDisk.type)
        except (DiskException, PartedException) as ex:
            self.log.error("cannot get partition table from %s: %s",
                           self.device, str(ex))
        except Exception:
            self.log.exception("cannot get partition table from %s",
                               self.device)

        self.log.info("clobbering disk label on %s", self.device)
        self.partedDevice.clobber()

        self.log.info("creating msdos label on %s", self.device)
        self.partedDisk = parted.freshDisk(self.partedDevice, 'msdos')

        return 0
    def partition(self):
        """
        Create a partition table on the block device.

        The newly created partition will have the following characteristics:
            - a primary partition using 100% of the device capacity
            - optimal alignment given the disk topology information
            - a MS-DOS disk label for simple BIOS booting on PC-type hardware
            - marked as bootable
        """
        self.logger.info('creating primary partition')
        device = parted.getDevice(self.path)
        self.logger.debug('created %s', device)
        disk = parted.freshDisk(device, 'msdos')
        self.logger.debug('created %s', disk)
        geometry = parted.Geometry(device=device, start=1,
                                   length=device.getLength() - 1)
        self.logger.debug('created %s', geometry)
        filesystem = parted.FileSystem(type='ext3', geometry=geometry)
        self.logger.debug('created %s', filesystem)
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL,
                                     fs=filesystem, geometry=geometry)
        self.logger.debug('created %s', partition)
        disk.addPartition(partition=partition,
                          constraint=device.optimalAlignedConstraint)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.commit()
示例#21
0
文件: mkcard.py 项目: rngadam/mkcard
def verify_partitions(device_path, partitions):
    try:
        device = parted.getDevice(device_path)
        disk = parted.Disk(device)
    except parted.DiskLabelException:
        print "disk is not initialized"
        return False

    if len(partitions) != len(disk.partitions):
        print "partitions differ in length: desired %d current %d" % (len(partitions), len(disk.partitions))
        return False

    for part_id in xrange(0, len(partitions)):
        current_partition = disk.partitions[part_id]
        target_partition = partitions[part_id]

        # check filesystem type
        if not current_partition.fileSystem:
            # no filesystem...
            print "no filesystem found on partition %d" % part_id
            return False

        current_fs_type = current_partition.fileSystem.getPedFileSystem().type.name
        if not current_fs_type.startswith(target_partition['type']): # linux-swap -> linux-swap(v1)
            print "partition type does not match: expected %s, got %s" % (target_partition['type'], current_fs_type)
            return False

        # check if the partition are in use... if yes, abort
        if current_partition.busy:
            raise mkcardException("Partition is busy %s, please umount first" % current_partition)

    return True
示例#22
0
def detect_storage(path):
    global mainscreen
    try:
        parted.getDevice(path).removeFromCache()
        mainscreen.setstatus("%s detected" % path)
        mainscreen.flush(disp)
        time.sleep(2)
        mainscreen.setstatus("Press -> BTN to write!")
        mainscreen.flush(disp)
        mainscreen.canwrite = True
    except parted.IOException:
        mainscreen.canwrite = False
        mainscreen.setstatus("%s removed" % path)
        mainscreen.flush(disp)
        time.sleep(2)
        mainscreen.setstatus("Ready.")
        mainscreen.flush(disp)
示例#23
0
    def __init__ (self, conf, testMode=False):
        self.conf = conf
        self.testMode = testMode
        self.resinBootPartPath = getBootPartition(conf)
        self.currentResinRootPartPath = getRootPartition(conf)

        self.device = parted.getDevice(getRootDevice(conf))
        self.disk = parted.newDisk(self.device)
示例#24
0
def parse_fdisk(device_node):
    dev_info = parted.getDevice(device_node)
    size_bytes = dev_info.length * dev_info.sectorSize

    # Convert bytes to GiB (1 GiB = 1024*1024*1024 bytes)
    int_size = int(size_bytes)
    size_gib = int_size / 1073741824

    return int(size_gib)
示例#25
0
def raw_format(device_path, fstype, volume_label):

    do_umount(device_path)

    # First erase MBR and partition table , if any
    os.system("dd if=/dev/zero of=%s bs=512 count=1 >/dev/null 2>&1" %
              device_path)

    device = parted.getDevice(device_path)

    # Create a default partition set up
    disk = parted.freshDisk(device, 'msdos')
    disk.commit()
    regions = disk.getFreeSpaceRegions()

    if len(regions) > 0:
        #print "Build partition"
        # Define size
        region = regions[-1]
        start = parted.sizeToSectors(1, "MiB", device.sectorSize)
        #print "start %s" % start
        end = device.getLength() - start - 1024
        #print end

        # Alignment
        #cylinder = device.endSectorToCylinder(end)
        #end = device.endCylinderToSector(cylinder)
        #print end
        try:
            geometry = parted.Geometry(device=device, start=start, end=end)
        except:
            print "Geometry error - Can't create partition"
            sys.exit(5)

        # fstype
        fs = parted.FileSystem(type=fstype, geometry=geometry)

        # Create partition
        partition = parted.Partition(disk=disk,
                                     type=parted.PARTITION_NORMAL,
                                     geometry=geometry,
                                     fs=fs)
        constraint = parted.Constraint(exactGeom=geometry)
        disk.addPartition(partition=partition, constraint=constraint)
        disk.commit()

        # Format partition according to the fstype specified
        if fstype == "fat32":
            os.system("mkdosfs -F 32 -n \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
        if fstype == "ntfs":
            os.system("mkntfs -f -L \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
        elif fstype == "ext4":
            os.system("mkfs.ext4 -L \"%s\" %s >/dev/null 2>&1" %
                      (volume_label, partition.path))
    sys.exit(0)
def get_partitions(diskpath):
    """ Return array of partition names for given disk """
    dev = parted.getDevice(diskpath)
    disk = parted.newDisk(dev)
    partitions = []
    for part in disk.partitions:
        (_, _, pname) = part.path.rsplit("/")
        partitions.append({"name": pname, "size": part.getLength() * dev.sectorSize})

    return partitions
示例#27
0
def get_partitions(diskpath):
    """ Return array of partition names for given disk """
    dev = parted.getDevice(diskpath)
    disk = parted.newDisk(dev)
    partitions = []
    for part in disk.partitions:
        (_, _, pname) = part.path.rsplit("/")
        partitions.append({"name": pname, "size": part.getLength() * dev.sectorSize})

    return partitions
示例#28
0
def raw_format(device_path, fstype, volume_label, uid, gid):

    do_umount(device_path)

    # First erase MBR and partition table , if any
    call(["dd", "if=/dev/zero", "of=%s" % device_path, "bs=512", "count=1"])

    device = parted.getDevice(device_path)

    # Create a default partition set up
    disk = parted.freshDisk(device, 'msdos')
    disk.commit()
    regions = disk.getFreeSpaceRegions()

    if len(regions) > 0:
        # Start partition at sector 2048
        offset = 2048
        # 1Mib grain size
        grain_size = kib_to_sectors(device, 1024)
        # Get first region
        region = regions[0]
        start = region.start
        end = region.end - start + 1

        align = parted.Alignment(offset=offset, grainSize=grain_size)
        if not align.isAligned(region, start):
            start = align.alignNearest(region, start)

        align = parted.Alignment(offset=offset -1, grainSize=grain_size)
        if not align.isAligned(region, end):
            end = align.alignNearest(region, end)
        try:
            geometry = parted.Geometry(device=device, start=start, end=end)
        except:
            print "Geometry error - Can't create partition"
            sys.exit(5)

        # fstype
        fs = parted.FileSystem(type=fstype, geometry=geometry)

        # Create partition
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geometry, fs=fs)
        constraint = parted.Constraint(exactGeom=geometry)
        disk.addPartition(partition=partition, constraint=constraint)
        partition.setFlag(parted.PARTITION_BOOT)
        disk.commit()

        # Format partition according to the fstype specified
        if fstype == "fat32":
            call(["mkdosfs", "-F", "32", "-n", volume_label, partition.path])
        if fstype == "ntfs":
            call(["mkntfs", "-f", "-L", volume_label, partition.path])
        elif fstype == "ext4":
            call(["mkfs.ext4", "-E", "root_owner=%s:%s" % (uid, gid), "-L", volume_label, partition.path])
    sys.exit(0)
示例#29
0
def testUSB():
    devices = [dev.path for dev in parted.getAllDevices()]
    print(devices)
    usb = parted.getDevice('/dev/sdb')
    print(usb)
    disk = parted.newDisk(usb)
    partitionsDesc = [(part.type, part.number) for part in disk.partitions]
    print(disk.partitions[0])
    # print(disk.partitions[1])
    print(partitionsDesc)
    print(disk.partitions[0].fileSystem.type)
示例#30
0
def raw_format(device_path, fstype, volume_label, uid, gid):

    do_umount(device_path)

    # First erase MBR and partition table , if any
    os.system ("dd if=/dev/zero of=%s bs=512 count=1 >/dev/null 2>&1" % device_path)

    device = parted.getDevice(device_path)

    # Create a default partition set up
    disk = parted.freshDisk(device, 'msdos')
    try:
        disk.commit()
    except:
        # Unable to write the new partition
        print "Can't create partition. The device could be read-only."
        sys.exit(5)
    regions = disk.getFreeSpaceRegions()

    if len(regions) > 0:
        #print "Build partition"
        # Define size
        start = parted.sizeToSectors(1, "MiB", device.sectorSize)
        #print "start %s" % start
        end = device.getLength() - start - 1024
        #print end

        # Alignment
        #cylinder = device.endSectorToCylinder(end)
        #end = device.endCylinderToSector(cylinder)
        #print end
        try:
            geometry = parted.Geometry(device=device, start=start, end=end)
        except:
            print "Geometry error - Can't create partition"
            sys.exit(5)

        # fstype
        fs = parted.FileSystem(type=fstype, geometry=geometry)

        # Create partition
        partition = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geometry, fs=fs)
        constraint = parted.Constraint(exactGeom=geometry)
        disk.addPartition(partition=partition, constraint=constraint)
        disk.commit()

        # Format partition according to the fstype specified
        if fstype == "fat32":
            os.system("mkdosfs -F 32 -n \"%s\" %s >/dev/null 2>&1" % (volume_label, partition.path))
        if fstype == "ntfs":
            os.system("mkntfs -f -L \"%s\" %s >/dev/null 2>&1" % (volume_label, partition.path))
        elif fstype == "ext4":
            os.system("mkfs.ext4 -E root_owner=%s:%s -L \"%s\" %s >/dev/null 2>&1" % (uid, gid, volume_label, partition.path))
    sys.exit(0)
 def on_fdhandler(self, devpath, mem, sysflag):
     data = self.error_handle(None, None)
     try :
         dev = parted.getDevice(devpath)
         fdresult = lib.autoparted.fdhandler(dev,mem, self.disks, sysflag)
         self.disks[devpath] = fdresult[0]
         number = fdresult[1]
         self.disks_tag[devpath] = True
         data = self.error_handle(None,number)
     except Exception, e:
         data = self.error_handle(e, None)
 def on_easyhandler(self, devpath, parttype, start, end, number):
     data = self.error_handle(None,None)
     try :
         dev = parted.getDevice(devpath)
         disk = self.disks[devpath]
         easyresult = lib.autoparted.easyhandler(dev, disk, parttype, start, end, number)
         self.disks[devpath] = easyresult[0]
         number = easyresult[1]
         self.disks_tag[devpath] = True
         data = self.error_handle(None,number)
     except Exception, e:
         data = self.error_handle(e, None)
示例#33
0
    def parted_device(self) -> Iterator[parted.Device]:
        try:
            import parted
        except ModuleNotFoundError:
            raise NotImplementedError(
                "Install pyparted (python3-parted in debian) to do partitioning work"
            )

        device = parted.getDevice(self.path)
        try:
            yield device
        finally:
            device.close
示例#34
0
 def start_scanning(self):
     try:
         device = parted.getDevice(self.path_to_input_device)
     except Exception as exception:
         error('Input Device could not be read: {}'.format(exception))
         self.is_running = False
         exit()
     else:
         self.is_running = True
         t = Thread(target=self.__start_scanning,
                    args=(device, ),
                    daemon=True)
         t.start()
示例#35
0
def get_all_devs():
    """Get all the storage devices that exists currently on the system.

    We only want the device name and the partitions for each device.
    We don't want the parted structures.
    Return - dictionary with device name and all device partitions.
    """

    # Must use an inner function as the test does not consider the device
    # number.  Olny device type.
    def is_dev_in_ignored(dev):
        for ignored in ignore_devs:
            if dev["device"].replace("/dev/","").startswith(ignored):
                return True
        return False

    retval = {}
    for device in minihal.get_devices_by_type("storage"):
        if device is None:
            continue

        elif is_dev_in_ignored(device):
            continue

        elif "storage.removable.media_available" in device.keys() and \
                device["storage.removable.media_available"] == False:
            # We ignore stuff that has no media inserted.
            continue

        else:
            try:
                # parted will provide us with all the partitions.
                partitions = []
                parteddev = parted.getDevice(device["device"])
                disk = parted.Disk(parteddev)
                for part in disk.partitions:
                    if part.type == parted.PARTITION_EXTENDED \
                            or part.type == parted.PARTITION_NORMAL \
                            or part.type == parted.PARTITION_LOGICAL:
                        partitions.append(
                                Dname("%s%s"%(device["device"],part.number)))
                # The key will be the device name and it will contain a list of
                # parts.  This is very unfortunate as the object would be better
                # sutied as a key.
                retval[Dname.asName(device["device"])] = partitions
            except:
                # If there is a problem with this dev... jus continue.
                continue

    return retval
示例#36
0
def destroy_partition_table(path_to_disk):

    disk = parted.getDevice(path_to_disk)

    answer = input(
        "WARNING!! You are about to destroy the given partition! Continue? y/n"
    )
    if (answer == 'y'):
        print("Now destroying the partition signatures and partition")
        return disk.clobber, disk.destroy
    elif (answer == 'n'):
        print("Canceling partition destruction")
    else:
        print("Invalid input, please use just 'y' or 'n'")
示例#37
0
 def __init__(self, number, path):
     self.number = number
     self.path = path
     self.pdev = parted.getDevice(path)
     self.pdisk = parted.freshDisk(self.pdev, 'msdos')
     if self.pdisk.deleteAllPartitions():
         self.pdisk.commit()
         logging.info('%s cleared all prexisting partitions from disk' % (
             self.__class__.__name__))
     self.size_bytes = get_disk_size(path)
     self.size_sectors = bytes_to_sectors(size_bytes_to_int(self.size_bytes),
                                          self.pdev.sectorSize)
     self.grow_part = False
     self._partitions = []
示例#38
0
    def __init__(self, devpath):
        # Supported commands and corresponding handlers

        try:
            self.device = parted.getDevice(devpath)
        except parted.IOException as e:
            raise RuntimeError(e.message)

        try:
            self.disk = parted.newDisk(self.device)
            if self.disk.type != 'msdos':
                raise RuntimeError('Only MBR partitions are supported')
        except parted.DiskException:
            self.create_empty()
示例#39
0
def revertRepartition(device, partition, deltastart, deltaend, unit='MiB'):
    dev = parted.getDevice(device)
    disk = parted.newDisk(dev)
    targetPartition = disk.getPartitionByPath(device + partition)
    geometry = targetPartition.geometry
    geometry.start += parted.sizeToSectors(deltastart, unit, dev.sectorSize)
    geometry.end += parted.sizeToSectors(deltaend, unit, dev.sectorSize)
    disk.deletePartition(targetPartition)
    partition = parted.Partition(disk=disk,
                                 type=parted.PARTITION_NORMAL,
                                 geometry=geometry)
    disk.addPartition(partition=partition,
                      constraint=dev.optimalAlignedConstraint)
    disk.commit()
示例#40
0
 def __init__(self, device_path, path):
   self.dev = device_path
   self.path = path
   
   device = parted.getDevice(device_path)
   
   if path is 'swap':
     self.type = 'swap'
   else:
     geometry = parted.geometry.Geometry(device)
     self.type = parted.probeFileSystem(geometry)
     
   self.options = 'defaults'
   self.dump = 1 if path is '/' else 0
   self.pass = 1 if path is '/' else 0
def print_disks(disks,free):
    """Print the stat of disks given."""
    devpaths = disks.keys()
    for devpath in devpaths:
        dev = parted.getDevice(devpath)
        disk = disks[devpath]
        print "dev model: %s" % (dev.model), 
        if disk:
            print ", type: %s" % (disk.type, ),
            print ", primaries: %d" % (disk.primaryPartitionCount, )
            #FIXME: this crashes on gpt device
            #print "maxSupportedPartitionCount: %d" % (disk.maxSupportedPartitionCount, )
            print_disk(disk, free)
        else:
            print ", type: unknown",
            print ", primaries: 0"
示例#42
0
def main():
    try:
        if sys.argv[1] == "--debug":
            del sys.argv[1]
            global DEBUG
            DEBUG = True
        device = parted.getDevice(sys.argv[1])
        parted.Disk(device).minimizeExtendedPartition()
    except IndexError:
        sys.stderr.write("ERROR: you must enter a device path\n")
        sys.exit(1)
    except Exception as e:
        sys.stderr.write("ERROR: %s\n" % e)
        sys.exit(1)
    else:
        curses.wrapper(start_curses, device)
示例#43
0
    def init_disk(self, disk, ptable):
        """
        Initial and wipe the disk, and set the new partition table to ptable.
        :param disk: Device to initialize.
        :param ptable: Partition table to use msdos/gpt.
        :return:
        """
        self.log.debug(f"parted: init_disk: disk:{disk} ptable:{ptable}")
        # Set the device.
        self.device = parted.getDevice(disk)

        # Wipe the device.
        self.device.clobber()

        # Create label on the disk.
        self.pdisk = parted.freshDisk(self.device, ptable)
示例#44
0
def partition(diskname, specs, force=False, check_mode=False):
    """
    Create requested partitions.
    Returns nr. of created partitions or 0 when the disk was already partitioned.
    """
    count = 0

    dev = parted.getDevice(diskname)
    try:
        disk = parted.newDisk(dev)
    except parted.DiskException:
        # unrecognizable format, treat as empty disk
        disk = None

    if disk and len(disk.partitions) > 0 and not force:
        print "skipping", diskname
        return 0

    # create new partition table, wiping all existing data
    disk = parted.freshDisk(dev, 'gpt')
    # calculate nr. of partitions of each size
    assign_space(dev.getSize(), specs)
    last_megabyte = 1
    for spec in specs:
        for _ in range(spec.count):
            # create the partition
            start = parted.sizeToSectors(last_megabyte, "MiB", dev.sectorSize)
            length = parted.sizeToSectors(spec.size, "MiB", dev.sectorSize)
            geo = parted.Geometry(device=dev, start=start, length=length)
            filesystem = parted.FileSystem(type='ext4', geometry=geo)
            part = parted.Partition(disk=disk,
                                    type=parted.PARTITION_NORMAL,
                                    fs=filesystem,
                                    geometry=geo)
            disk.addPartition(partition=part,
                              constraint=dev.optimalAlignedConstraint)
            last_megabyte += spec.size
            count += 1
    try:
        if not check_mode:
            disk.commit()
    except parted.IOException:
        # partitions have been written, but we have been unable to inform the
        # kernel of the change, probably because they are in use.
        # Ignore it and hope for the best...
        pass
    return count
def partition(diskname, specs, force=False, check_mode=False):
    """
    Create requested partitions.
    Returns nr. of created partitions or 0 when the disk was already partitioned.
    """
    count = 0

    dev = parted.getDevice(diskname)
    try:
        disk = parted.newDisk(dev)
    except parted.DiskException:
        # unrecognizable format, treat as empty disk
        disk = None

    if disk and len(disk.partitions) > 0 and not force:
        print "skipping", diskname
        return 0

    # create new partition table, wiping all existing data
    disk = parted.freshDisk(dev, 'gpt')
    # calculate nr. of partitions of each size
    assign_space(dev.getSize(), specs)
    last_megabyte = 1
    for spec in specs:
        for _ in range(spec.count):
            # create the partition
            start = parted.sizeToSectors(last_megabyte, "MiB", dev.sectorSize)
            length = parted.sizeToSectors(spec.size, "MiB", dev.sectorSize)
            geo = parted.Geometry(device=dev, start=start, length=length)
            filesystem = parted.FileSystem(type='ext4', geometry=geo)
            part = parted.Partition(
                disk=disk,
                type=parted.PARTITION_NORMAL,
                fs=filesystem,
                geometry=geo)
            disk.addPartition(partition=part, constraint=dev.optimalAlignedConstraint)
            last_megabyte += spec.size
            count += 1
    try:
        if not check_mode:
            disk.commit()
    except parted.IOException:
        # partitions have been written, but we have been unable to inform the
        # kernel of the change, probably because they are in use.
        # Ignore it and hope for the best...
        pass
    return count
示例#46
0
def raw_write(source: str, target: str):
    mountutils.do_umount(target)
    bs: int = 4096
    size: int = 0
    inputFile = open(source, 'rb')
    total_size: float = float(os.path.getsize(source))

    # Check if the ISO can fit ... :)
    device = parted.getDevice(target)
    device_size = device.getLength() * device.sectorSize
    if (device.getLength() * device.sectorSize) < float(
            os.path.getsize(source)):
        inputFile.close()
        print("nospace")
        exit(3)

    increment = total_size / 100

    written: int = 0
    print("Source: " + str(source))
    print("Target: " + str(target))
    output = open(target, 'wb')
    while True:
        buffer = inputFile.read(bs)
        if len(buffer) == 0:
            break
        output.write(buffer)
        size = size + len(buffer)
        written = written + len(buffer)
        print(size / total_size)
        if (written >= increment):
            output.flush()
            os.fsync(output.fileno())
            written = 0

    output.flush()
    os.fsync(output.fileno())
    inputFile.close()
    output.close()

    if size == total_size:
        print("1.0")
        exit(0)
    else:
        print("failed")
        exit(4)
示例#47
0
def main():
    opt = opciones()
    verifica(opt)
    #Inicializando dispositivo
    try:
        print '\nVerificando dispositivo............',
        sdb = parted.getDevice(opt.device)
    except Exception:
        print '[ERROR]'
        exit(1)
    print '[OK]'
    print '\nDispositivo seleccionado: ' + opt.device
    c = ''
    while c != 'y':
        c = raw_input(
            '\nAl dispositivo ' + opt.device +
            ' se le eliminara la tabla de particion actual, quieres continuar? [Y/n] '
        )
        c = c.lower()
        if c == 'n':
            print '\nSaliendo ...\n'
            exit(1)
        elif c == '' or c == 'y':
            c = 'y'
            sdb.clobber()
            print ''
            pass
    try:
        disk = parted.newDisk(sdb)
    except Exception:
        pass
    print 'Creando dispositivo msdos\n'
    disk = parted.freshDisk(sdb, 'msdos')
    print 'Tipos aceptados'
    for x in parted.fileSystemType.keys():
        print x + ' ',
    print ''
    fin = 0
    n = raw_input('\nCuantas particiones van a ser? (maximo 4)> ')
    print ''
    for x in range(int(n)):
        print 'Particion primaria ' + str(x + 1) + ':'
        t = raw_input('Tipo> ')
        s = long(raw_input('Tamaño en MiB> '))
        print ''
        fin = particion_pri(sdb, disk, s, t, fin)
def find_ext_part(blkdev_path):
    # if root use parted, if normal user use sudo blkid
    if os.geteuid() == 0:
        device = parted.getDevice(blkdev_path)
        disk = parted.Disk(device)
        primary_partitions = disk.getPrimaryPartitions()

        count = 1
        for partition in primary_partitions:
            # the boot part must be either part 1 or 2 of the device
            if count > 2:
                return []

            print "Partition: %s" % partition.path
            try:
                fs = parted.probeFileSystem(partition.geometry)
            except:
                fs = "unknown"
            print "Filesystem: %s" % fs
            if fs == 'ext2' or fs == 'ext3':
                return partition.path
            count += 1  # increment counter
    else:
        # the boot part must be either part 1 or 2 of the device
        for partition in [1, 2]:
            output = ''
            try:
                command = 'blkid ' + blkdev_path + str(partition)
                command = add_sudo(command)
                output = subprocess.check_output(command,
                                                 stderr=subprocess.STDOUT,
                                                 shell=True)
            except:
                pass
            result = re.search(r"TYPE=(.*)\s", output)
            if result:
                fs = result.group(1).strip()
                fs = fs.split()[0]
                fs = fs.strip('"')
                if fs == 'ext2' or fs == 'ext3':
                    path = blkdev_path + str(partition)
                    return path

    # search failed
    return []
    def on_mkpart(self, devpath, parttype, start, size, end, fs):
        data = {}
        if self.has_disk(devpath):
            disk = self.disks[devpath]
            dev = parted.getDevice(devpath)
            partnumber = [ part.number for part in disk.partitions ]
            size = parted.sizeToSectors(size, "GB", 512)
            try:
                self.disks[devpath] = lib.rfparted.mkpart(dev, disk, parttype, start,size, end, fs)
                self.disks_tag[devpath] = True
            except Exception, e:
                data = self.error_handle(e,None)

            for p in disk.partitions:
                if p.number in partnumber:
                    continue
                data = self.error_handle(None,"add"+devpath+ str(p.number))
                break;
示例#50
0
def capture(args):
    """Captures an image of args.src to args.dest, and shrinks the filesystem on the last partition"""
    # Get device info
    device = parted.getDevice(args.src)
    lastpart = parted.newDisk(device).partitions[-1]
    lastsector = lastpart.geometry.end + 1
    sectorsize = device.sectorSize
    lastbyte = lastsector * sectorsize

    logging.debug("Total Size: %s", str(lastbyte))

    if os.path.isfile(args.dest):
        if not yes_or_no("File: '%s' already exists. Overwrite?", args.dest):
            print("Operation aborted.")
            raise SystemExit

    if not args.no_shrink: lastbyte = shrinkfs(lastpart, args.free)

    if not args.no_copy:
        docopy(args.src, args.dest, lastbyte, args.buffer_size)
def size_of_part(part_path, bytes=False):
    """Get the size of the partition at `part_path`

    If `bytes` is True, return size in bytes.
    Else, return size in gigabytes.
    """
    # Get the root Drive
    root = get_drive_path(part_path)
    # connect to that drive's partition table
    device = parted.getDevice(root)
    try:
        disk = parted.Disk(device)
    except parted._ped.DiskLabelException:
        raise OSError(f"NO PARTITION TABLE EXISTS ON { root } ")
    # Grab the right partiton
    part = disk.getPartitionByPath(part_path)
    # get size
    size = part.getSize(unit="b")
    # size conversion, if necessary
    if not bytes:
        size = bytes_to_gb(size)
    return size
示例#52
0
def select_device():
    """Returns a device object, retrieved from the users selection.
       Loops until a valid device is chosen, and the user has confirmed
       their selection."""
    show_devices()

    while True:
        device_path = input("\nInput the device to use: ")
        try:
            device = parted.getDevice(device_path)
        except parted.IOException:
            print(device_path + ": Cannot retrieve device.")
            pass

        print("\nALL DATA ON", device_path, "WILL BE LOST!")

        confirm = input("Really use this device? (y/N): ")
        if confirm != "y":
            print("Lets try that again.")
            pass
        else:
            return device
def print_disks_to_json_format(disks,free):
    """Return the stat of disks given with json."""
    data = []
    devpaths = disks.keys()
    for devpath in devpaths:
        dev = parted.getDevice(devpath)
        disksize = parted.formatBytes(dev.getLength()*512,'GB')
        dev_data = {
            "model": dev.model,
            "path":  dev.path,
            "size": disksize,
            "type": "unknow",
            "unit": 'GB',
            "table": [],
            }
        if(disks[devpath]):
            disk = disks[devpath]
            dev_data["type"] = disk.type
            dev_data["table"] = print_disk_to_json_format(disk,free)
        data.append(dev_data)

    return json.dumps(data)
示例#54
0
 def build_esp(self):
     ''' Try to find an ESP '''
     if not os.path.exists("/sys/firmware/efi"):
         return
     esp = list()
     for path in self.disks:
         device = parted.getDevice(path)
         try:
             disk = parted.Disk(device)
         except Exception:
             pass
         if disk.type != "gpt":
             continue
         partition = disk.getFirstPartition()
         while (partition is not None):
             fs = partition.fileSystem
             if fs is not None:
                 if fs.type in ["fat", "fat32"]:
                     f = partition.getFlag(parted.PARTITION_BOOT)
                     if f:
                         if partition.path not in esp:
                             esp.append(partition.path)
             partition = partition.nextPartition()
     self.installer.suggestions["esp"] = esp
示例#55
0
文件: fdisk.py 项目: huaixzk/fdisk.py
    def __init__(self, devpath):
        # Supported commands and corresponding handlers
        self.commands = {
            'a': self.toggle_bootable,
            'd': self.delete_partition,
            'm': self.print_menu,
            'n': self.add_partition,
            'o': self.create_empty,
            'p': self.print_partitions,
            'q': self.quit,
            'w': self.write
        }

        try:
            self.device = parted.getDevice(devpath)
        except parted.IOException as e:
            raise RuntimeError(e.message)

        try:
            self.disk = parted.newDisk(self.device)
            if self.disk.type != 'msdos':
                raise RuntimeError('Only MBR partitions are supported')
        except parted.DiskException:
            self.create_empty()
示例#56
0
    def build_partitions(self):
        os.popen('mkdir -p /tmp/os-installer/tmpmount')
        
        try:                                                                                            
            self.partitions = []
            
            model = Gtk.ListStore(str,str,str,str,str,str,str, object, bool, long, long, bool)
            model2 = Gtk.ListStore(str)
            
            swap_found = False
            
            if self.target_disk is not None:
                path =  self.target_disk # i.e. /dev/sda
                device = parted.getDevice(path)                
                try:
                    disk = parted.Disk(device)
                except Exception:
                    pass
                partition = disk.getFirstPartition()
                last_added_partition = PartitionSetup(partition)
                partition = partition.nextPartition()
                while (partition is not None):
                    if last_added_partition.partition.number == -1 and partition.number == -1:
                        last_added_partition.add_partition(partition)
                    else:                        
                        last_added_partition = PartitionSetup(partition)
                                        
                        if "swap" in last_added_partition.type:
                            last_added_partition.type = "swap"                                                            

                        if partition.number != -1 and "swap" not in last_added_partition.type and partition.type != parted.PARTITION_EXTENDED:
                            #Umount temp folder
                            if ('/tmp/os-installer/tmpmount' in commands.getoutput('mount')):
                                os.popen('umount /tmp/os-installer/tmpmount')

                            #Mount partition if not mounted
                            if (partition.path not in commands.getoutput('mount')):                                
                                os.system("mount %s /tmp/os-installer/tmpmount" % partition.path)

                            #Identify partition's description and used space
                            if (partition.path in commands.getoutput('mount')):
                                df_lines = commands.getoutput("df 2>/dev/null | grep %s" % partition.path).split('\n')
                                for df_line in df_lines:
                                    df_elements = df_line.split()
                                    if df_elements[0] == partition.path:
                                        last_added_partition.used_space = df_elements[4]  
                                        mount_point = df_elements[5]                              
                                        if "%" in last_added_partition.used_space:
                                            used_space_pct = int(last_added_partition.used_space.replace("%", "").strip())
                                            last_added_partition.free_space = int(float(last_added_partition.size) * (float(100) - float(used_space_pct)) / float(100))
                                        if os.path.exists(os.path.join(mount_point, 'etc/issue')):
                                            last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/issue')).replace('\\n', '').replace('\l', '').strip()
                                        if os.path.exists(os.path.join(mount_point, 'etc/evolveos-release')):
                                            last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/evolveos-release')).strip()                              
                                        if os.path.exists(os.path.join(mount_point, 'etc/lsb-release')):
                                            last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/lsb-release') + " | grep DISTRIB_DESCRIPTION").replace('DISTRIB_DESCRIPTION', '').replace('=', '').replace('"', '').strip()                                    
                                        if os.path.exists(os.path.join(mount_point, 'Windows/servicing/Version')):
                                            version = commands.getoutput("ls %s" % os.path.join(mount_point, 'Windows/servicing/Version'))                                    
                                            if version.startswith("6.1"):
                                                last_added_partition.description = "Windows 7"
                                            elif version.startswith("6.0"):
                                                last_added_partition.description = "Windows Vista"
                                            elif version.startswith("5.1") or version.startswith("5.2"):
                                                last_added_partition.description = "Windows XP"
                                            elif version.startswith("5.0"):
                                                last_added_partition.description = "Windows 2000"
                                            elif version.startswith("4.90"):
                                                last_added_partition.description = "Windows Me"
                                            elif version.startswith("4.1"):
                                                last_added_partition.description = "Windows 98"
                                            elif version.startswith("4.0.1381"):
                                                last_added_partition.description = "Windows NT"
                                            elif version.startswith("4.0.950"):
                                                last_added_partition.description = "Windows 95"
                                        elif os.path.exists(os.path.join(mount_point, 'Boot/BCD')):
                                            if os.system("grep -qs \"V.i.s.t.a\" " + os.path.join(mount_point, 'Boot/BCD')) == 0:
                                                last_added_partition.description = "Windows Vista bootloader"
                                            elif os.system("grep -qs \"W.i.n.d.o.w.s. .7\" " + os.path.join(mount_point, 'Boot/BCD')) == 0:
                                                last_added_partition.description = "Windows 7 bootloader"
                                            elif os.system("grep -qs \"W.i.n.d.o.w.s. .R.e.c.o.v.e.r.y. .E.n.v.i.r.o.n.m.e.n.t\" " + os.path.join(mount_point, 'Boot/BCD')) == 0:
                                                last_added_partition.description = "Windows recovery"
                                            elif os.system("grep -qs \"W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8\" " + os.path.join(mount_point, 'Boot/BCD')) == 0:
                                                last_added_partition.description = "Windows Server 2008 bootloader"
                                            else:
                                                last_added_partition.description = "Windows bootloader"
                                        elif os.path.exists(os.path.join(mount_point, 'Windows/System32')):
                                            last_added_partition.description = "Windows"
                                        break
                            else:
                                print "Failed to mount %s" % partition.path

                            
                            #Umount temp folder
                            if ('/tmp/os-installer/tmpmount' in commands.getoutput('mount')):
                                os.popen('umount /tmp/os-installer/tmpmount')
                                
                    if last_added_partition.size > 1.0:
                        if last_added_partition.partition.type == parted.PARTITION_LOGICAL:
                            display_name = "  " + last_added_partition.name
                        else:
                            display_name = last_added_partition.name

                        iter = model.append([display_name, last_added_partition.type, last_added_partition.description, "", "", '%.0f' % round(last_added_partition.size, 0), str(last_added_partition.free_space), last_added_partition, False, last_added_partition.start, last_added_partition.end, False]);
                        if last_added_partition.partition.number == -1:                     
                            model.set_value(iter, INDEX_PARTITION_TYPE, "<span foreground='#a9a9a9'>%s</span>" % last_added_partition.type)                                    
                        elif last_added_partition.partition.type == parted.PARTITION_EXTENDED:                    
                            model.set_value(iter, INDEX_PARTITION_TYPE, "<span foreground='#a9a9a9'>%s</span>" % _("Extended"))  
                        else:                                        
                            if last_added_partition.type == "ntfs":
                                color = "#42e5ac"
                            elif last_added_partition.type == "fat32":
                                color = "#18d918"
                            elif last_added_partition.type == "ext4":
                                color = "#4b6983"
                            elif last_added_partition.type == "ext3":
                                color = "#7590ae"
                            elif last_added_partition.type in ["linux-swap", "swap"]:
                                color = "#c1665a"
                                last_added_partition.mount_as = "swap"
                                model.set_value(iter, INDEX_PARTITION_MOUNT_AS, "swap")
                            else:
                                color = "#a9a9a9"
                            model.set_value(iter, INDEX_PARTITION_TYPE, "<span foreground='%s'>%s</span>" % (color, last_added_partition.type))                                            
                            #deviceSize = float(device.getSize()) * float(0.9) # Hack.. reducing the real size to 90% of what it is, to make sure our partitions fit..
                            #space = int((float(partition.getSize()) / deviceSize) * float(80))                            
                            self.partitions.append(last_added_partition)
                            
                    partition = partition.nextPartition()
            self.treeview.set_model(model)
        except Exception, e:
            print e
示例#57
0
def get_device_by_path(device):
    """Returns parted device for given device file"""
    dev = parted.getDevice(device)
    dsk = parted.Disk(dev)
    return dsk
    def findGpt(self):
        self.blkidParts = BlkidParser(log=self.log.getChild("blkid"))

        deviceOrLabel = self.im.platformConf['grub']['device']
        if deviceOrLabel.startswith('/dev'):
            tgtDevice, tgtLabel = deviceOrLabel, None
        else:
            tgtDevice, tgtLabel = None, deviceOrLabel

        # enumerate labeled partitions to try to identify
        # the boot device
        for part in self.blkidParts:
            dev, partno = part.splitDev()
            if tgtLabel is not None and tgtLabel == part.label:
                if not len(partno):
                    self.log.error("cannot use whole disk")
                    return 1
                if self.device is None:
                    self.device = dev
                else:
                    self.log.error("found multiple devices: %s, %s",
                                   dev, self.device)
                    return 1
            elif tgtDevice is not None and tgtDevice == dev:
                if not len(partno):
                    self.log.error("cannot use whole disk")
                    return 1
                if self.device is None:
                    self.device = dev
                else:
                    self.log.error("found multiple devices: %s, %s",
                                   dev, self.device)
                    return 1
        if self.device is None:
            self.log.error("cannot find an install device")
            return 1

        code = self.assertUnmounted()
        if code: return code

        # optionally back up a config partition
        # if it's on the boot device
        for part in self.blkidParts:
            dev, partno = part.splitDev()
            if dev == self.device and part.label == 'ONL-CONFIG':
                self.backupConfig(part.device)

        self.partedDevice = parted.getDevice(self.device)
        self.partedDisk = parted.newDisk(self.partedDevice)

        # enumerate the partitions that will stay and go
        minpart = -1
        for part in self.partedDisk.partitions:

            if part.getFlag(parted.PARTITION_HIDDEN):
                minpart = max(minpart, part.number+1)
                continue

            # else, the partition should exist
            blkidParts = [x for x in self.blkidParts if x.device == part.path]
            if not blkidParts:
                self.log.warn("cannot identify partition %s", part)
                continue

            blkidPart = blkidParts[0]
            if not blkidPart.isOnieReserved(): continue

            # else, check the GPT label for reserved-ness
            if (part.name
                and ('GRUB' in part.name
                     or 'ONIE-BOOT' in part.name
                     or 'DIAG' in part.name)):
                minpart = max(minpart, part.number+1)

        if minpart < 0:
            self.log.error("cannot find an install partition")
            return 1
        self.minpart = minpart

        return 0