def _set_file_system_type(self): try: print "---------------" print "TRYING TO SET FILE SYSTEM of %s to %s" % ( self.volume.device_path, self.new_file_system) try: parted_device = parted.Device(self.volume.device_path) parted_disk = parted.Disk(parted_device) except: parted_device = parted.Device(self.volume.path) parted_disk = parted.Disk(parted_device) parted_partition = parted_disk.getPartitionByPath(self.volume.path) parted_partition.system = parted.fileSystemType.get( self.new_file_system_parted) # Commit Changes parted_disk.commit() print "SUCCCESS" except Exception as e: print "FAILED TO SET FILE SYSTEM", e.message self.error = True self.emit(SIGNAL("partition_table_error()"))
def __init__(self, path, arch="x86"): self._arch = arch self._path = "" self._device = None self._model = "" self._disk = None self._disklabel = "" self._length = 0 # total sectors self._sectorSize = 0 self._isSetup = False device = parted.Device(path) self._model = device.model self._length = device.length self._sectorSize = device.sectorSize self._device = device try: self._disk = parted.Disk(device) except: label = archinfo[self._arch]["disklabel"] self._disk = parted.freshDisk(self._device, ty=label) self._disklabel = self._disk.type self._path = path self._partitions = None self._update()
def _remove_volume_flags(self): try: print "---------------" print "TRYING TO REMOVE FLAGS of %s" % self.volume.device_path parted_device = parted.Device(self.volume.device_path) parted_disk = parted.Disk(parted_device) parted_partition = parted_disk.getPartitionByPath(self.volume.path) # Get possible flags parted_flags = parted.partitionFlag.values() # Remove any Flags flags_found = parted_partition.getFlagsAsString().split(", ") if flags_found: for flag in flags_found: parted_partition.unsetFlag(parted_flags.index(flag) + 1) # Commit Changes parted_disk.commit() print "SUCCCESS" except Exception as e: print "FAILED TO REMOVE FLAGS \n", e.message
def creeTablePartition(self): """Créer une nouvelle table d Efface signaturev disque wipefs --all /dev/sdb2 /dev/sdb2 : 2 octets ont été effacés à l'index 0x00000438 (ext4) : 53 ef Cree Systeme fichiers fat Créé le systeme de fichiers mkfs.fat -F32 -v -I -n "BOOT" /dev/sdb1 mkfs.fat 3.0.28 (2015-05-16) /dev/sdb1 has 255 heads and 63 sectors per track, hidden sectors 0x0800; logical sector size is 512, using 0xf8 media descriptor, with 2048000 sectors; drive number 0x80; filesystem has 2 32-bit FATs and 8 sectors per cluster. FAT size is 1997 sectors, and provides 255496 clusters. There are 32 reserved sectors. Volume ID is 2107cb40, volume label BOOT . Cree Systeme fichiers ext4 e partition sur un disque""" dev = parted.Device(self.disque) table = parted.freshDisk(dev, 'gpt') #gpt msdos if not table.commit(): #Si c'est Vrai on le commit sys.exit() else: print("\nNouvelle table de partition " + self.disque) time.sleep(3)
def crear_particion(self, drive, start, end, fs, partype, format): ''' Argumentos: - disco: el disco donde se realizará la partición. Ej: /dev/sda - tipo: el tipo de partición a realizar {primary, extended, logical} - formato: el formato que usará la partición {ext2, ext4, linux-swap,fat32, ntfs} - inicio: donde comenzará la partición, en kB - fin: donde terminará la partición, en kB ''' i = 0 j = 0 k = 0 dev = parted.Device(drive) disk = parted.Disk(dev) s_sec = start * 1024 / dev.sectorSize e_sec = end * 1024 / dev.sectorSize if partype == 'primary' or partype == 0: pedtype = _ped.PARTITION_NORMAL elif partype == 'logical' or partype == 1: pedtype = _ped.PARTITION_LOGICAL elif partype == 'extended' or partype == 2: pedtype = _ped.PARTITION_EXTENDED else: return False while True: if not dev.busy: break try: geometry = parted.Geometry(device=dev, start=s_sec, end=e_sec) i += 1 except Exception, a: print a
def partition_table(device, part_type, fs_type): # wipe the old partition table utils.sysexec( "dd if=/dev/zero of={} bs=512 count=1".format(device), log) # get the device dev = parted.Device(device) disk = parted.freshDisk(dev, part_type) # create one big partition on each block device constraint = parted.constraint.Constraint(device=dev) geometry = parted.geometry.Geometry(device=dev, start=0, end=1) fs = parted.filesystem.FileSystem(type=fs_type, geometry=geometry) new_part = parted.partition.Partition(disk, type=parted.PARTITION_NORMAL, fs=fs, geometry=geometry) # make it an lvm partition new_part.setFlag(parted.PARTITION_LVM) # actually add the partition to the disk disk.addPartition(new_part, constraint) disk.maximizePartition(new_part, constraint) disk.commit() log.write("Current disk for {} - partition type {}\n{}\n".format( device, part_type, disk)) log.write("Current dev for {}\n{}\n".format(device, dev)) del disk
def best_disklabel_type(self, device): """The best disklabel type for the specified device.""" if flags.testing: return self.default_disklabel_type parted_device = parted.Device(path=device.path) # if there's a required type for this device type, use that label_type = self.required_disklabel_type(parted_device.type) log.debug("required disklabel type for %s (%s) is %s", device.name, parted_device.type, label_type) if not label_type: # otherwise, use the first supported type for this platform # that is large enough to address the whole device label_type = self.default_disklabel_type log.debug("default disklabel type for %s is %s", device.name, label_type) for lt in self.disklabel_types: l = parted.freshDisk(device=parted_device, ty=lt) if l.maxPartitionStartSector > parted_device.length: label_type = lt log.debug("selecting %s disklabel for %s based on size", label_type, device.name) break return label_type
def post_init(self): self.device = parted.Device(self.devpath) self.disk = parted.Disk(self.device) self.type = self.disk.type self.sector = int(self.device.sectorSize) # self.grainSize = self.disk.partitionAlignment.intersect(self.disk.device.optimumAlignment).grainSize # 使用统一的分区对齐值 self.grainSize = PARTED_START_SECTOR
def do_image_hd(outf, hd, fslabel, target, grub_version, grub_fw_type=None): # pylint: disable=too-many-arguments # pylint: disable=too-many-locals # pylint: disable=too-many-branches sector_size = 512 s = size_to_int(hd.text("size")) size_in_sectors = s / sector_size imagename = os.path.join(target, hd.text("name")) outf.do('rm -f "%s"' % imagename, allow_fail=True) f = open(imagename, "wb") f.truncate(size_in_sectors * sector_size) f.close() imag = parted.Device(imagename) if hd.tag == "gpthd": disk = parted.freshDisk(imag, "gpt") else: disk = parted.freshDisk(imag, "msdos") if grub_version == 199: grub = grubinstaller199(outf) elif grub_version == 202 and grub_fw_type == "efi": grub = grubinstaller202(outf, "efi") elif grub_version == 202 and grub_fw_type == "hybrid": grub = grubinstaller202(outf, "hybrid") elif grub_version == 202: grub = grubinstaller202(outf) else: grub = grubinstaller_base(outf) current_sector = 2048 for part in hd: if part.tag == "partition": ppart = create_partition(disk, part, parted.PARTITION_NORMAL, fslabel, size_in_sectors, current_sector) if part.text("label") in fslabel: create_label(outf, disk, part, ppart, fslabel, target, grub) elif part.tag == "extended": ppart = create_partition(disk, part, parted.PARTITION_EXTENDED, fslabel, size_in_sectors, current_sector) create_logical_partitions(outf, disk, part, ppart, fslabel, target, grub) else: continue current_sector += ppart.getLength() disk.commit() if hd.has("grub-install") and grub_version: grub.install(target) return hd.text("name")
def partedDevice(self): if self.exists and self.status and not self._partedDevice: ctx.logger.debug("looking up parted Device: %s" % self.path) try: self._partedDevice = parted.Device(path=self.path) except (_ped.IOException, _ped.DeviceException): pass return self._partedDevice
def get_disk_partition(self): """ Return the PedDisk and partition of the selected device """ import parted parent = self.drives[self._drive]['parent'] dev = parted.Device(path=parent) disk = parted.Disk(device=dev) for part in disk.partitions: if self._drive == '/dev/%s' % (part.getDeviceNodeName(), ): return disk, part raise TailsInstallerError(_('Unable to find partition'))
def nueva_tabla_particiones(self, drive, t): dev = parted.Device(drive) new = parted.freshDisk(dev, t) while True: if not dev.busy: break try: new.commit() except _ped.IOException, x: print x
def __init__(self): self.disque = ((parted.getAllDevices())[-1].path ) #Unite disque ,dernier p.e /dev/sdb if '/dev/sda' in self.disque: #Disque principal systeme sys.exit() else: print("Disque = ", self.disque) self.dev = parted.Device(self.disque) #Parted device self.partitions = parted.Disk(self.dev) #Partition time.sleep(1)
def num_particion(self, drive, ptype, start, end): dev = parted.Device(drive) disk = parted.Disk(dev) s_sec = start * 1024 / dev.sectorSize e_sec = end * 1024 / dev.sectorSize m_sec = ((e_sec - s_sec) / 2) + s_sec if ptype == 'logical' or ptype == 'primary' or ptype == 1 or ptype == 0: part = disk.getPartitionBySector(m_sec) else: part = disk.getExtendedPartition() return part.number
def blockPartitions(path): device = parted.Device(path) try: disk = parted.Disk(device) except: # FIXME: This is suck! Must be changed! disk = parted.freshDisk(device, parted.diskType['msdos']) partition = disk.getFirstPartition() while partition: if partition.fileSystem and partition.fileSystem.type != "linux-swap": yield partition.path, partition.fileSystem.type partition = partition.nextPartition()
def partedDevice(self): if not self._partedDevice and self.device and \ os.path.exists(self.device): # We aren't guaranteed to be able to get a device. In # particular, built-in USB flash readers show up as devices but # do not always have any media present, so parted won't be able # to find a device. try: self._partedDevice = parted.Device(path=self.device) except (_ped.IOException, _ped.DeviceException): pass return self._partedDevice
def createpartitions(self): ''' Partition the LVM volume into persistent and swap partitions using the parted module. ''' dev = parted.Device(path=self.lvpath) dev.removeFromCache() disk = parted.freshDisk(dev, 'msdos') constraint = parted.Constraint(device=dev) persist_size = int(0.75 * constraint.maxSize); self.createpartition(device=dev, disk=disk, start=1, end=(persist_size - 1) , type="ext4") self.createpartition(device=dev, disk=disk, start=persist_size, end=(constraint.maxSize - 1) , type="linux-swap(v1)") disk.commit()
def bestDiskLabelType(self, device): """The best disklabel type for the specified device.""" if flags.testing: return self.defaultDiskLabelType # the device is FBA DASD if dasd.is_fba_dasd(device.name): return "msdos" # the device is DASD elif parted.Device(path=device.path).type == parted.DEVICE_DASD: return "dasd" # other types of devices return super(S390, self).bestDiskLabelType(device)
def initVGs(): VGs={} PVs={} disks={} re_split=re.compile('[ \t]+') dsk_re=re.compile('([/a-z]*)([0-9]*)') p=subprocess.Popen(['pvs','--segments','--nosuffix','--noheadings','--units','B','-ovg_name,vg_extent_size,seg_start,seg_size,stripes,pv_name,pv_size,pv_free,pvseg_start,pvseg_size,lv_name'], stdout=subprocess.PIPE, stderr=stderr) for l in p.stdout: l=l.replace('\n','') c=re_split.split(l) try: empty,vg_name,vg_extent_size,seg_start,seg_size,stripes,pv_name,pv_size,pv_free,pvseg_start,pvseg_size = c[0:10] except: continue try: VG=VGs[vg_name] except: VG=LVM_VG(vg_name, vg_extent_size) VGs[vg_name]=VG try: PV=PVs[pv_name] except: m=dsk_re.match(pv_name) disk_path=m.group(1) try: disk=disks[disk_path] except: dev=parted.Device(disk_path) disk=parted.Disk(dev) disks[disk_path] = self.disk pv_part=disk.getPartitionByPath(part_name) PV=LVM_PV(pv_part,VG,pv_size,pv_free) PVs[pv_name]=PV if len(c) > 10: try: lv_name=c[10] LV=VG[lv_name] except: LV=LVM_LV(lv_name) VG[lv_name]=LV try: seg=LV[seg_start] except Exception: seg=LV_segment(seg_start,seg_size) LV[seg_start]=seg seg.append(PV_segment(PV,pvseg_start,pvseg_size)) return VGs
def partitionDelete(self): if self.treePartitionWidget.selectedItems(): select = self.treePartitionWidget.selectedItems()[0] if isinstance(select.parent(), QTreeWidgetItem): try: print(select.parent().text(0)) disk = parted.Disk(parted.Device(select.parent().text(0))) for partition in disk.partitions: if partition.path == select.text(0): print(partition.path) #disk.deletePartition(partition) except parted.PartitionException as err: print(err)
def parted_device(self): if not self._parted_device and self.device: if os.path.exists(self.device): # We aren't guaranteed to be able to get a device. In # particular, built-in USB flash readers show up as devices but # do not always have any media present, so parted won't be able # to find a device. try: self._parted_device = parted.Device(path=self.device) except (_ped.IOException, _ped.DeviceException) as e: log.error("DiskLabel.parted_device: Parted exception: %s", e) else: log.info("DiskLabel.parted_device: %s does not exist", self.device) if not self._parted_device: log.info("DiskLabel.parted_device returning None") return self._parted_device
def partition(device): dev = parted.Device(path=device) disk = parted.freshDisk(dev, 'msdos') constraint = parted.Constraint(device=dev) new_geom = parted.Geometry(device=dev, start=1, end=(constraint.maxSize - 1)) filesystem = parted.FileSystem(type="ext2", geometry=new_geom) partition = parted.Partition(disk=disk, fs=filesystem, type=parted.PARTITION_NORMAL, geometry=new_geom) constraint = parted.Constraint(exactGeom=new_geom) partition.setFlag(parted.PARTITION_BOOT) disk.addPartition(partition=partition, constraint=constraint) disk.commit()
def remover_bandera(self, drive, part, flag): dev = parted.Device(drive) disk = parted.Disk(dev) partition = disk.getPartitionByPath(part) if flag == 'boot': pedflag = _ped.PARTITION_BOOT while True: if not dev.busy: break if partition.unsetFlag(pedflag): if disk.commit(): return True else: return False else: return False
def __init__(self, device=None, PedDisk=None): """Create a new Disk object from the device and type specified. The device is a Device object and type is a string matching a key in the diskType hash.""" if PedDisk: self.__disk = PedDisk if device is None: self._device = parted.Device(PedDevice=self.__disk.dev) else: self._device = device elif device is None: raise parted.DiskException("no device specified") else: self.__disk = _ped.Disk(device.getPedDevice()) self._device = device # pylint: disable=W0108 self._partitions = CachedList(lambda : self.__getPartitions())
def getDevicePartedInfo(devPath): try: partedDevice = parted.Device(devPath) except: return {} try: partedDisk = parted.Disk(partedDevice) except: # partedDevice is a partition or a disk without partition table return { 'model': partedDevice.model, 'sectorSize': partedDevice.sectorSize, 'type': '', 'freeSpaceRegions': [], 'partitions': {} } freeRegionList = [] for region in partedDisk.getFreeSpaceRegions(): freeBytes = region.length * partedDevice.sectorSize freeRegionList.append( (region.start, region.end, region.length, freeBytes)) partitions = {} for partition in partedDisk.partitions: partitionFlags = [ flagname for (flag, flagname) in parted.partition.partitionFlag.items() if partition.getFlag(flag) ] partitions.update({ partition.path: (partitionFlags, partition.geometry.start, partition.geometry.end) }) return { 'model': partedDevice.model, 'sectorSize': partedDevice.sectorSize, 'type': partedDisk.type, 'freeSpaceRegions': freeRegionList, 'partitions': partitions }
def bestDiskLabelType(self, device): """The best disklabel type for the specified device.""" if flags.testing: return self.defaultDiskLabelType parted_device = parted.Device(path=device.path) label_type = self.defaultDiskLabelType log.debug("default disklabel type for %s is %s", device.name, label_type) # use the first supported type for this platform # that is large enough to address the whole device for lt in self.diskLabelTypes: l = parted.freshDisk(device=parted_device, ty=lt) if l.maxPartitionStartSector > parted_device.length: label_type = lt log.debug("selecting %s disklabel for %s based on size", label_type, device.name) break return label_type
def __init__(self, path, size, schema=None): """Initialize an image file to a given size in bytes. :param path: Path to image file on the file system. :type path: str :param size: Size in bytes to set the image file to. :type size: int :param schema: The partitioning schema of the volume. :type schema: VolumeSchema Public attributes: * path - Path to the image file. """ self.path = path # Create an empty image file of a fixed size. Unlike # truncate(1) --size 0, os.truncate(path, 0) doesn't touch the # file; i.e. it must already exist. with open(path, 'wb'): pass # Truncate to zero, so that extending the size in the next call # will cause all the bytes to read as zero. Stevens $4.13 os.truncate(path, 0) os.truncate(path, size) # Prepare the device and disk objects for parted to be used for all # future partition() calls. Only do it if we actually care about the # partition table. if schema is None: self.sector_size = 512 self.device = None self.disk = None self.schema = None else: self.device = parted.Device(self.path) label = 'msdos' if schema is VolumeSchema.mbr else 'gpt' self.schema = schema self.disk = parted.freshDisk(self.device, label) self.sector_size = self.device.sectorSize
def __init__(self, device=None, start=None, length=None, end=None, PedGeometry=None): """Create a new Geometry object for the given _ped.Device that extends for length sectors from the start sector. Optionally, an end sector can also be provided.""" if PedGeometry: self.__geometry = PedGeometry if device is None: self._device = parted.Device(PedDevice=self.__geometry.dev) else: self._device = device elif not end: self._device = device self.__geometry = _ped.Geometry(self.device.getPedDevice(), start, length) elif not length and (end > start): self._device = device self.__geometry = _ped.Geometry(self.device.getPedDevice(), start, (end - start + 1), end=end) elif start and length and end and (end > start): self._device = device self.__geometry = _ped.Geometry(self.device.getPedDevice(), start, length, end=end) else: raise parted.GeometryException("must specify PedGeometry or (device, start, length) or (device, start, end) or (device, start, length, end)")
def borrar_particion(self, drive, part): ''' Argumentos: - disco: el disco donde se realizará la partición. Ej: /dev/sda - tipo: el tipo de partición a realizar {primary, extended, logical} - formato: el formato que usará la partición {ext2, ext4, linux-swap,fat32, ntfs} - inicio: donde comenzará la partición, en kB - fin: donde terminará la partición, en kB ''' i = 0 dev = parted.Device(drive) disk = parted.Disk(dev) partition = disk.getPartitionByPath(part) while True: if not dev.busy: break try: disk.deletePartition(partition=partition) i += 1 except Exception, x: print x
def populate(self, nonraids, mpaths, raids, activeByDefault=False): def _addTuple(tuple): global totalDevices, totalSize global selectedDevices, selectedSize added = False self.store.append(None, tuple) for pg in self.pages: if pg.cb.isMember(tuple[0]): added = True pg.cb.addToUI(tuple) # Only update the size label if this device was added to any pages. # This prevents situations where we're only displaying the basic # filter that has one disk, but there are several advanced disks # in the store that cannot be seen. if added: totalDevices += 1 totalSize += tuple[0]["XXX_SIZE"] if tuple[ACTIVE_COL]: selectedDevices += 1 selectedSize += tuple[0]["XXX_SIZE"] def _isProtected(info): protectedNames = map(udev_resolve_devspec, self.anaconda.protected) sysfs_path = udev_device_get_sysfs_path(info) for protected in protectedNames: _p = "/sys/%s/%s" % (sysfs_path, protected) if os.path.exists(os.path.normpath(_p)): return True return False def _active(info): if _isProtected(info) or activeByDefault: return True name = udev_device_get_name(info) if self.anaconda.storage.exclusiveDisks and \ name in self.anaconda.storage.exclusiveDisks: return True elif self.anaconda.storage.ignoredDisks and \ name not in self.anaconda.storage.ignoredDisks: return True else: return False for d in nonraids: name = udev_device_get_name(d) # We aren't guaranteed to be able to get a device. In # particular, built-in USB flash readers show up as devices but # do not always have any media present, so parted won't be able # to find a device. try: partedDevice = parted.Device(path="/dev/" + name) except (_ped.IOException, _ped.DeviceException): continue d["XXX_SIZE"] = int(partedDevice.getSize()) # cciss controllers, without any sets defined, show up as a 0 size # blockdev, ignore these if d["XXX_SIZE"] == 0: continue # This isn't so great, but iSCSI and s390 devices have an ID_PATH # that contains a lot of useful identifying info, so that should be # displayed instead of a blank WWID. if udev_device_is_iscsi(d) or udev_device_is_dasd( d) or udev_device_is_zfcp(d): ident = udev_device_get_path(d) else: ident = udev_device_get_wwid(d) tuple = (d, True, _active(d), _isProtected(d), name, partedDevice.model, str(d["XXX_SIZE"]) + " MB", udev_device_get_vendor(d), udev_device_get_bus(d), udev_device_get_serial(d), ident, "", "", "", "") _addTuple(tuple) if raids and flags.dmraid: used_raidmembers = [] for rs in block.getRaidSets(): # dmraid does everything in sectors size = (rs.rs.sectors * 512) / (1024.0 * 1024.0) fstype = "" # get_members also returns subsets with layered raids, we only # want the devices members = filter(lambda m: isinstance(m, block.device.RaidDev), list(rs.get_members())) members = map(lambda m: m.get_devpath(), members) for d in raids: if udev_device_get_name(d) in members: fstype = udev_device_get_format(d) sysfs_path = udev_device_get_sysfs_path(d) break # Skip this set if none of its members are in the raids list if not fstype: continue used_raidmembers.extend(members) # biosraid devices don't really get udev data, at least not in a # a way that's useful to the filtering UI. So we need to fake # that data now so we have something to put into the store. data = { "XXX_SIZE": size, "ID_FS_TYPE": fstype, "DM_NAME": rs.name, "name": rs.name, "sysfs_path": sysfs_path } model = "BIOS RAID set (%s)" % rs.rs.set_type tuple = (data, True, _active(data), _isProtected(data), rs.name, model, str(size) + " MB", "", "", "", "", "", "", "", "") _addTuple(tuple) unused_raidmembers = [] for d in raids: if udev_device_get_name(d) not in used_raidmembers: unused_raidmembers.append(udev_device_get_name(d)) self.anaconda.intf.unusedRaidMembersWarning(unused_raidmembers) for mpath in mpaths: # We only need to grab information from the first device in the set. name = udev_device_get_name(mpath[0]) try: partedDevice = parted.Device(path="/dev/" + name) except (_ped.IOException, _ped.DeviceException): continue mpath[0]["XXX_SIZE"] = int(partedDevice.getSize()) model = partedDevice.model # However, we do need all the paths making up this multipath set. paths = "\n".join(map(udev_device_get_name, mpath)) # We use a copy here, so as to not modify the original udev info # dict as that would break NameCache matching data = mpath[0].copy() data["name"] = udev_device_get_multipath_name(mpath[0]) tuple = (data, True, _active(data), _isProtected(data), udev_device_get_multipath_name(mpath[0]), model, str(mpath[0]["XXX_SIZE"]) + " MB", udev_device_get_vendor(mpath[0]), udev_device_get_bus(mpath[0]), udev_device_get_serial(mpath[0]), udev_device_get_wwid(mpath[0]), paths, "", "", "") _addTuple(tuple)