def __init__(self, window): Page.__init__(self, window, Gtk.Orientation.VERTICAL) self.list = Gtk.ListBox() self.pack_start(self.list, True, True, 5) self.devices = [] for device in parted.getAllDevices(): self.devices.append(device.path) row = Gtk.HBox() row.add(Gtk.Label("{}: {}".format(device.path, device.model))) row.add( Gtk.Label("{} GB".format( int((device.length * device.sectorSize) / (1000 * 1000 * 1000))))) self.list.add(row) self.buttons = Gtk.HButtonBox() self.pack_start(self.buttons, False, False, 5) self.back_button = Gtk.Button(label="Back") self.back_button.connect("clicked", self.on_back_clicked) self.buttons.pack_start(self.back_button, True, False, 5) self.continue_button = Gtk.Button(label="Continue") self.continue_button.connect("clicked", self.on_continue_clicked) self.buttons.pack_start(self.continue_button, True, False, 5)
def get_devices(): device_list = parted.getAllDevices() disk_dic = {} for dev in device_list: #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 if not dev.path.startswith("/dev/sr"): try: diskob = parted.Disk(dev) disk_dic[dev.path] = diskob except Exception as e: print(e) disk_dic[dev.path] = None return disk_dic
def populate_devices(self): """ Fill list with devices """ with misc.raised_privileges() as __: device_list = parted.getAllDevices() self.device_store.remove_all() self.devices = {} self.bootloader_device_entry.remove_all() self.bootloader_devices.clear() 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"): # hard drives measure themselves assuming kilo=1000, mega=1mil, etc size_in_gigabytes = int( (dev.length * dev.sectorSize) / 1000000000) line = '{0} [{1} GB] ({2})' line = line.format(dev.model, size_in_gigabytes, dev.path) self.device_store.append_text(line) self.devices[line] = dev.path self.bootloader_device_entry.append_text(line) self.bootloader_devices[line] = dev.path logging.debug(line) self.select_first_combobox_item(self.device_store) self.select_first_combobox_item(self.bootloader_device_entry)
def main(): # Get EBS volume Id try: volumeId = str(sys.argv[1]) except IndexError: print "Provide an EBS volume ID to attach i.e. vol-cc789ea5" sys.exit(1) # Get instance ID instanceId = urllib2.urlopen("http://169.254.169.254/latest/meta-data/instance-id").read() # Get region region = urllib2.urlopen("http://169.254.169.254/latest/meta-data/placement/availability-zone").read() region = region[:-1] # Generate a list of system paths minus the root path paths = [convert_dev(device.path) for device in parted.getAllDevices()] # List of possible block devices blockDevices = ['/dev/sdb', '/dev/sdc', '/dev/sdd', '/dev/sde', '/dev/sdf', '/dev/sdg', '/dev/sdh', '/dev/sdi','/dev/sdj', '/dev/sdk', '/dev/sdl', '/dev/sdm', '/dev/sdn', '/dev/sdo', '/dev/sdp', '/dev/sdq', '/dev/sdr', '/dev/sds', '/dev/sdt', '/dev/sdu', '/dev/sdv', '/dev/sdw', '/dev/sdx', '/dev/sdy', '/dev/sdz'] # List of available block devices after removing currently used block devices availableDevices = [a for a in blockDevices if a not in paths] # Parse configuration file to read proxy settings config = ConfigParser.RawConfigParser() config.read('/etc/boto.cfg') proxy_config = Config() if config.has_option('Boto', 'proxy') and config.has_option('Boto', 'proxy_port'): proxy = config.get('Boto', 'proxy') proxy_port = config.get('Boto', 'proxy_port') proxy_config = Config(proxies={'https': "{0}:{1}".format(proxy, proxy_port)}) # Connect to AWS using boto ec2 = boto3.client('ec2', region_name=region, config=proxy_config) # Attach the volume dev = availableDevices[0] response = ec2.attach_volume(VolumeId=volumeId, InstanceId=instanceId, Device=dev) # Poll for volume to attach state = response.get("State") x = 0 while state != "attached": if x == 36: print "Volume %s failed to mount in 180 seconds." % volumeId exit(1) if state in ["busy" or "detached"]: print "Volume %s in bad state %s" % (volumeId, state) exit(1) print "Volume %s in state %s ... waiting to be 'attached'" % (volumeId, state) time.sleep(5) x += 1 try: state = ec2.describe_volumes(VolumeIds=[volumeId]).get('Volumes')[0].get('Attachments')[0].get('State') except IndexError as e: continue
def __init__(self): #Clear disk values disk.disks = [] disk.sd_disks = [] disk.size = [] disk.unit = [] disk.path_to_disk = {} disk.path_to_device = {} sector_size = [] #Probe for Devices disk.devices = parted.getAllDevices() # Add device paths for x in range(0, len(disk.devices)): disk.disks.append(disk.devices[x].path) #Dictionary, path: device for x in disk.disks: disk.path_to_device[x] = Device(x) disk.path_to_disk[x] = Disk(disk.path_to_device[x]) #Add other disk information for x in disk.disks: disk.sd_disks.append(x.replace("/dev/", "")) for x in range(0, len(disk.disks)): disk.size.append(float(str(disk.devices[x].length).replace("MB", ""))) for x in disk.disks: disk.unit.append("M")
def populate_devices(self): with misc.raised_privileges(): device_list = parted.getAllDevices() self.device_store.remove_all() self.devices = {} self.bootloader_device_entry.remove_all() self.bootloader_devices.clear() 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"): # hard drives measure themselves assuming kilo=1000, mega=1mil, etc size_in_gigabytes = int((dev.length * dev.sectorSize) / 1000000000) line = '{0} [{1} GB] ({2})'.format(dev.model, size_in_gigabytes, dev.path) self.device_store.append_text(line) self.devices[line] = dev.path self.bootloader_device_entry.append_text(line) self.bootloader_devices[line] = dev.path logging.debug(line) self.select_first_combobox_item(self.device_store) self.select_first_combobox_item(self.bootloader_device_entry)
def fill_device_list(self): """ Fill the partition list with all the data. """ # We will store our data model in 'device_list_store' if self.device_list_store is not None: self.device_list_store.clear() self.device_list_store = Gtk.TreeStore(bool, bool, bool, str, int, str, str) with misc.raised_privileges(): devices = parted.getAllDevices() self.get_ids() for dev in devices: # Skip cdrom, raid, lvm volumes or encryptfs if not dev.path.startswith("/dev/sr") and not dev.path.startswith("/dev/mapper"): size_in_gigabytes = int((dev.length * dev.sectorSize) / 1000000000) # Use check | Disk (sda) | Size(GB) | Name (device name) if dev.path.startswith("/dev/"): path = dev.path[len("/dev/") :] else: path = dev.path disk_id = self.ids.get(path, "") row = [False, True, True, path, size_in_gigabytes, dev.model, disk_id] self.device_list_store.append(None, row) self.device_list.set_model(self.device_list_store)
def fill_device_list(self): """ Fill the partition list with all the data. """ # We will store our data model in 'device_list_store' if self.device_list_store is not None: self.device_list_store.clear() self.device_list_store = Gtk.TreeStore(bool, bool, bool, str, int, str, str) with misc.raised_privileges() as __: devices = parted.getAllDevices() self.get_ids() for dev in devices: # Skip cdrom, raid, lvm volumes or encryptfs if (not dev.path.startswith("/dev/sr") and not dev.path.startswith("/dev/mapper")): size_in_gigabytes = int( (dev.length * dev.sectorSize) / 1000000000) # Use check | Disk (sda) | Size(GB) | Name (device name) if dev.path.startswith("/dev/"): path = dev.path[len("/dev/"):] else: path = dev.path disk_id = self.ids.get(path, "") row = [ False, True, True, path, size_in_gigabytes, dev.model, disk_id ] self.device_list_store.append(None, row) self.device_list.set_model(self.device_list_store)
def __init__(self, ebeveyn=None): super(BolumlemePencere, self).__init__(ebeveyn) self.ebeveyn = ebeveyn self.sistemDiski = ["", ""] self.takasDiski = ["", ""] self.seciliDisk = None self.diskler = parted.getAllDevices() disklerWidget = QWidget() disklerLayout = QHBoxLayout() self.disklerAcilirKutu = QComboBox() self.yenileButon = QPushButton(self.tr("Yenile")) self.yenileButon.pressed.connect(self.diskYenile) self.bolumListeKutu = QTreeWidget() self.bolumListeKutu.setColumnCount(4) self.bolumListeKutu.header().setStretchLastSection(False) self.bolumListeKutu.header().setSectionResizeMode( 0, QHeaderView.Stretch) self.bolumListeKutu.header().setSectionResizeMode( 1, QHeaderView.Stretch) self.bolumListeKutu.header().setSectionResizeMode( 2, QHeaderView.Stretch) self.bolumListeKutu.header().setSectionResizeMode( 3, QHeaderView.Stretch) self.bolumListeKutu.headerItem().setText(0, self.tr("Bölüm")) self.bolumListeKutu.headerItem().setText(1, self.tr("Kullanım Şekli")) self.bolumListeKutu.headerItem().setText(2, self.tr("Boyut")) self.bolumListeKutu.headerItem().setText(3, self.tr("Dosya Sistemi")) self.disklerAcilirKutu.currentIndexChanged.connect(self.diskDegisti) disklerLayout.addWidget(self.disklerAcilirKutu) disklerLayout.addWidget(self.yenileButon) disklerWidget.setLayout(disklerLayout) layout = QVBoxLayout() layout.addWidget(disklerWidget) layout.addWidget(self.bolumListeKutu) lejant = QLabel() lejant.setPixmap(QPixmap(":/gorseller/lejant.png")) lejant.setAlignment(Qt.AlignCenter) layout.addWidget(lejant) self.bolumListeKutu.itemClicked.connect(self.bolumSecildiFonk) self.bolumListeKutu.itemDoubleClicked.connect(self.bolumFormatSecFonk) opWidget = QWidget() opButonlar = QHBoxLayout() self.yeniBolumBtn = QPushButton(self.tr("Yeni Bölüm Ekle")) self.yeniBolumBtn.pressed.connect(self.bolumEkleFonk) self.bolumSilBtn = QPushButton(self.tr("Bölümü Sil")) self.bolumSilBtn.pressed.connect(self.bolumSilFonk) opButonlar.addWidget(self.yeniBolumBtn) opButonlar.addWidget(self.bolumSilBtn) opWidget.setLayout(opButonlar) layout.addWidget(opWidget) self.bolumSilBtn.setEnabled(False) self.setLayout(layout) self.diskYenile()
def updateDevices(self): self.devices = [dev for dev in parted.getAllDevices()] data = [[ d.path, d.model, str(d.length * 512 / 1024 / 1024 / 1024) + " Гб" ] for d in self.devices] self.model.setDevices(data) self.ui.devicesView.resizeColumnsToContents()
def show_devices(): """Prints a list of storage devices and some attributes.""" print("{:<15} {:<30} {:<}".format("Device Path", "Device Model", "Capacity (MB)")) for device in parted.getAllDevices(): print("{:<15} {:<30} {:<}".format(device.path, device.model, device.getSize()))
def get_devices(): """Code used by list-harddrives in anaconda.""" devices = parted.getAllDevices() devices = [d for d in devices if d.type != parted.DEVICE_DM and not d.path.startswith('/dev/sr')] for dev in devices: path = dev.path[5:] if dev.path.startswith('/dev/') else dev.path yield path, dev.getSize()
def __init__(self): self._disks = [] self._partitions = [] for device in parted.getAllDevices(): disk = parted.disk.Disk(device) self._disks.append(disk) for part in disk.partitions: self._partitions.append(part)
def get(id=None): devs, mps = [], {} fstab = get_fstab() # Get mount data for all devices with open("/etc/mtab", "r") as f: for x in f.readlines(): x = x.split() mps[x[0]] = x[1] # Get physical disks available for d in parted.getAllDevices(): try: parts = parted.Disk(d).getPrimaryPartitions() except: continue for p in parts: if p.path.split("/")[-1].startswith("loop"): continue try: fstype = parted.probeFileSystem(p.geometry) except: fstype = "Unknown" try: dev = DiskPartition(id=p.path.split("/")[-1], path=p.path, mountpoint=mps.get(p.path) or None, size=int(p.getSize("B")), fstype=fstype, enabled=p.path in fstab, crypt=crypto.is_luks(p.path)==0) if id == dev.id: return dev devs.append(dev) except: continue # Replace mount data for virtual disks with loopback id dd = losetup.get_loop_devices() for x in dd: try: s = dd[x].get_status() except: continue if "/dev/loop%s" % s.lo_number in mps: mps[s.lo_filename] = mps["/dev/loop%s" % s.lo_number] # Get virtual disks available for x in glob.glob(os.path.join(config.get("filesystems", "vdisk_dir"), "*")): if not x.endswith((".img", ".crypt")): continue dname = os.path.splitext(os.path.split(x)[1])[0] dev = VirtualDisk(id=dname, path=x, size=os.path.getsize(x), mountpoint=mps.get(x) or mps.get("/dev/mapper/%s" % dname) or None, enabled=x in fstab, crypt=x.endswith(".crypt")) if id == dev.id: return dev devs.append(dev) return devs if not id else None
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 get_dev_path_A1970(self): s = [] for dev in parted.getAllDevices(): name = "{}: {}".format(os.path.basename(dev.path), dev.model) size = int(dev.getSize()) #print name, size if not "multipath" in name: continue #print dev.path s.append(dev.path) return s
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)
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 lista_discos(self): ''' devuelve los discos que están conectados al equipo ''' l = [] dev = parted.getAllDevices() for d in dev: if not d.readOnly: l.append(d.path) return sorted(l)
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 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 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 find_device(device_path): """Return suitable device to install PlayOS on""" devices = parted.getAllDevices() device = None if device_path == None: # Use the largest available disk try: device = sorted(parted.getAllDevices(), key=lambda d: d.length * d.sectorSize, reverse=True)[0] except IndexError: pass else: try: device = next(device for device in devices if device.path == device_path) except StopIteration: pass if device == None: raise ValueError('No suitable device to install on found.') else: return device
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 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 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 populate_devices(self): device_list = parted.getAllDevices() self.device_store.remove_all() self.devices = {} for dev in device_list: # hard drives measure themselves assuming kilo=1000, mega=1mil, etc size_in_gigabytes = int((dev.length * dev.sectorSize) / 1000000000) line = '{0} [{1} GB] ({2})'.format(dev.model, size_in_gigabytes, dev.path) self.device_store.append_text(line) self.devices[line] = dev.path print(line) self.select_first_combobox_item(self.device_store)
def parted_print(disks,isjson = False,free = False): """Get all disks,if disks is not given.Return the json data if isjson is true.Get the stat of freepartition if free is true.""" # disks = {devpath:disks} if disks is None: disks = {} for dev in parted.getAllDevices(): try: disks[dev.path] = parted.disk.Disk(dev) except: disks[dev.path] = None continue if isjson: return print_disks_to_json_format(disks,free) else: print_disks(disks,free)
def print_devices(used_devices): output = [' Devices ', ''] for dev in sorted(parted.getAllDevices(), key=lambda x: x.path): output.append(dev.path + ' ' + dev.model + ' ' + human_number(dev.getSize(), 'MiB')) try: partitions = [] disk = parted.Disk(dev) for partition in disk.partitions: used = ' ' + used_devices.get(partition.path, '') + ' ' partitions.append([used, partition.path, human_number(partition.getLength() * partition.geometry.device.sectorSize)]) if partitions: output += pad(partitions) except parted.DiskLabelException: pass return output
def DevDisk(): disks = {} disks_tag = {} blacklist = ["mapper", "sr"] ##the device type not supported for dev in parted.getAllDevices(): if test(dev.path.split("/")[2], blacklist) is False: continue disks_tag[dev.path] = False try: disks[dev.path] = parted.disk.Disk(dev) except: if dev.getSize("TB") >= 2: ##larger than 2TiB disks[dev.path] = parted.freshDisk(dev, "gpt") else: disks[dev.path] = parted.freshDisk(dev, "msdos") continue return [disks, disks_tag]
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 cd drive and special devices like LUKS and LVM if not dev.path.startswith("/dev/sr") and not dev.path.startswith("/dev/mapper"): try: diskob = parted.Disk(dev) result = OK logging.info(_("Adding %s to disk_dic") % dev.path) except parted.DiskLabelException as err: logging.warning(_("Unrecognised disk label in device %s.") % dev.path) diskob = None result = UNRECOGNISED_DISK_LABEL except Exception as err: show.error((_("Exception: %s.\nFor more information take a look at /tmp/thus.log") % err)) diskob = None result = UNKNOWN_ERROR finally: disk_dic[dev.path] = (diskob, result) return disk_dic
def mount_devices(): partitions = [] for device in parted.getAllDevices(): disk = parted.disk.Disk(device) partitions.extend([(part.path, part.fileSystem.type if part.fileSystem else "", str(part.getSize())) for part in disk.partitions]) sizes = [0, 0, 0] for part in partitions: for member in [0, 1, 2]: if len(part[member]) > sizes[member]: sizes[member] = len(part[member]) #Printing for part in partitions: print " " + " ".join([part[member].ljust(sizes[member] + 2, " ") for member in (0, 1, 2)]) print "Enter device and mountpoint, divided by space" print "or type <Enter> to move on:" while True: command = raw_input("=> ") if command: device, path = command.split() for part in partitions: if part[0] == device: if part[1] in ("fat32", "fat16"): filesystem = "vfat" elif "swap" in part[1]: filesystem = "swap" else: filesystem = part[1] instance['mountpoints'].append({ 'path': path, 'device': device, 'type': filesystem, 'options': 'defaults', 'dump': 1 if path is '/' else 0, 'pass_value': 1 if path is '/' else 0 }) break else: break if instance['mountpoints']: for point in instance['mountpoints']: os.system("mount -t " + point['type'] + " " + point['device'] + " " + point['path'])
def populate_combobox_with_devices(self, combobox): device_list = parted.getAllDevices() combobox.remove_all() extended = 2 for dev in device_list: if not dev.path.startswith("/dev/sr"): 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 != extended: combobox.append_text(p.path) except Exception as e: print(e)
def get_devices(): disk_dic = {} devices = parted.getAllDevices() for device in devices: dev_path = device.path try: disk = parted.Disk(device) except: continue part_dict = {} for p in disk.partitions: part_path = p.path part_type = "unkown" if p.fileSystem: part_type = p.fileSystem.type if part_type == "fat32" or part_type == "fat16": part_dict[part_path] = {"type":part_type} disk_dic[dev_path] = {"partitions": part_dict} return disk_dic
def get_devices(): """ Returns the available partitions known to the kernel :return: a tuple, (/dev/sdX#, fs, size, name/ if applicable) or returns a tuple " ", " ", " ", " " if not run as root """ devices = ptd.getAllDevices() disks = [] drv_info = [] if len(devices) == 0: return [(" ", " ", " ", " ")] for device in devices: disks.append(ptd.Disk(device)) for disk in disks: parts = disk.partitions for part in parts: drv_info.append( (part.path, part.fileSystem.type, part.getSize(), part.name)) return drv_info
def populate_treeview(self): if self.treeview_store != None: self.treeview_store.clear() self.treeview_store = Gtk.TreeStore(str, str, str) oses = {} oses = bootinfo.get_os_dict() self.partitions = {} device_list = parted.getAllDevices() 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 file system 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: log.debug( _("In alongside install, can't create list of partitions" )) # assign our new model to our treeview self.treeview.set_model(self.treeview_store) self.treeview.expand_all()
def populate_devices(self): device_list = parted.getAllDevices() self.device_store.remove_all() self.devices = {} 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"): # hard drives measure themselves assuming kilo=1000, mega=1mil, etc size_in_gigabytes = int( (dev.length * dev.sectorSize) / 1000000000) line = '{0} [{1} GB] ({2})'.format(dev.model, size_in_gigabytes, dev.path) self.device_store.append_text(line) self.devices[line] = dev.path log.debug(line) self.select_first_combobox_item(self.device_store)
def populate_treeview(self): if self.treeview_store != None: self.treeview_store.clear() self.treeview_store = Gtk.TreeStore(str, str, str) oses = {} oses = bootinfo.get_os_dict() self.partitions = {} device_list = parted.getAllDevices() 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 file system 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: log.debug(_("In alongside install, can't create list of partitions")) # assign our new model to our treeview self.treeview.set_model(self.treeview_store) self.treeview.expand_all()
def print_devices(used_devices): output = [' Devices ', ''] for dev in sorted(parted.getAllDevices(), key=lambda x: x.path): output.append(dev.path + ' ' + dev.model + ' ' + human_number(dev.getSize(), 'MiB')) try: partitions = [] disk = parted.Disk(dev) for partition in disk.partitions: used = ' ' + used_devices.get(partition.path, '') + ' ' partitions.append([ used, partition.path, human_number(partition.getLength() * partition.geometry.device.sectorSize) ]) if partitions: output += pad(partitions) except parted.DiskLabelException: pass return output
def populate_combobox_with_devices(self, combobox): device_list = parted.getAllDevices() combobox.remove_all() extended = 2 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 != extended: combobox.append_text(p.path) except Exception as e: log.debug(_("In easy install, can't create list of partitions"))
def get_devices(): device_list = parted.getAllDevices() disk_dic = {} for dev in device_list: #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 diskob = parted.Disk(dev) disk_dic[dev.path] = diskob return disk_dic
def get_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 if not dev.path.startswith("/dev/sr") and not dev.path.startswith("/dev/mapper"): try: diskob = parted.Disk(dev) disk_dic[dev.path] = diskob except Exception as e: print(e) disk_dic[dev.path] = None return disk_dic
def diskPartitionList(self): self.treePartitionWidget.clear() for device in parted.getAllDevices(): top_item = QTreeWidgetItem(self.treePartitionWidget) top_item.setExpanded(True) top_item.setText(0, device.path) self.treePartitionWidget.addTopLevelItem(top_item) try: for partition in parted.Disk(device).partitions: try: part_item = QTreeWidgetItem(top_item) part_item.setText(0, partition.path) part_item.setText(1, partition.fileSystem.type) part_item.setText(2, "") part_item.setText(3, partition.name or "") part_item.setText(4, "✔") part_item.setText(5, mbToGB(partition.getSize())) except AttributeError: part_item = QTreeWidgetItem(top_item) part_item.setText(0, partition.path) part_item.setText(1, self.tr("Unknown")) part_item.setText(2, "") part_item.setText(3, partition.name or "") part_item.setText(4, "✔") part_item.setText(5, mbToGB(partition.getSize())) except parted.DiskLabelException as err: if is_efi(): disk = parted.freshDisk(device, "gpt") else: disk = parted.freshDisk(device, "msdos") try: disk.commit() except parted.IOException as err: print(err) self.diskPartitionList()
def initDisks(self): """ Inizializza le informazioni sui dischi """ print 'initDisks' # Inizializza le informazioni dei dischi devices = parted.getAllDevices() for dev in devices: try: disk = parted.Disk(dev) except: # Continua nonostante le eccezioni continue self.disks += [disk.device.path] for i in disk.partitions: if i.fileSystem: # Cerca la partizione di swap se esiste if string.find(i.fileSystem.type, "linux-swap") != -1: Glob.SWAP_PARTITION = i.path msg = "swap:%s" % Glob.SWAP_PARTITION logging.debug(msg) else: self.parts += [i.path]
def __get_devices(self): ''' Filter = only partitions with a valid filesystem ''' disk_dict = {} devices = parted.getAllDevices() for device in devices: dev_path = device.path dev_model = device.model dev_size = device.getSize('b') disk_dict[dev_path] = {"model": dev_model, "size": dev_size, "partitions": {}} try: disk = parted.Disk(device) except Exception as e: print e continue part_dict = {} for p in disk.partitions: if p.type not in (parted.PARTITION_NORMAL, parted.PARTITION_LOGICAL): continue part_path = p.path part_size =1024*1024*int(p.getSize('b')) part_type = "unknown" if p.fileSystem: part_type = p.fileSystem.type part_dict[part_path] = {"size": part_size, "type": part_type} disk_dict[dev_path]["partitions"] = part_dict return disk_dict
def get_dev_path(self): #s = "" #for dev in parted.getAllDevices(): # name = "{}: {}".format(os.path.basename(dev.path), dev.model) # size = int(dev.getSize()) # if size > 30000000: # st = len(dev.path) # if st == 29: # if not s: #get the first one if there are many # s= dev.path #print s #return s s = [] for dev in parted.getAllDevices(): name = "{}: {}".format(os.path.basename(dev.path), dev.model) size = int(dev.getSize()) #print name, size if not "multipath" in name: continue #print dev.path s.append(dev.path) return s
def get_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 if not dev.path.startswith("/dev/sr"): try: diskob = parted.Disk(dev) disk_dic[dev.path] = diskob except Exception as e: print(e) disk_dic[dev.path] = None return disk_dic
def getDevice(self): devices = parted.getAllDevices() self.chosen_device = getDevice(devices) try: self.chosen_device = int(self.chosen_device) - 1 if self.chosen_device < 0 or self.chosen_device > len(devices) - 1: self.valid = False self.code = 103 self.message = "Invalid number: out of range" return device = devices[self.chosen_device].path except ValueError: if not path.exists(self.chosen_device): self.valid = False self.code = 101 self.message = "Invalid file: file does not exist" return device = self.chosen_device self.device = parted.getDevice(device) self.disk = parted.newDisk(self.device) self.disk_file = open(self.device.path, "rb")
def diskYenile(self): self.disklerAcilirKutu.clear() self.diskler = parted.getAllDevices() for disk in self.diskler: try: if parted.Disk(disk).type == "msdos": 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 get_devices(): """Enumerates parted devies""" return parted.getAllDevices()
def setUp(self): self.devices = parted.getAllDevices()
except IndexError: print "Provide an EBS volume ID to attach i.e. vol-cc789ea5" sys.exit(1) # Get instance ID instanceId = urllib2.urlopen( "http://169.254.169.254/latest/meta-data/instance-id").read() # Get region region = urllib2.urlopen( "http://169.254.169.254/latest/meta-data/placement/availability-zone" ).read() region = region[:-1] # Generate a list of system paths minus the root path paths = [device.path for device in parted.getAllDevices()] # List of possible block devices blockDevices = [ '/dev/xvdb', '/dev/xvdc', '/dev/xvdd', '/dev/xvde', '/dev/xvdf', '/dev/xvdg', '/dev/xvdh', '/dev/xvdi', '/dev/xvdj', '/dev/xvdk', '/dev/xvdl', '/dev/xvdm', '/dev/xvdn', '/dev/xvdo', '/dev/xvdp', '/dev/xvdq', '/dev/xvdr', '/dev/xvds', '/dev/xvdt', '/dev/xvdu', '/dev/xvdv', '/dev/xvdw', '/dev/xvdx', '/dev/xvdy', '/dev/xvdz' ] # List of available block devices after removing currently used block devices availableDevices = [a for a in blockDevices if a not in paths] # Connect to AWS using boto ec2 = boto3.client('ec2', region_name=region)
import parted #This creates a list of all devices device_list = parted.getAllDevices() for dev in device_list: #AFAIK 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) #Must create disk object to drill down diskob = parted.Disk(dev) #Do not let user specify more than this number of primary partitions disk_max_pri = diskob.maxPrimaryPartitionCount #create list of partitions for this device(/dev/sda for example) partition_list = diskob.partitions for p in partition_list: #this is start sector, end sector, and length startbyte = p.geometry.start endbyte = p.geometry.end plength = p.geometry.length #lets calcule its size in something ppl understand psize = plength * dev.sectorSize #just calculating it in more sane formats #should probably add in something like
def dernierSecteur(self): """Récupéré le dernier secteur du disque""" return parted.getAllDevices()[-1].length
def partitionsFind(self,mounted=None,ttype=None,ssd=None,prefix="sd",minsize=5,maxsize=5000,devbusy=None,\ initialize=False,forceinitialize=False): """ looks for disks which are know to be data disks & are formatted ext4 return [[$partpath,$size,$free,$ssd]] @param ssd if None then ssd and other """ import parted import JumpScale.grid.osis import psutil result = [] mounteddevices = psutil.disk_partitions() def getpsutilpart(partname): for part in mounteddevices: if part.device == partname: return part return None for dev in parted.getAllDevices(): path = dev.path #ssize = dev.sectorSize; # size = (geom[0] * geom[1] * geom[2] * ssize) / 1000 / 1000 / 1000; # size2=dev.getSize() if devbusy == None or dev.busy == devbusy: if path.startswith("/dev/%s" % prefix): try: disk = parted.Disk(dev) partitions = disk.partitions except parted.DiskLabelException: partitions = list() for partition in partitions: disko = Disk() disko.model = dev.model disko.path = partition.path if disk.type != 'loop' else disk.device.path disko.size = round(partition.getSize(unit="mb"), 2) disko.free = 0 print "partition:%s %s" % (disko.path, disko.size) try: fs = parted.probeFileSystem(partition.geometry) except: fs = "unknown" disko.fs = fs partfound = getpsutilpart(disko.path) mountpoint = None if partfound == None and mounted <> True: mountpoint = "/mnt/tmp" cmd = "mount %s /mnt/tmp" % partition.path rcode, output = j.system.process.execute( cmd, ignoreErrorOutput=False, dieOnNonZeroExitCode=False, ) if rcode <> 0: #mount did not work mountpoint == None disko.mountpoint = None disko.mounted = False elif partfound: mountpoint = partfound.mountpoint disko.mountpoint = mountpoint disko.mounted = True pathssdcheck = "/sys/block/%s/queue/rotational" % dev.path.replace( "/dev/", "").strip() ssd0 = int( j.system.fs.fileGetContents(pathssdcheck)) == 0 disko.ssd = ssd0 result.append(disko) if mountpoint <> None: print "mountpoint:%s" % mountpoint size, used, free, percent = psutil.disk_usage( mountpoint) disko.free = disko.size * float(1 - percent / 100) size = disko.size / 1024 disko.free = int(disko.free) if (ttype == None or fs == ttype) and size > minsize and ( maxsize is None or size < maxsize): if ssd == None or disko.ssd == ssd: # print disko hrdpath = "%s/disk.hrd" % mountpoint if j.system.fs.exists(hrdpath): hrd = j.core.hrd.getHRD(hrdpath) partnr = hrd.getInt("diskinfo.partnr") if partnr == 0 or forceinitialize: j.system.fs.remove(hrdpath) if not j.system.fs.exists( hrdpath) and initialize: C = """ diskinfo.partnr= diskinfo.gid= diskinfo.nid= diskinfo.type= diskinfo.epoch= diskinfo.description= """ j.system.fs.writeFile(filename=hrdpath, contents=C) hrd = j.core.hrd.getHRD(hrdpath) hrd.set( "diskinfo.description", j.console.askString( "please give description for disk" )) hrd.set( "diskinfo.type", ",".join( j.console.askChoiceMultiple([ "BOOT", "CACHE", "TMP", "DATA", "OTHER" ]))) hrd.set("diskinfo.gid", j.application.whoAmI.gid) hrd.set("diskinfo.nid", j.application.whoAmI.nid) hrd.set("diskinfo.epoch", j.base.time.getTimeEpoch()) masterip = j.application.config.get( "grid.master.ip") client = j.core.osis.getClient( masterip, user="******") client_disk = j.core.osis.getClientForCategory( client, "system", "disk") disk = client_disk.new() for key, val in disko.__dict__.iteritems( ): disk.__dict__[key] = val disk.description = hrd.get( "diskinfo.description") disk.type = hrd.get( "diskinfo.type").split(",") disk.type.sort() disk.nid = j.application.whoAmI.nid disk.gid = j.application.whoAmI.gid guid, new, changed = client_disk.set( disk) disk = client_disk.get(guid) diskid = disk.id hrd.set("diskinfo.partnr", diskid) if j.system.fs.exists(hrdpath): # hrd=j.core.hrd.getHRD(hrdpath) disko.id = hrd.get("diskinfo.partnr") disko.type = hrd.get( "diskinfo.type").split(",") disko.type.sort() disko.description = hrd.get( "diskinfo.description") print "found disk:\n%s" % (disko) cmd = "umount /mnt/tmp" j.system.process.execute( cmd, dieOnNonZeroExitCode=False) if os.path.ismount("/mnt/tmp") == True: raise RuntimeError( "/mnt/tmp should not be mounted") return result
def disksList(): return parted.getAllDevices()
def get_device_list(): hd_list = filter(lambda d: d.type != parted.DEVICE_DM, parted.getAllDevices()) return hd_list