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 disk_doldur(self, widget): self.ebeveyn.milis_ayarlari["takas_disk"] = "" self.ebeveyn.milis_ayarlari["sistem_disk"] = "" self.ebeveyn.milis_ayarlari["uefi_disk"] = "" if self.ebeveyn.stack_secili == 4: self.ebeveyn.ileri_dugme.set_sensitive(False) self.diskler_combo.remove_all() self.grub_combo.remove_all() self.diskler = parted.getAllDevices() for disk in self.diskler: try: if parted.Disk(disk).type == "msdos" or parted.Disk( disk).type == "gpt": self.diskler_liste[disk.path] = { "parted": parted.Disk(disk), "tum_boyut": format(disk.getSize(unit="GB"), '.2f'), "bölüm": [] } self.diskler_combo.append_text( disk.path + " | " + disk.model + " | " + format(disk.getSize(unit="GB"), '.2f') + "GB") self.grub_combo.append_text(disk.path + " | " + disk.model + " | " + format(disk.getSize( unit="GB"), '.2f') + "GB") except parted.DiskLabelException: disk = parted.freshDisk(disk, "msdos") # CDROM Aygıtları için try: disk.commit() except parted.IOException: pass else: disk = disk.device self.diskler_liste[disk.path] = { "parted": parted.Disk(disk), "tum_boyut": format(disk.getSize(unit="GB"), '.2f'), "bölüm": [] } self.diskler_combo.append_text( disk.path + " | " + disk.model + " | " + format(disk.getSize(unit="GB"), '.2f') + "GB") self.grub_combo.append_text(disk.path + " | " + disk.model + " | " + format(disk.getSize( unit="GB"), '.2f') + "GB") for bolum in parted.Disk(disk).partitions: gelen = self.bolumBilgi(bolum) if gelen: self.diskler_liste[disk.path]["bölüm"].append(gelen) self.diskler_combo.set_active(0) self.grub_combo.set_active(0)
def partitions(self): pts = [] disk = parted.Disk(self.device) for part in disk.partitions: pts.append( (self.part_prefix + str(part.number), part.fileSystem.type)) return pts
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 __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 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 _get_best_label_type(self): label_type = self._default_label_type label_types = self.get_platform_label_types()[:] if label_type in label_types: label_types.remove(label_type) if label_type: label_types.insert(0, label_type) if arch.is_s390(): if blockdev.s390.dasd_is_fba(self.device): # the device is FBA DASD return "msdos" elif self.parted_device.type == parted.DEVICE_DASD: # the device is DASD return "dasd" elif util.detect_virt(): # check for dasds exported into qemu as normal virtio/scsi disks try: _parted_disk = parted.Disk(device=self.parted_device) except (_ped.DiskLabelException, _ped.IOException, NotImplementedError): pass else: if _parted_disk.type == "dasd": return "dasd" for lt in label_types: if self._label_type_size_check(lt): log.debug("selecting %s disklabel for %s based on size", label_type, os.path.basename(self.device)) label_type = lt break return label_type
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 __init__(self, disk=None, type=None, fs=None, geometry=None, PedPartition=None): if PedPartition is None: if disk is None: raise parted.PartitionException("no disk specified") elif type is None: raise parted.PartitionException("no type specified") elif geometry is None: raise parted.PartitionException("no geometry specified") self._fileSystem = fs self._geometry = geometry self._disk = disk if fs is None: self.__partition = _ped.Partition(disk.getPedDisk(), type, geometry.start, geometry.end) else: self.__partition = _ped.Partition(disk.getPedDisk(), type, geometry.start, geometry.end, parted.fileSystemType[fs.type]) else: self.__partition = PedPartition self._geometry = parted.Geometry(PedGeometry=self.__partition.geom) if disk is None: self._disk = parted.Disk(PedDisk=self.__partition.disk) else: self._disk = disk if self.__partition.fs_type is None: self._fileSystem = None else: self._fileSystem = parted.FileSystem(type=self.__partition.fs_type.name, geometry=self._geometry)
def device_probe_all(mia, operid, dummy): def get_device_list(): hd_list = filter(lambda d: d.type != parted.DEVICE_DM and \ d.readOnly != True, # CD-ROM will be read only. parted.getAllDevices()) return hd_list mia.set_step(operid, 0, -1) result = [] # The following commented code is implemented by kudzu. devlist = get_device_list() if devlist: for dev in devlist: newdisklabel = None try: disk = parted.Disk(dev) except _ped.DiskLabelException: # For the disk without any disk label, create it. # disk label is disk partition table format dltype = parted.diskType['msdos'] disk = parted.freshDisk(device=dev, ty=dltype) #newdisklabel = 'y' #disk = dev.disk_new_fresh(parted.disk_type_get('msdos')) # Model might contain GB2312, it must be convert to Unicode. model = iconv.iconv('gb2312', 'utf8', dev.model).encode('utf8') result.append((dev.path, dev.length, model)) CF.S.all_harddisks[dev.path] = (dev, disk, newdisklabel) dolog('operations.parted.device_probe_all: %s\n' % str(result)) return result
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 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 __make_root_boot__(device): """Make Root partition bootable. This ONLY works if the root partition is the only partition on the drive """ disk = parted.Disk(device) partitions = disk.getPrimaryPartitions() partitions[0].setFlag(parted.PARTITION_BOOT) disk.commit()
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 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 get_devices(): device_list = parted.getAllDevices() disk_dic = {} myhomepath = '/bootmnt' if os.path.exists(myhomepath): myhome = subprocess.check_output(["df", "-P", myhomepath]).decode() else: myhome = "" for dev in device_list: if dev.path in myhome: continue # I left all of the below here but commented out to see some use cases # isbusy = in use/mounted. Needs to flag if 'yes' to prompt user to umount # isbusy = dev.busy # path gives /dev/sda or something similar # myname = dev.path # Hard drives measure themselves assuming kilo=1000, mega=1mil, etc # limiter = 1000 # Some disk size calculations # byte_size = dev.length * dev.sectorSize # megabyte_size = byte_size / (limiter * limiter) # gigabyte_size = megabyte_size / limiter # print(byte_size) # print(dev.length) # Must create disk object to drill down # Skip all blacklisted devices dev_name = dev.path[5:] if any(re.search(expr, dev_name) for expr in DEVICE_BLACKLIST): continue # Skip cd drive and special devices like LUKS and LVM disk_obj = None if not dev.path.startswith("/dev/sr") and not dev.path.startswith( "/dev/mapper"): try: disk_obj = parted.Disk(dev) result = OK except parted.DiskLabelException: # logging.warning(_('Unrecognised disk label in device {0}.'.format(dev.path))) result = UNRECOGNISED_DISK_LABEL except Exception as general_error: logging.error(general_error) msg = _( "Exception: {0}.\nFor more information take a look at /tmp/thus.log" ).format(general_error) show.error(None, msg) result = UNKNOWN_ERROR finally: disk_dic[dev.path] = (disk_obj, result) return disk_dic
def __make_root__(device, start=config["ROOT"]["START"], end=config["ROOT"]["END"], fs=config["ROOT"]["fs"]): """Make root partition""" # __parted__(device, ["mkpart", name, fs, str(start), str(end)]) size = sectors_to_size(device.length, device.sectorSize) try: if start[-1] == "%": start = int(start[:-1]) / 100 start = int(size * start) except TypeError: pass try: if end[-1] == "%": end = int(end[:-1]) / 100 end = int(size * end) except TypeError: pass disk = parted.Disk(device) start_geo = parted.geometry.Geometry(device=device, start=parted.sizeToSectors(common.real_number(start - 20), "MB", device.sectorSize), end=parted.sizeToSectors(start + 20, "MB", device.sectorSize)) end_geo = parted.geometry.Geometry(device=device, start=parted.sizeToSectors(common.real_number(end - 40), "MB", device.sectorSize), end=parted.sizeToSectors(end, "MB", device.sectorSize)) min_size = parted.sizeToSectors(common.real_number((end - start) - 150), "MB", device.sectorSize) max_size = parted.sizeToSectors(common.real_number((end - start) + 150), "MB", device.sectorSize) const = parted.Constraint(startAlign=device.optimumAlignment, endAlign=device.optimumAlignment, startRange=start_geo, endRange=end_geo, minSize=min_size, maxSize=max_size) geometry = parted.geometry.Geometry(start=parted.sizeToSectors(start, "MB", device.sectorSize), length=parted.sizeToSectors((end - start), "MB", device.sectorSize), device=device) new_part = parted.Partition(disk=disk, type=parted.PARTITION_NORMAL, geometry=geometry) disk.addPartition(partition=new_part, constraint=const) disk.commit() time.sleep(0.1) __mkfs__(new_part.path, fs) return new_part.path
def get_devices(): """ Get all devices """ device_list = parted.getAllDevices() disk_dic = {} myhomepath = '/run/archiso/bootmnt' if os.path.exists(myhomepath): myhome = subprocess.check_output(["df", "-P", myhomepath]).decode() else: myhome = "" for dev in device_list: if dev.path in myhome: continue # I left all of the below here but commented out to see some use cases # isbusy = in use/mounted. Needs to flag if 'yes' to prompt user to umount # isbusy = dev.busy # path gives /dev/sda or something similar # myname = dev.path # Hard drives measure themselves assuming kilo=1000, mega=1mil, etc # limiter = 1000 # Some disk size calculations # byte_size = dev.length * dev.sectorSize # megabyte_size = byte_size / (limiter * limiter) # gigabyte_size = megabyte_size / limiter # print(byte_size) # print(dev.length) # Must create disk object to drill down # Skip cd drive, special devices like LUKS and LVM and # RPMB (Replay Protected Memory Block) disk_obj = None rpmb = (dev.path.startswith("/dev/mmcblk") and dev.path.endswith("rpmb")) exclude = (dev.path.startswith("/dev/sr") or dev.path.startswith("/dev/mapper")) if not rpmb and not exclude: try: disk_obj = parted.Disk(dev) result = OK except parted.DiskLabelException: # logging.warning('Unrecognised disk label in device %s.', dev.path) result = UNRECOGNISED_DISK_LABEL except Exception as ex: template = "Cannot get devices information. An exception of type {0} occured. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) logging.error(message) show.error(None, message) result = UNKNOWN_ERROR finally: disk_dic[dev.path] = (disk_obj, result) return disk_dic
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 reload_partition_table(mia, operid, devpath): logger.d('reload_partition_table %s' % devpath) if CF.S.all_harddisks.has_key(devpath): dev = CF.S.all_harddisks[devpath][0] try: CF.S.all_harddisks[devpath] = (dev, parted.Disk(dev), None) except _ped.DiskLabelException: dltype = parted.diskType['msdos'] CF.S.all_harddisks[devpath] = (dev, parted.freshDisk(device=dev, ty=dltype), 'y') return 0
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 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 populate_treeview(self): if self.treeview_store is not None: self.treeview_store.clear() self.treeview_store = Gtk.TreeStore(str, str, str) oses = {} oses = bootinfo.get_os_dict() self.partitions = {} try: device_list = parted.getAllDevices() except: txt = _("pyparted3 not found!") logging.error(txt) show.fatal_error(txt) device_list = [] for dev in device_list: ## avoid cdrom and any raid, lvm volumes or encryptfs if not dev.path.startswith("/dev/sr") and \ not dev.path.startswith("/dev/mapper"): try: disk = parted.Disk(dev) # create list of partitions for this device (p.e. /dev/sda) partition_list = disk.partitions for p in partition_list: if p.type != pm.PARTITION_EXTENDED: ## Get filesystem fs_type = "" if p.fileSystem and p.fileSystem.type: fs_type = p.fileSystem.type if "swap" not in fs_type: if p.path in oses: row = [p.path, oses[p.path], fs_type] else: row = [p.path, _("unknown"), fs_type] self.treeview_store.append(None, row) self.partitions[p.path] = p except Exception as e: txt = _( "Unable to create list of partitions for alongside installation." ) logging.warning(txt) #show.warning(txt) # assign our new model to our treeview self.treeview.set_model(self.treeview_store) self.treeview.expand_all()
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
def main(argv): lst = set() for dev in filter(lambda d: d.type != parted.DEVICE_DM, parted.getAllDevices()): disk = parted.Disk(dev) for part in disk.partitions: lst.add("%s %s" % (part.path, int(part.getSize()))) lst = list(lst) lst.sort() for entry in lst: print entry
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 show_device(device): disk = parted.Disk(device) part = disk.getFirstPartition() print device print "%-12s %8s %16s %16s %16s %8s" %("Path","Fstype","Start","End","Length","Size") while part != None: geom = part.geometry if part.fileSystem: fstype = part.fileSystem.type if fstype.startswith("linux-swap"): fstype = "swap" else: fstype = "None" print "%-12s %8s %16d %16d %16d %8s" %(part.path,fstype,geom.start,geom.end,geom.length,size2str(part.getSize(unit='b'))) part = part.nextPartition()
def diskYenile(self): self.disklerAcilirKutu.clear() self.diskler = parted.getAllDevices() for disk in self.diskler: try: if parted.Disk(disk).type == "msdos" or parted.Disk( disk).type == "gpt": self.disklerAcilirKutu.addItem("{} {} GB ({})".format( disk.model, format(disk.getSize(unit="GB"), '.2f'), disk.path), userData=disk.path) except parted.DiskLabelException: disk = parted.freshDisk(disk, "msdos") # CDROM Aygıtları için try: disk.commit() except parted.IOException: pass else: disk = disk.device self.disklerAcilirKutu.addItem("{} {} GB ({})".format( disk.model, format(disk.getSize(unit="GB"), '.2f'), disk.path), userData=disk.path)
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 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 []