code cleanup

pull/155/head
Alin Trăistaru 7 years ago
parent 2691bab31f
commit 2a21a37ab4

@ -1,5 +1,4 @@
import os import os
import platform
import inspect import inspect
from . import config from . import config
@ -8,8 +7,8 @@ try:
except: except:
try: try:
from .colorama import init as colorama_init, Fore, Back, Style from .colorama import init as colorama_init, Fore, Back, Style
except: except Exception as e:
pass raise e
finally: finally:
try: try:
colorama_init(autoreset=True) colorama_init(autoreset=True)
@ -38,7 +37,8 @@ def fnCall():
Prints filename:line:function for parent and grandparent. Prints filename:line:function for parent and grandparent.
""" """
if not config.debug: return if not config.debug:
return
print(colors.OKGREEN + colors.BOLD + "=== DEBUG === | %s:%d:%s() called from %s:%d:%s()" % ( print(colors.OKGREEN + colors.BOLD + "=== DEBUG === | %s:%d:%s() called from %s:%d:%s()" % (
inspect.stack()[1][1].split(os.sep)[-1], inspect.stack()[1][1].split(os.sep)[-1],
@ -48,4 +48,3 @@ def fnCall():
inspect.stack()[2][2], inspect.stack()[2][2],
inspect.stack()[2][3], inspect.stack()[2][3],
)+colors.RESET) )+colors.RESET)

@ -7,7 +7,6 @@
# under the terms of GNU General Public License, v.2 or above # under the terms of GNU General Public License, v.2 or above
import os import os
import string
import platform import platform
import re import re
from .iso import * from .iso import *
@ -32,7 +31,7 @@ def distro(iso_cfg_ext_dir, iso_link):
if name.endswith(('.cfg', '.CFG', '.txt', '.TXT', '.lst')): if name.endswith(('.cfg', '.CFG', '.txt', '.TXT', '.lst')):
try: try:
# errors='ignore' is required as some files also contain non utf character # errors='ignore' is required as some files also contain non utf character
string = open(os.path.join(path, name), errors='ignore').read() string = open(os.path.join(path, name), errors='ignore').read()
except IOError: except IOError:
return "Read Error." return "Read Error."
else: else:
@ -143,15 +142,13 @@ def distro(iso_cfg_ext_dir, iso_link):
if distro: if distro:
return distro return distro
# FIXME: See the below comments. # FIXME: See the below comments.
''' # else:
else: # # FIXME: The idea of detecting as generic is to work like a unetbootin if other methods fails.
# FIXME: The idea of detecting as generic is to work like a unetbootin if other methods fails. # # This simply extracts distro to root of the USB and install syslinux on isolinux.bin directory.
# This simply extracts distro to root of the USB and install syslinux on isolinux.bin directory. # # All works fine but unable to boot the distro successfully. Also, see the generic section from
# All works fine but unable to boot the distro successfully. Also, see the generic section from # # syslinux, update_cfg and install_distro modules.
# syslinux, update_cfg and install_distro modules. # if self.isolinux_bin_exist():
if self.isolinux_bin_exist(): # return "generic"
return "generic"
'''
else: else:
return None return None

@ -243,17 +243,17 @@ def read_input_yes():
return False return False
def strings(filename, min=4): def strings(filename, _min=4):
with open(filename, errors="ignore") as f: with open(filename, errors="ignore") as f:
result = "" result = ""
for c in f.read(): for c in f.read():
if c in string.printable: if c in string.printable:
result += c result += c
continue continue
if len(result) >= min: if len(result) >= _min:
yield result yield result
result = "" result = ""
if len(result) >= min: # catch result at EOF if len(result) >= _min: # catch result at EOF
yield result yield result
@ -392,7 +392,7 @@ def write_to_file(filepath, text):
Simple function to write a text file Simple function to write a text file
:param filepath: Path to file :param filepath: Path to file
:param text: Text to be written on to file :param text: Text to be written on to file
:return: :return:
""" """
with open(filepath, 'w') as f: with open(filepath, 'w') as f:
f.write(text.strip()) f.write(text.strip())

@ -147,19 +147,16 @@ def grub_custom_menu(mbus_grub_cfg_path, distro):
if distro in ['sgrubd2', 'raw_iso']: if distro in ['sgrubd2', 'raw_iso']:
grub_raw_iso(mbus_grub_cfg_path) grub_raw_iso(mbus_grub_cfg_path)
''' # with open(mbus_grub_cfg_path, 'a') as f:
with open(mbus_grub_cfg_path, 'a') as f: # f.write("#start " + iso.iso_basename(config.image_path) + "\n")
f.write("#start " + iso.iso_basename(config.image_path) + "\n") # f.write(grub_raw_iso())
f.write(grub_raw_iso()) # f.write("#end " + iso.iso_basename(config.image_path) + "\n")
f.write("#end " + iso.iso_basename(config.image_path) + "\n") #
#
# elif iso_size_mb < 750.0:
elif iso_size_mb < 750.0: # grub_raw_iso(mbus_grub_cfg_path)
grub_raw_iso(mbus_grub_cfg_path)
'''
else: else:
return False return False
@ -207,10 +204,10 @@ def extract_kernel_line(search_text, match_line, isolinux_dir):
""" """
Function to check if kernel/linux line present in isolinux.cfg file is valid. Function to check if kernel/linux line present in isolinux.cfg file is valid.
If valid, then convert them in to grub accepted format If valid, then convert them in to grub accepted format
:param search_text: Type of text is to be searched. Typically kernel or linux :param search_text: Type of text is to be searched. Typically kernel or linux
:param match_line: Line containing kernel ot linux from isolinux supported .cfg files :param match_line: Line containing kernel ot linux from isolinux supported .cfg files
:param isolinux_dir: Path to isolinux directory of an ISO :param isolinux_dir: Path to isolinux directory of an ISO
:return: Valid grub2 accepted kernel/linux line after conversion. If nothing found return ''. :return: Valid grub2 accepted kernel/linux line after conversion. If nothing found return ''.
""" """
kernel_line = '' kernel_line = ''
@ -250,8 +247,8 @@ def extract_kernel_line(search_text, match_line, isolinux_dir):
def iso2grub2(iso_dir): def iso2grub2(iso_dir):
""" """
Function to convert syslinux configuration to grub2 accepted configuration format. Features implemented are similar Function to convert syslinux configuration to grub2 accepted configuration format. Features implemented are similar
to that of grub2 'loopback.cfg'. This 'loopback.cfg' file can be later on caled directly from grub2. The main to that of grub2 'loopback.cfg'. This 'loopback.cfg' file can be later on caled directly from grub2. The main
advantage of this function is to generate the 'loopback.cfg' file automatically without manual involvement. advantage of this function is to generate the 'loopback.cfg' file automatically without manual involvement.
:param iso_dir: Path to distro install directory for looping through '.cfg' files. :param iso_dir: Path to distro install directory for looping through '.cfg' files.
:param file_out: Path to 'loopback.cfg' file. By default it is set to root of distro install directory. :param file_out: Path to 'loopback.cfg' file. By default it is set to root of distro install directory.
:return: :return:
@ -308,7 +305,7 @@ def iso2grub2(iso_dir):
for _lines in kernel_text: for _lines in kernel_text:
kernel_line = extract_kernel_line(_lines[0][1], _lines[0][0], kernel_line = extract_kernel_line(_lines[0][1], _lines[0][0],
iso_bin_dir) iso_bin_dir)
if kernel_line is '': if kernel_line == '':
continue continue
else: else:
break break
@ -322,7 +319,7 @@ def iso2grub2(iso_dir):
for _lines in initrd_text: for _lines in initrd_text:
initrd_line = extract_kernel_line(_lines[0][1], _lines[0][0], initrd_line = extract_kernel_line(_lines[0][1], _lines[0][0],
iso_bin_dir) iso_bin_dir)
if initrd_line is '': if initrd_line == '':
continue continue
else: else:
break break

@ -12,9 +12,7 @@ import subprocess
import collections import collections
import platform import platform
import signal import signal
from PyQt5 import QtGui
from PyQt5 import QtWidgets from PyQt5 import QtWidgets
from PyQt5 import QtCore
from .gui.ui_multibootusb import Ui_MainWindow from .gui.ui_multibootusb import Ui_MainWindow
from .gen import * from .gen import *
from . import iso from . import iso
@ -28,15 +26,14 @@ if platform.system() == "Windows":
def dd_linux(): def dd_linux():
import time import time
input = "if=" + config.image_path _input = "if=" + config.image_path
in_file_size = float(os.path.getsize(config.image_path)) in_file_size = float(os.path.getsize(config.image_path))
output = "of=" + config.usb_disk _output = "of=" + config.usb_disk
os.system("umount " + config.usb_disk + "1") os.system("umount " + config.usb_disk + "1")
command = ['dd', input, output, "bs=1M", "oflag=sync"] command = ['dd', _input, _output, "bs=1M", "oflag=sync"]
log("Executing ==> " + " ".join(command)) log("Executing ==> " + " ".join(command))
dd_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) dd_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
# bar = progressbar.ProgressBar(redirect_stdout=True)
pbar = progressbar.ProgressBar( pbar = progressbar.ProgressBar(
maxval=100, maxval=100,
widgets=[ widgets=[
@ -73,10 +70,10 @@ def dd_win():
windd = resource_path(os.path.join("data", "tools", "dd", "dd.exe")) windd = resource_path(os.path.join("data", "tools", "dd", "dd.exe"))
if os.path.exists(resource_path(os.path.join("data", "tools", "dd", "dd.exe"))): if os.path.exists(resource_path(os.path.join("data", "tools", "dd", "dd.exe"))):
log("dd exist") log("dd exist")
input = "if=" + config.image_path _input = "if=" + config.image_path
in_file_size = float(os.path.getsize(config.image_path) / 1024 / 1024) in_file_size = float(os.path.getsize(config.image_path) / 1024 / 1024)
output = "of=\\\.\\" + config.usb_disk _output = "of=\\\.\\" + config.usb_disk
command = [windd, input, output, "bs=1M", "--progress"] command = [windd, _input, _output, "bs=1M", "--progress"]
log("Executing ==> " + " ".join(command)) log("Executing ==> " + " ".join(command))
dd_process = subprocess.Popen(command, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, dd_process = subprocess.Popen(command, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
shell=False) shell=False)
@ -127,19 +124,8 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
self.ui.imager_iso_size.setText("ISO Size: " + self.iso_size + " MB") self.ui.imager_iso_size.setText("ISO Size: " + self.iso_size + " MB")
log("ISO Size is " + self.iso_size + " MB") log("ISO Size is " + self.iso_size + " MB")
# def onImagerComboChange(self): @staticmethod
# config.imager_usb_disk = str(self.ui.comboBox_2.currentText()) def imager_list_usb(partition=1):
# if bool(config.imager_usb_disk):
# self.ui.imager_disk_label.setText(self.imager_usb_detail(config.imager_usb_disk, partition=0).usb_type)
# self.ui.imager_total_size.setText(usb.bytes2human(int(self.imager_usb_detail(config.imager_usb_disk, partition=0).total_size)))
#
# if platform.system() == "Linux":
# self.ui.label_imager_uuid.setText("Disk Model:")
# self.ui.imager_uuid.setText(str(self.imager_usb_detail(config.imager_usb_disk, partition=0).model))
# else:
# self.ui.imager_uuid.setText(self.imager_usb_detail(config.imager_usb_disk, partition=0).model)
def imager_list_usb(self, partition=1):
""" """
Function to detect whole USB disk. It uses lsblk package on Linux. Function to detect whole USB disk. It uses lsblk package on Linux.
:param partition: What to return. By default partition is set. :param partition: What to return. By default partition is set.
@ -148,7 +134,7 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
disk = [] disk = []
if platform.system() == "Linux": if platform.system() == "Linux":
output = subprocess.check_output("lsblk -i", shell=True) output = subprocess.check_output("lsblk -i", shell=True)
if not partition == 1: if partition != 1:
for line in output.splitlines(): for line in output.splitlines():
line = line.split() line = line.split()
if (line[2].strip()) == b'1' and (line[5].strip()) == b'disk': if (line[2].strip()) == b'1' and (line[5].strip()) == b'disk':
@ -159,15 +145,15 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
if (line[2].strip()) == b'1' and line[5].strip() == b'part': if (line[2].strip()) == b'1' and line[5].strip() == b'part':
disk.append(str("/dev/" + str(line[0].strip()[2:]))) disk.append(str("/dev/" + str(line[0].strip()[2:])))
else: else:
if partition == 1 or not partition == 1: oFS = win32com.client.Dispatch("Scripting.FileSystemObject")
oFS = win32com.client.Dispatch("Scripting.FileSystemObject") oDrives = oFS.Drives
oDrives = oFS.Drives for drive in oDrives:
for drive in oDrives: if drive.DriveType == 1 and drive.IsReady:
if drive.DriveType == 1 and drive.IsReady: disk.append(drive)
disk.append(drive)
return disk return disk
def imager_usb_detail(self, usb_disk, partition=1): @staticmethod
def imager_usb_detail(usb_disk, partition=1):
""" """
Function to detect details of USB disk using lsblk Function to detect details of USB disk using lsblk
:param usb_disk: path to usb disk :param usb_disk: path to usb disk
@ -180,7 +166,7 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow):
output = subprocess.check_output("lsblk -ib " + usb_disk, shell=True) output = subprocess.check_output("lsblk -ib " + usb_disk, shell=True)
for line in output.splitlines(): for line in output.splitlines():
line = line.split() line = line.split()
if not partition == 1: if partition != 1:
if line[2].strip() == b'1' and line[5].strip() == b'disk': if line[2].strip() == b'1' and line[5].strip() == b'disk':
total_size = line[3] total_size = line[3]
if not total_size: if not total_size:

@ -10,7 +10,6 @@
import sys import sys
import os import os
import string import string
import platform
import re import re
from .gen import * from .gen import *
from .isodump3 import ISO9660 from .isodump3 import ISO9660
@ -56,11 +55,7 @@ def isolinux_bin_exist(iso_link):
""" """
if os.path.exists(iso_link): if os.path.exists(iso_link):
iso_file_list = _7zip.list_iso(iso_link) iso_file_list = _7zip.list_iso(iso_link)
if any("isolinux.bin" in s.lower() for s in iso_file_list): return bool(any("isolinux.bin" in s.lower() for s in iso_file_list))
return True
else:
return False
def iso_size(iso_link): def iso_size(iso_link):
@ -74,10 +69,7 @@ def is_bootable(iso_link):
""" """
iso9660fs = ISO9660(iso_link) iso9660fs = ISO9660(iso_link)
isBootable = iso9660fs.checkISOBootable() isBootable = iso9660fs.checkISOBootable()
if isBootable: return bool(isBootable)
return True
else:
return False
def isolinux_bin_dir(iso_link): def isolinux_bin_dir(iso_link):
@ -162,14 +154,14 @@ def isolinux_version(isolinux_bin_path):
return str(number) return str(number)
def iso_extract_file(iso_link, dest_dir, filter): def iso_extract_file(iso_link, dest_dir, _filter):
""" """
Extract the specific file(s) from an ISO Extract the specific file(s) from an ISO
:param dest_dir: Path to destination directory. :param dest_dir: Path to destination directory.
:param filter: Filter to extract particular file(s) :param filter: Filter to extract particular file(s)
:return: Extract file(s) to destination. :return: Extract file(s) to destination.
""" """
_7zip.extract_iso(iso_link, dest_dir, filter) _7zip.extract_iso(iso_link, dest_dir, _filter)
def extract_cfg_file(iso_link): def extract_cfg_file(iso_link):
@ -232,4 +224,3 @@ if __name__ == '__main__':
iso_extract_full(iso_path, 'test') iso_extract_full(iso_path, 'test')
iso_extract_file(iso_path, 'test', 'isolinux.bin') iso_extract_file(iso_path, 'test', 'isolinux.bin')
log(isolinux_version(test_iso_bin_path)) log(isolinux_version(test_iso_bin_path))

@ -6,7 +6,6 @@
# Licence: This file is a part of multibootusb package. You can redistribute it or modify # Licence: This file is a part of multibootusb package. You can redistribute it or modify
# under the terms of GNU General Public License, v.2 or above # under the terms of GNU General Public License, v.2 or above
import sys
import os import os
import platform import platform
import tarfile import tarfile
@ -92,7 +91,7 @@ def create_persistence():
if subprocess.call(persistence_dd_cmd, shell=True) == 0: if subprocess.call(persistence_dd_cmd, shell=True) == 0:
gen.log("\nSuccessfully created persistence file...\n") gen.log("\nSuccessfully created persistence file...\n")
if not config.distro == 'fedora': if config.distro != 'fedora':
gen.log('Applying filesystem to persistence file...') gen.log('Applying filesystem to persistence file...')
config.status_text = 'Applying filesystem to persistence file. Please wait...' config.status_text = 'Applying filesystem to persistence file. Please wait...'
gen.log('Executing ==> ' + persistence_mkfs_cmd) gen.log('Executing ==> ' + persistence_mkfs_cmd)
@ -111,4 +110,3 @@ def extract_file(file_path, install_dir):
tar = tarfile.open(file_path, "r:bz2") tar = tarfile.open(file_path, "r:bz2")
tar.extractall(install_dir) tar.extractall(install_dir)
tar.close() tar.close()

@ -11,7 +11,6 @@
import os import os
import subprocess import subprocess
import platform import platform
from .admin import adminCmd
from PyQt5 import QtWidgets from PyQt5 import QtWidgets
from .gui.ui_multibootusb import Ui_MainWindow from .gui.ui_multibootusb import Ui_MainWindow
from .gen import * from .gen import *
@ -27,7 +26,7 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
QtWidgets.QMainWindow.__init__(self) QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow() self.ui = Ui_MainWindow()
self.ui.setupUi(self) self.ui.setupUi(self)
def on_Qemu_Boot_iso_Click(self): def on_Qemu_Boot_iso_Click(self):
""" """
Main function to boot a selected ISO. Main function to boot a selected ISO.
@ -102,9 +101,7 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
cmd = qemu + ' -hda ' + qemu_usb_disk + ram + ' -vga std' cmd = qemu + ' -hda ' + qemu_usb_disk + ram + ' -vga std'
try: try:
log('Executing ==> ' + cmd) log('Executing ==> ' + cmd)
# adminCmd([qemu, '-hda', usb_disk[:-1], '-m', ram, '-vga std'], gui=True)
subprocess.Popen(cmd, shell=True) subprocess.Popen(cmd, shell=True)
# adminCmd(qemu_cmd, gui=True)
except: except:
QtWidgets.QMessageBox.information(self, 'Error...', 'Error booting USB\n\nUnable to start QEMU.') QtWidgets.QMessageBox.information(self, 'Error...', 'Error booting USB\n\nUnable to start QEMU.')
@ -133,8 +130,9 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
return None return None
else: else:
return selected_ram return selected_ram
def check_qemu_exist(self): @staticmethod
def check_qemu_exist():
""" """
Check if QEMU is available on host system. Check if QEMU is available on host system.
:return: path to QEMU program or None otherwise. :return: path to QEMU program or None otherwise.
@ -150,7 +148,7 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
elif platform.system() == "Windows": elif platform.system() == "Windows":
qemu = resource_path(os.path.join("data", "tools", "qemu", "qemu-system-x86_64.exe")) qemu = resource_path(os.path.join("data", "tools", "qemu", "qemu-system-x86_64.exe"))
log(qemu) log(qemu)
if qemu: if qemu:
log("QEMU: using " + qemu) log("QEMU: using " + qemu)
else: else:
@ -158,24 +156,21 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow):
return qemu return qemu
@staticmethod
def get_physical_disk_number(self, usb_disk): def get_physical_disk_number(usb_disk):
""" """
Get the physical disk number as detected ny Windows. Get the physical disk number as detected ny Windows.
:param usb_disk: USB disk (Like F:) :param usb_disk: USB disk (Like F:)
:return: Disk number. :return: Disk number.
""" """
import wmi import wmi
c = wmi.WMI () c = wmi.WMI()
for physical_disk in c.Win32_DiskDrive (): for physical_disk in c.Win32_DiskDrive():
for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"): for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"): for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
if logical_disk.Caption == usb_disk: if logical_disk.Caption == usb_disk:
""" # log physical_disk.Caption
log physical_disk.Caption # log partition.Caption
log partition.Caption # log logical_disk.Caption
log logical_disk.Caption
"""
log("Physical Device Number is " + partition.Caption[6:-14]) log("Physical Device Number is " + partition.Caption[6:-14])
return str(partition.Caption[6:-14]) return str(partition.Caption[6:-14])

@ -7,7 +7,6 @@
# under the terms of GNU General Public License, v.2 or above # under the terms of GNU General Public License, v.2 or above
import os import os
import sys
import subprocess import subprocess
import platform import platform
from .gen import * from .gen import *
@ -39,7 +38,7 @@ def set_boot_flag(usb_disk):
return False return False
def syslinux_default(usb_disk, version=4): def syslinux_default(usb_disk):
""" """
Install Syslinux of a selected drive Install Syslinux of a selected drive
:param usb_disk: '/dev/sdx' on linux and 'E:' on Windows :param usb_disk: '/dev/sdx' on linux and 'E:' on Windows
@ -152,7 +151,7 @@ def syslinux_distro_dir(usb_disk, iso_link, distro):
if platform.system() == "Linux": if platform.system() == "Linux":
syslinux_path = os.path.join(multibootusb_host_dir(), "syslinux", "bin", "syslinux") + config.syslinux_version syslinux_path = os.path.join(multibootusb_host_dir(), "syslinux", "bin", "syslinux") + config.syslinux_version
if os.access(syslinux_path, os.X_OK) is False: if os.access(syslinux_path, os.X_OK) is False:
subprocess.call('chmod +x ' + syslinux_path, shell=True) == 0 subprocess.call('chmod +x ' + syslinux_path, shell=True)
sys_cmd = syslinux_path + option + quote(distro_syslinux_install_dir) + ' ' + usb_disk sys_cmd = syslinux_path + option + quote(distro_syslinux_install_dir) + ' ' + usb_disk
dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1' dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1'
log("Executing ==> " + sys_cmd) log("Executing ==> " + sys_cmd)
@ -194,7 +193,7 @@ def syslinux_distro_dir(usb_disk, iso_link, distro):
ext_cmd = syslinux_path + " --install " + distro_syslinux_install_dir ext_cmd = syslinux_path + " --install " + distro_syslinux_install_dir
dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1' dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1'
if os.access(syslinux_path, os.X_OK) is False: if os.access(syslinux_path, os.X_OK) is False:
subprocess.call('chmod +x ' + syslinux_path, shell=True) == 0 subprocess.call('chmod +x ' + syslinux_path, shell=True)
log("Executing ==> " + ext_cmd) log("Executing ==> " + ext_cmd)
if subprocess.call(ext_cmd, shell=True) == 0: if subprocess.call(ext_cmd, shell=True) == 0:
log("\nSyslinux install on distro directory is successful...\n") log("\nSyslinux install on distro directory is successful...\n")

@ -11,7 +11,8 @@ __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
# from __future__ import print_function # from __future__ import print_function
import os, re import os
import re
def node_mountpoint(node): def node_mountpoint(node):
@ -133,16 +134,6 @@ class UDisks2(object):
def mount(self, device_node_path): def mount(self, device_node_path):
d = self.device(device_node_path) d = self.device(device_node_path)
# euid = os.environ['SUDO_UID']
# egid = os.environ['SUDO_GID']
#
# if euid and egid:
# user, group = int(euid), int(egid)
# else:
# user, group = os.getuid(), os.getgid()
#
# mount_options = ['rw', 'noexec', 'nosuid', 'nodev', 'uid=%d' % user, 'gid=%d' % group]
mount_options = ['rw', 'noexec', 'nosuid', 'nodev'] mount_options = ['rw', 'noexec', 'nosuid', 'nodev']
try: try:
@ -158,8 +149,8 @@ class UDisks2(object):
mp = node_mountpoint(str(device_node_path)) mp = node_mountpoint(str(device_node_path))
if mp is None: if mp is None:
raise raise
finally:
return mp return mp
def unmount(self, device_node_path): def unmount(self, device_node_path):
d = self.device(device_node_path) d = self.device(device_node_path)

@ -84,7 +84,7 @@ def disk_usage(mount_path):
raise NotImplementedError("Platform not supported.") raise NotImplementedError("Platform not supported.")
def list_devices(partition=1, fixed=False): def list_devices(fixed=False):
""" """
List inserted USB devices. List inserted USB devices.
:return: USB devices as list. :return: USB devices as list.
@ -97,7 +97,7 @@ def list_devices(partition=1, fixed=False):
try: try:
import pyudev import pyudev
except Exception as e: except Exception as e:
gen.log('Pydev is not installed on host system. Using the inbuilt one.') gen.log('PyUdev is not installed on host system, using built-in.')
from . import pyudev from . import pyudev
context = pyudev.Context() context = pyudev.Context()
@ -209,12 +209,9 @@ def details_udev(usb_disk_part):
import pyudev import pyudev
except: except:
from . import pyudev from . import pyudev
""" # Try with PyUdev to get the details of USB disks.
Try with PyUdev to get the details of USB disks. # This is the easiest and reliable method to find USB details.
This is the easiest and reliable method to find USB details. # Also, it is a standalone package and no dependencies are required.
Also, it is a standalone package and no dependencies are required.
"""
# gen.log "Using PyUdev for detecting USB details..."
context = pyudev.Context() context = pyudev.Context()
try: try:
device = pyudev.Device.from_device_file(context, usb_disk_part) device = pyudev.Device.from_device_file(context, usb_disk_part)
@ -280,7 +277,7 @@ def details_udisks2(usb_disk_part):
device = bd.Get('org.freedesktop.UDisks2.Block', 'Device', dbus_interface='org.freedesktop.DBus.Properties') device = bd.Get('org.freedesktop.UDisks2.Block', 'Device', dbus_interface='org.freedesktop.DBus.Properties')
device = bytearray(device).replace(b'\x00', b'').decode('utf-8') device = bytearray(device).replace(b'\x00', b'').decode('utf-8')
uuid = bd.Get('org.freedesktop.UDisks2.Block', 'IdUUID', dbus_interface='org.freedesktop.DBus.Properties') uuid = bd.Get('org.freedesktop.UDisks2.Block', 'IdUUID', dbus_interface='org.freedesktop.DBus.Properties')
file_system = bd.Get('org.freedesktop.UDisks2.Block', 'IdType', dbus_interface='org.freedesktop.DBus.Properties') file_system = bd.Get('org.freedesktop.UDisks2.Block', 'IdType', dbus_interface='org.freedesktop.DBus.Properties')
mount_point = bd.Get('org.freedesktop.UDisks2.Filesystem', 'MountPoints', dbus_interface='org.freedesktop.DBus.Properties') mount_point = bd.Get('org.freedesktop.UDisks2.Filesystem', 'MountPoints', dbus_interface='org.freedesktop.DBus.Properties')
if mount_point: if mount_point:
# mount_point = str(bytearray(mount_point[0]).decode('utf-8').replace(b'\x00', b'')) # mount_point = str(bytearray(mount_point[0]).decode('utf-8').replace(b'\x00', b''))
@ -367,18 +364,17 @@ def win_disk_details(disk_drive):
size_total = shutil.disk_usage(mount_point)[0] size_total = shutil.disk_usage(mount_point)[0]
size_used = shutil.disk_usage(mount_point)[1] size_used = shutil.disk_usage(mount_point)[1]
size_free = shutil.disk_usage(mount_point)[2] size_free = shutil.disk_usage(mount_point)[2]
'''
# The below code works only from vista and above. I have removed it as many people reported that the software # The below code works only from vista and above. I have removed it as many people reported that the software
# was not working under windows xp. Even then, it is significantly slow if 'All Drives' option is checked. # was not working under windows xp. Even then, it is significantly slow if 'All Drives' option is checked.
# Removing the code doesn't affect the functionality as it is only used to find vendor id and model of the drive. # Removing the code doesn't affect the functionality as it is only used to find vendor id and model of the drive.
c = wmi.WMI() # c = wmi.WMI()
for physical_disk in c.Win32_DiskDrive(InterfaceType="USB"): # for physical_disk in c.Win32_DiskDrive(InterfaceType="USB"):
for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"): # for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators("Win32_LogicalDiskToPartition"): # for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
if logical_disk.Caption == disk_drive: # if logical_disk.Caption == disk_drive:
vendor = (physical_disk.PNPDeviceID.split('&VEN_'))[1].split('&PROD_')[0] # vendor = (physical_disk.PNPDeviceID.split('&VEN_'))[1].split('&PROD_')[0]
model = (physical_disk.PNPDeviceID.split('&PROD_'))[1].split('&REV_')[0] # model = (physical_disk.PNPDeviceID.split('&PROD_'))[1].split('&REV_')[0]
'''
return {'uuid': uuid, 'file_system': file_system, 'label': label, 'mount_point': mount_point, return {'uuid': uuid, 'file_system': file_system, 'label': label, 'mount_point': mount_point,
'size_total': size_total, 'size_used': size_used, 'size_free': size_free, 'size_total': size_total, 'size_used': size_used, 'size_free': size_free,

Loading…
Cancel
Save