pull/314/head
shinji-s 6 years ago
commit 223bcc9276

@ -139,9 +139,10 @@ if __name__ == '__main__':
admin.runAsAdmin()
sys.exit(0)
try:
opts, args = getopt.getopt(sys.argv[1:], 'i:t:yvhcudrs',
['iso=', 'target=', 'yes', 'version', 'help', 'command', 'uninstall', 'debug',
'raw', 'syslinux'])
opts, args = getopt.getopt(
sys.argv[1:], 'i:t:yvhcudrsp:',
['iso=', 'target=', 'yes', 'version', 'help', 'command',
'uninstall', 'debug', 'raw', 'syslinux', 'persistence-size='])
except getopt.GetoptError:
usage()
sys.exit(2)
@ -158,7 +159,9 @@ if __name__ == '__main__':
else:
config.image_path = arg.split(',')
elif opt in ('-t', '--target'):
config.usb_disk = arg
# Convert to upper if windows drive name is given
config.usb_disk = len(arg)==2 and arg[0].isalpha() and arg[1]==':'\
and arg.upper() or arg
elif opt in ('-c', '--command'):
gui = False
elif opt in ('-u', '--uninstall'):
@ -171,6 +174,8 @@ if __name__ == '__main__':
config.cli_dd = True
elif opt in ('-s', '--syslinux'):
config.cli_syslinux = True
elif opt in ('-p', '--persistence-size'):
config.persistence = int(arg) * 1024 * 1024
else:
gui = True
#start_gui()

@ -61,7 +61,7 @@ def extract_iso(src, dst, pattern=None, suppress_out=True):
subprocess.call(_cmd, stdin=devnull, stdout=devnull, stderr=devnull, shell=True)
def list_iso(iso_link, suppress_out=True):
def list_iso(iso_link, suppress_out=True, expose_exception=False):
"""
List the content of ISO files. It does'nt work with non 'utf' characters (simply ignores them).
:param iso_link:Path to ISO link
@ -85,6 +85,8 @@ def list_iso(iso_link, suppress_out=True):
shell=True).decode('utf-8', 'ignore').splitlines()
except Exception as e:
gen.log(e)
if expose_exception:
raise
_cmd_out = ''
for line in _cmd_out:
if '...' in line:

@ -15,7 +15,7 @@ from .gen import *
from . import _7zip
def distro(iso_cfg_ext_dir, iso_link):
def distro(iso_cfg_ext_dir, iso_link, expose_exception=False):
"""
Detect if distro is supported by multibootusb.
:param iso_cfg_ext_dir: Directory where *.cfg files are extracted.
@ -23,7 +23,7 @@ def distro(iso_cfg_ext_dir, iso_link):
"""
# iso9660fs = ISO9660(iso_link)
# iso_file_list = iso9660fs.readDir("/")
iso_file_list = _7zip.list_iso(iso_link)
iso_file_list = _7zip.list_iso(iso_link, expose_exception=expose_exception)
if platform.system() == "Linux" or platform.system() == "Windows":
for path, subdirs, files in os.walk(iso_cfg_ext_dir):
for name in files:
@ -65,6 +65,9 @@ def distro(iso_cfg_ext_dir, iso_link):
return "solydx"
elif re.search(r'knoppix', string, re.I):
return "knoppix"
elif re.search(r'root=live:CDLABEL=CentOS',
string, re.I):
return 'centos' # centos-live
elif re.search(r'root=live:CDLABEL=', string, re.I) or re.search(r'root=live:LABEL=', string, re.I):
return "fedora"
elif re.search(r'redcore', string, re.I):
@ -115,6 +118,8 @@ def distro(iso_cfg_ext_dir, iso_link):
return "zenwalk"
elif re.search(r'ubuntu server', string, re.I):
return "ubuntu-server"
elif re.search(r'Install CentOS', string, re.I):
return "centos-install"
elif re.search(r'CentOS', string, re.I):
return "centos"
elif re.search(r'Trinity Rescue Kit', string, re.I):
@ -146,7 +151,7 @@ def distro(iso_cfg_ext_dir, iso_link):
elif re.search(r'BOOT_IMAGE=insert', string, re.I):
return 'insert'
distro = detect_iso_from_file_list(iso_link)
distro = detect_iso_from_file_list(iso_link, iso_file_list)
if distro:
return distro
@ -166,13 +171,12 @@ def distro(iso_cfg_ext_dir, iso_link):
return None
def detect_iso_from_file_list(iso_link):
def detect_iso_from_file_list(iso_link, iso_file_list):
"""
Fallback detection script from the content of an ISO.
:return: supported distro as string
"""
if os.path.exists(iso_link):
iso_file_list = _7zip.list_iso(iso_link)
if any("sources" in s.lower() for s in iso_file_list) and any("boot.wim" in s.lower() for s in iso_file_list):
return "Windows"
elif any("config.isoclient" in s.lower() for s in iso_file_list):

@ -27,20 +27,30 @@ def install_distro():
:return:
"""
usb_mount = config.usb_mount
install_dir = os.path.join(config.usb_mount, "multibootusb", iso_basename(config.image_path))
install_dir = os.path.join(config.usb_mount, "multibootusb",
iso_basename(config.image_path))
if not os.path.exists(os.path.join(usb_mount, "multibootusb")):
log("Copying multibootusb directory to " + usb_mount)
shutil.copytree(resource_path(os.path.join("data", "tools", "multibootusb")),
os.path.join(config.usb_mount, "multibootusb"))
shutil.copytree(
resource_path(os.path.join("data", "tools", "multibootusb")),
os.path.join(config.usb_mount, "multibootusb"))
if not os.path.exists(install_dir):
_iso_file_list = iso.iso_file_list(config.image_path)
os.makedirs(install_dir)
with open(os.path.join(install_dir, "multibootusb.cfg"), "w") as f:
f.write(config.distro)
with open(os.path.join(install_dir, "iso_file_list.cfg"), 'w') as f:
for file_path in iso.iso_file_list(config.image_path):
for file_path in _iso_file_list:
f.write(file_path + "\n")
else:
# This path is usually not taken.
with open(os.path.join(install_dir, "multibootusb.cfg"), "r") as f:
assert config.distro == f.read()
with open(os.path.join(install_dir, "iso_file_list.cfg"), 'r') as f:
_iso_file_list = [s.strip() for s in f.readlines()]
log("Installing " + iso_name(config.image_path) + " on " + install_dir)
# Some distros requires certain directories be at the root.
@ -105,6 +115,12 @@ def install_distro():
elif config.distro == 'insert':
iso_extract_full(config.image_path, install_dir)
relocator.move(('INSERT',))
elif config.distro == 'centos-install' and \
any(f=='.treeinfo' for f in _iso_file_list):
# DVD installer
iso.iso_extract_file(config.image_path, install_dir, '-xr-!Packages')
log("Copying the source iso file as is.")
copy_iso(config.image_path, install_dir)
else:
iso.iso_extract_full(config.image_path, install_dir)
@ -220,7 +236,7 @@ class DirectoryRelocator:
src = os.path.join(self.src_dir, dir_name)
dst = os.path.join(self.dst_dir, dir_name)
if os.path.exists(dst):
os.rmtree(dst)
shutil.rmtree(dst)
shutil.move(src, dst)
if __name__ == '__main__':

@ -77,45 +77,45 @@ def iso_install(iso_image):
:param iso_image: Path to ISO image
:return:
"""
if size_not_enough(iso_image, config.usb_disk) is True:
if os.path.exists(os.path.join(config.usb_mount, 'multibootusb',
iso.iso_basename(iso_image))):
log("'%s' is already installed. Skipping installation." %
iso.iso_basename(iso_image))
elif size_not_enough(iso_image, config.usb_disk) is True:
log(config.usb_disk + ' does not have enough space...')
else:
clean_iso_cfg_ext_dir(os.path.join(multibootusb_host_dir(), "iso_cfg_ext_dir")) # Need to be cleaned everytime
clean_iso_cfg_ext_dir( # Need to be cleaned everytime
os.path.join(multibootusb_host_dir(), "iso_cfg_ext_dir"))
extract_cfg_file(iso_image)
_distro = distro(iso_cfg_ext_dir(), iso_image)
if _distro is not None:
log('Initiating installation process for ' + iso.iso_basename(iso_image))
log('Initiating installation process for ' +
iso.iso_basename(iso_image))
log('Detected distro type is :' + _distro)
log('\nSelected ISO is :' + quote(iso_name(iso_image)))
log('Selected target device is :' + quote(config.usb_disk), '\n')
if config.yes is not True:
log('Please confirm the option.')
log('Y/y/Yes/yes/YES or N/n/No/no/NO')
if read_input_yes() is True:
config.distro = _distro
copy_mbusb_dir_usb(config.usb_disk)
install_progress()
syslinux_distro_dir(config.usb_disk, iso_image, _distro)
syslinux_default(config.usb_disk)
replace_grub_binary()
update_distro_cfg_files(iso_image, config.usb_disk, _distro)
log('Finished installing ' + iso.iso_basename(iso_image))
else:
if read_input_yes() is not True:
log('Not proceeding. User cancelled the operation.')
return
else:
log('Skipping user confirmation for ' + iso_image)
config.distro = _distro
copy_mbusb_dir_usb(config.usb_disk)
install_progress()
syslinux_distro_dir(config.usb_disk, iso_image, _distro)
syslinux_default(config.usb_disk)
replace_grub_binary()
update_distro_cfg_files(iso_image, config.usb_disk, _distro)
log('Finished installing ' + iso.iso_basename(iso_image))
config.distro = _distro
copy_mbusb_dir_usb(config.usb_disk)
install_progress()
syslinux_distro_dir(config.usb_disk, iso_image, _distro)
syslinux_default(config.usb_disk)
replace_grub_binary()
update_distro_cfg_files(iso_image, config.usb_disk, _distro,
config.persistence)
log('Finished installing ' + iso.iso_basename(iso_image))
else:
log('\n\nSorry ' + iso_name(iso_image) + ' is not supported at the moment.\n'
'Please report tissue at https://github.com/mbusb/multibootusb/issues\n')
log('\n\nSorry ' + iso_name(iso_image) +
' is not supported at the moment.\n'
'Please report an issue at '
'https://github.com/mbusb/multibootusb/issues\n')
def cli_uninstall_distro():
distro_list = install_distro_list()
@ -192,7 +192,8 @@ def cli_install_syslinux():
log('Operation cancelled by user. Exiting...')
sys.exit(2)
else:
log('\nSkipping user input and installing syslinux on ' + config.usb_disk)
log('\nSkipping user input and installing syslinux on ' +
config.usb_disk)
if syslinux.syslinux_default(config.usb_disk) is True:
log('Syslinux successfully installed on ' + config.usb_disk)
else:

@ -208,14 +208,16 @@ Are you SURE you want to enable it?",
def browse_iso(self):
if str(self.ui.image_path.text()):
self.ui.image_path.clear()
preference_file_path = os.path.join(multibootusb_host_dir(), "preference", "iso_dir.txt")
preference_file_path = os.path.join(multibootusb_host_dir(),
"preference", "iso_dir.txt")
dir_path = ''
if os.path.exists(preference_file_path):
dir_path = open(preference_file_path, 'r').read()
config.image_path = QtWidgets.QFileDialog.getOpenFileName(self, 'Select an iso...', dir_path,
'ISO Files (*.iso);; Zip Files(*.zip);; '
'Img Files(*.img);; All Files(*.*)')[0]
config.image_path = QtWidgets.QFileDialog.getOpenFileName(
self, 'Select an iso...', dir_path,
'ISO Files (*.iso);; Zip Files(*.zip);; '
'Img Files(*.img);; All Files(*.*)')[0]
if config.image_path:
# sanity checks
@ -223,20 +225,38 @@ Are you SURE you want to enable it?",
QtWidgets.QMessageBox.critical(
self,
"ISO Not readable",
"Sorry, the file \"{0}\" is not readable.".format(config.image_path)
"Sorry, the file \"{0}\" is not readable.".format(
config.image_path)
)
return
if iso_size(config.image_path) == 0:
QtWidgets.QMessageBox.critical(
self,
"ISO is an empty file",
"Sorry, the file \"{0}\" contains no data.".format(config.image_path)
"Sorry, the file \"{0}\" contains no data.".format(
config.image_path)
)
return
default_dir_path = os.path.dirname(config.image_path)
gen.write_to_file(preference_file_path, default_dir_path)
# Detect supported distro
try:
clean_iso_cfg_ext_dir( # Need to be cleaned.
os.path.join(multibootusb_host_dir(), "iso_cfg_ext_dir"))
extract_cfg_file(config.image_path)
config.distro = distro(iso_cfg_ext_dir(), config.image_path,
expose_exception=True)
except Exception as exc:
QtWidgets.QMessageBox.critical(
self,
"Failure to detect distro type",
'Sorry, failed in examining "{0}" to detect distro type '
'due to the following reason.\n\n"{1}".'
.format(config.image_path, exc)
)
return
if platform.system() == "Windows":
if "/" in config.image_path:
config.image_path = config.image_path.strip().replace("/", "\\")
@ -248,9 +268,6 @@ Are you SURE you want to enable it?",
self.ui.label_image_bootable_value.setVisible(True)
if os.path.exists(config.image_path):
clean_iso_cfg_ext_dir(os.path.join(multibootusb_host_dir(), "iso_cfg_ext_dir")) # Need to be cleaned.
extract_cfg_file(config.image_path)
config.distro = distro(iso_cfg_ext_dir(), config.image_path) # Detect supported distro
self.ui.label_image_type_value.setText(str(config.distro))
self.ui.label_image_type_value.setVisible(True)
if config.distro:
@ -263,7 +280,8 @@ Are you SURE you want to enable it?",
log('Persistence Max Size: ' + str(bytes2human(per_max_size)))
else:
config.persistence_available = False
log('Persistence is not available for ' + iso_name(config.image_path))
log('Persistence support is not available for '
+ iso_name(config.image_path))
self.ui_update_persistence()
else:
@ -330,7 +348,8 @@ Are you SURE you want to enable it?",
syslinux_distro_dir(config.usb_disk, config.image_path, config.distro)
syslinux_default(config.usb_disk)
replace_grub_binary()
update_distro_cfg_files(config.image_path, config.usb_disk, config.distro, config.persistence)
update_distro_cfg_files(config.image_path, config.usb_disk,
config.distro, config.persistence)
self.update_list_box(config.usb_disk)
if sys.platform.startswith("linux"):
self.ui.statusbar.showMessage("Status: Sync is in progress...")
@ -453,16 +472,23 @@ Are you SURE you want to enable it?",
QtWidgets.QMessageBox.information(self, 'No selection.', 'Please select a distro from the list.')
self.ui_enable_controls()
else:
config.uninstall_distro_dir_name = str(self.ui.installed_distros.currentItem().text()).strip()
reply = QtWidgets.QMessageBox.question(self, "Review selection...",
"Are you sure to uninstall " + config.uninstall_distro_dir_name,
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No)
config.uninstall_distro_dir_name = str(
self.ui.installed_distros.currentItem().text()).strip()
reply = QtWidgets.QMessageBox.question(
self, "Review selection...",
"Are you sure to uninstall " + config.uninstall_distro_dir_name,
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.Yes:
if not os.path.exists(os.path.join(config.usb_mount, 'multibootusb', config.uninstall_distro_dir_name)):
log("Distro install directory not found. Just updating syslinux.cfg file.")
update_sys_cfg_file()
if not os.path.exists(
os.path.join(config.usb_mount, 'multibootusb',
config.uninstall_distro_dir_name)):
log("Distro install directory not found. "
"Just updating syslinux.cfg and grub.cfg.")
update_sys_cfg_file(config.uninstall_distro_dir_name)
update_grub_cfg_file(config.uninstall_distro_dir_name)
self.uninstall_sys_file_update()
# self.uninstall.update_sys_cfg_file()
self.ui_enable_controls()
else:
@ -475,7 +501,10 @@ Are you SURE you want to enable it?",
Function to remove and update uninstall distro text.
:return:
"""
update_sys_cfg_file()
# This function is already called from 'do_uninstall_distro()'
# update_sys_cfg_file(config.uninstall_distro_dir_name)
self.update_list_box(config.usb_mount)
if sys.platform.startswith("linux"):
self.ui.statusbar.showMessage("Status: Sync in progress...")

@ -77,6 +77,7 @@ def contains_any_token(*tokens):
def contains_key(key):
assert type(key)==str
assert key[-1:] == '='
return lambda starter, params: any(x.startswith(key) for x in params)
def contains_all_keys(*keys):

@ -48,7 +48,7 @@ def persistence_distro(distro, iso_link):
# iso_size = iso.iso_size(iso_link)
if distro in ["ubuntu", "debian", "debian-install", "fedora"]:
if distro in ["ubuntu", "debian", "debian-install", "fedora", "centos"]:
gen.log("Persistence option is available.")
return distro
else:
@ -162,6 +162,10 @@ creator_dict = {
create_persistence_using_mkfs,
lambda C: (os.path.join(
'LiveOS', 'overlay-%s-%s' % (C.usb_label, C.usb_uuid)),)),
'centos' : (
create_persistence_using_mkfs,
lambda C: (os.path.join(
'LiveOS', 'overlay-%s-%s' % (C.usb_label, C.usb_uuid)),)),
}
def detect_missing_tools(distro):

@ -35,21 +35,18 @@ def install_distro_list():
return None
def unin_distro():
usb_details = details(config.usb_disk)
usb_mount = usb_details['mount_point']
config.uninstall_distro_dir_name = config.uninstall_distro_dir_name.replace('\n', '')
gen.log(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name, "multibootusb.cfg"))
if os.path.exists(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name, "multibootusb.cfg")):
with open(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name, "multibootusb.cfg"), "r") as multibootusb_cfg:
config.distro = multibootusb_cfg.read().replace('\n', '')
if config.distro:
uninstall_distro()
else:
return ""
class UninstallThread(threading.Thread):
def __init__(self, target_distro, uninstall_distro_dir_name, *args, **kw):
super(UninstallThread, self).__init__(*args, **kw)
self.target_distro = target_distro
self.uninstall_distro_dir_name = uninstall_distro_dir_name
def run(self):
do_uninstall_distro(self.target_distro, self.uninstall_distro_dir_name)
def delete_frm_file_list():
def delete_frm_file_list(iso_file_list, uninstall_distro_dir_name):
"""
Generic way to remove files from USB disk.
:param config.usb_disk:
@ -59,12 +56,11 @@ def delete_frm_file_list():
"""
usb_details = details(config.usb_disk)
usb_mount = usb_details['mount_point']
if config.iso_file_list is not None:
for f in config.iso_file_list:
if iso_file_list is not None:
for f in iso_file_list:
f = f.replace('\n', '').strip("/")
if platform.system() == "Windows":
f = f.replace('\n', '').strip("/").replace("/", "\\")
else:
f = f.replace('\n', '').strip("/")
f = f.replace("/", "\\")
if os.path.exists(os.path.join(usb_mount, "ldlinux.sys")):
try:
os.chmod(os.path.join(usb_mount, "ldlinux.sys"), 0o777)
@ -82,28 +78,30 @@ def delete_frm_file_list():
gen.log("Removing file " + (os.path.join(usb_mount, f)))
os.remove(os.path.join(usb_mount, f))
if os.path.exists(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name, "generic.cfg")):
with open(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name, "generic.cfg"), "r") as generic_cfg:
generic_cfg_fullpath = os.path.join(
usb_mount, "multibootusb", uninstall_distro_dir_name,
"generic.cfg")
if os.path.exists(generic_cfg_fullpath):
with open(generic_cfg_fullpath, "r") as generic_cfg:
generic = generic_cfg.read().replace('\n', '')
if platform.system() == "Windows":
generic = generic_cfg.read().replace('\n', '').replace("/", "\\")
else:
generic = generic_cfg.read().replace('\n', '')
generic = generic_cfg.read().replace("/", "\\")
if os.path.exists(os.path.join(usb_mount, generic.strip("/"))):
os.remove(os.path.join(usb_mount, generic.strip("/")))
gen.log('Removed files from ' + uninstall_distro_dir_name)
if platform.system() == 'Linux':
gen.log('Removed files from ' + config.uninstall_distro_dir_name)
gen.log('Syncing....')
os.sync()
def uninstall_distro():
def do_uninstall_distro(target_distro, uninstall_distro_dir_name):
"""
Uninstall selected distro from selected USB disk.
:param config.usb_disk: Path of the USB disk
:param config.uninstall_distro_dir_name: Directory where the distro is installed
:param _distro: Generic name applied to distro install by multibootusb
:param target_distro: Generic name applied to distro to be uninstalled
:param uninstall_distro_dir_name: Directory where the distro is installed
:return:
"""
usb_details = details(config.usb_disk)
@ -115,47 +113,50 @@ def uninstall_distro():
if usb_mount:
subprocess.call("chattr -i -R %s/* 2>/dev/null" % usb_mount, shell=True)
uninstall_distro_dir_name = os.path.join(
usb_mount, "multibootusb", config.uninstall_distro_dir_name)
uninstall_distro_dir_name_fullpath = os.path.join(
usb_mount, "multibootusb", uninstall_distro_dir_name)
uninstall_distro_iso_name = os.path.join(
usb_mount, config.uninstall_distro_dir_name) + '.iso'
filelist_fname = os.path.join(uninstall_distro_dir_name,
usb_mount, uninstall_distro_dir_name) + '.iso'
filelist_fname = os.path.join(uninstall_distro_dir_name_fullpath,
"iso_file_list.cfg")
if os.path.exists(filelist_fname):
with open(filelist_fname, "r") as f:
config.iso_file_list = f.readlines()
iso_file_list = f.readlines()
else:
iso_file_list = []
for path, subdirs, files in os.walk(uninstall_distro_dir_name):
for path, subdirs, files in os.walk(uninstall_distro_dir_name_fullpath):
for name in files:
if name.endswith(('ldlinux.sys', 'ldlinux.c32')):
os.chmod(os.path.join(path, name), 0o777)
os.unlink(os.path.join(path, name))
if config.distro == "opensuse":
if target_distro == "opensuse":
if os.path.exists(uninstall_distro_iso_name):
os.remove(uninstall_distro_iso_name)
elif config.distro in ["windows", "alpine", "generic"]:
delete_frm_file_list()
if config.distro == "ipfire":
elif target_distro in ["windows", "alpine", "generic"]:
# This function will be called anyway after this if/elif block
# delete_frm_file_list()
pass
elif target_distro == "ipfire":
files = os.listdir(usb_mount)
for f in files:
if f.endswith('.tlz'):
os.remove(os.path.join(usb_mount, f))
if os.path.exists(os.path.join(usb_mount, "distro.img")):
os.remove(os.path.join(usb_mount, "distro.img"))
elif config.distro == "trinity-rescue":
elif target_distro == "trinity-rescue":
shutil.rmtree(os.path.join(usb_mount, "trk3"))
if os.path.exists(uninstall_distro_dir_name):
if os.path.exists(uninstall_distro_dir_name_fullpath):
if platform.system() == 'Linux':
os.sync()
shutil.rmtree(uninstall_distro_dir_name)
shutil.rmtree(uninstall_distro_dir_name_fullpath)
delete_frm_file_list()
delete_frm_file_list(iso_file_list, uninstall_distro_dir_name)
update_sys_cfg_file()
update_grub_cfg_file()
update_sys_cfg_file(uninstall_distro_dir_name)
update_grub_cfg_file(uninstall_distro_dir_name)
# Check if bootx64.efi is replaced by distro
efi_grub_img = os.path.join(config.usb_mount, 'EFI', 'BOOT', 'bootx64.efi')
@ -172,7 +173,7 @@ def uninstall_distro():
gen.log('multibootusb EFI image already exist. Not copying...')
def update_sys_cfg_file():
def update_sys_cfg_file(uninstall_distro_dir_name):
"""
Main function to remove uninstall distro specific operations.
:return:
@ -186,13 +187,16 @@ def update_sys_cfg_file():
else:
gen.log("Updating syslinux.cfg file...")
string = open(sys_cfg_file).read()
string = re.sub(r'#start ' + config.uninstall_distro_dir_name + '.*?' + '#end ' + config.uninstall_distro_dir_name + '\s*', '', string, flags=re.DOTALL)
string = re.sub(r'#start ' + re.escape(uninstall_distro_dir_name)
+ '.*?' + '#end '
+ re.escape(uninstall_distro_dir_name)
+ r'\s*', '', string, flags=re.DOTALL)
config_file = open(sys_cfg_file, "w")
config_file.write(string)
config_file.close()
def update_grub_cfg_file():
def update_grub_cfg_file(uninstall_distro_dir_name):
"""
Main function to remove uninstall distro name from the grub.cfg file.
:return:
@ -200,13 +204,17 @@ def update_grub_cfg_file():
if platform.system() == 'Linux':
os.sync()
grub_cfg_file = os.path.join(config.usb_mount, "multibootusb", "grub", "grub.cfg")
grub_cfg_file = os.path.join(config.usb_mount, "multibootusb",
"grub", "grub.cfg")
if not os.path.exists(grub_cfg_file):
gen.log("grub.cfg file not found for updating changes.")
else:
gen.log("Updating grub.cfg file...")
string = open(grub_cfg_file).read()
string = re.sub(r'#start ' + config.uninstall_distro_dir_name + '.*?' + '#end ' + config.uninstall_distro_dir_name + '\s*', '', string, flags=re.DOTALL)
string = re.sub(r'#start ' + re.escape(uninstall_distro_dir_name)
+ '.*?' + '#end '
+ re.escape(uninstall_distro_dir_name)
+ r'\s*', '', string, flags=re.DOTALL)
config_file = open(grub_cfg_file, "w")
config_file.write(string)
config_file.close()
@ -214,7 +222,10 @@ def update_grub_cfg_file():
def uninstall_progress():
"""
Calculate uninstall progress percentage.
Start another thread that does the actual uninstallation work
and continuously calculate uninstall progress percentage.
This is the entry point for the uninstallation thread spawned
in GuiUninstallProgress.__init__.
:return:
"""
from . import progressbar
@ -223,42 +234,50 @@ def uninstall_progress():
if platform.system() == 'Linux':
os.sync()
if os.path.exists(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name, "multibootusb.cfg")):
with open(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name, "multibootusb.cfg"),
"r") as multibootusb_cfg:
config.distro = multibootusb_cfg.read().replace('\n', '')
else:
config.distro = ""
gen.log("Installed distro type is " + config.distro)
uninstall_distro_dir_name = config.uninstall_distro_dir_name \
.replace('\n', '')
if config.distro == "opensuse":
if os.path.exists(os.path.join(usb_mount, config.uninstall_distro_dir_name) + ".iso"):
folder_size_to_remove = os.path.getsize(os.path.join(usb_mount, config.uninstall_distro_dir_name) + ".iso")
drive_relative_mbcfg_path = os.path.join(
"multibootusb", uninstall_distro_dir_name, "multibootusb.cfg")
mbcfg_fullpath = os.path.join(usb_mount, drive_relative_mbcfg_path)
if os.path.exists(mbcfg_fullpath):
with open(mbcfg_fullpath,"r") as multibootusb_cfg:
target_distro = multibootusb_cfg.read().replace('\n', '')
else:
target_distro = ""
gen.log("Installed distro type is " + target_distro or "unknown")
if target_distro == "opensuse":
iso_fullpath = os.path.join(usb_mount, uninstall_distro_dir_name) \
+ ".iso"
if os.path.exists(iso_fullpath):
folder_size_to_remove = os.path.getsize(iso_fullpath)
else:
folder_size_to_remove = 0
folder_size_to_remove += disk_usage(str(usb_mount) + "/multibootusb/" + config.uninstall_distro_dir_name).used
elif config.distro == "windows" or config.distro == "Windows":
folder_size_to_remove += disk_usage(str(usb_mount) + "/multibootusb/" + uninstall_distro_dir_name).used
elif target_distro == "windows" or target_distro == "Windows":
if os.path.exists(os.path.join(usb_mount, "SOURCES")):
folder_size_to_remove = disk_usage(str(usb_mount) + "/SOURCES").used
else:
folder_size_to_remove = disk_usage(str(usb_mount) + "/SSTR").used
elif config.distro == "ipfire":
folder_size_to_remove = disk_usage(str(usb_mount) + "/multibootusb/" + config.uninstall_distro_dir_name).used
elif target_distro == "ipfire":
folder_size_to_remove = disk_usage(str(usb_mount) + "/multibootusb/" + uninstall_distro_dir_name).used
files = os.listdir(os.path.join(str(usb_mount)))
for f in files:
if f.endswith('.tlz'):
folder_size_to_remove += os.path.getsize(os.path.join(config.usb_mount, f))
elif config.distro == "trinity-rescue":
elif target_distro == "trinity-rescue":
folder_size_to_remove = disk_usage(os.path.join(usb_mount, "trk3")).used
folder_size_to_remove += disk_usage(usb_mount + "/multibootusb/" + config.uninstall_distro_dir_name).used
folder_size_to_remove += disk_usage(usb_mount + "/multibootusb/" + uninstall_distro_dir_name).used
else:
folder_size_to_remove = disk_usage(os.path.join(usb_mount, "multibootusb", config.uninstall_distro_dir_name)).used
folder_size_to_remove = disk_usage(os.path.join(usb_mount, "multibootusb", uninstall_distro_dir_name)).used
thrd = threading.Thread(target=unin_distro, name="uninstall_progress")
thrd = UninstallThread(target_distro, uninstall_distro_dir_name,
name="uninstall_progress")
initial_usb_size = disk_usage(usb_mount).used
thrd.start()
config.status_text = "Uninstalling " + config.uninstall_distro_dir_name
config.status_text = "Uninstalling " + uninstall_distro_dir_name
pbar = progressbar.ProgressBar(maxval=100).start() # bar = progressbar.ProgressBar(redirect_stdout=True)
while thrd.is_alive():
current_size = disk_usage(usb_mount).used

@ -138,13 +138,15 @@ def update_distro_cfg_files(iso_link, usb_disk, distro, persistence=0):
log('Updating distro specific config files...')
tweaker_params = ConfigTweakerParam(
distro, '/multibootusb/%s' % iso_basename(iso_link),
_iso_name, install_dir_for_grub,
persistence, usb_uuid, usb_mount, usb_disk)
tweaker_class_dict = {
'ubuntu' : UbuntuConfigTweaker,
'debian' : DebianConfigTweaker,
'debian-install' : DebianConfigTweaker,
'gentoo' : GentooConfigTweaker,
'centos' : CentosConfigTweaker,
'centos-install' : CentosConfigTweaker,
}
tweaker_class = tweaker_class_dict.get(distro)
@ -163,7 +165,7 @@ def update_distro_cfg_files(iso_link, usb_disk, distro, persistence=0):
string = re.sub(r'linuxefi', 'linux', string)
string = re.sub(r'initrdefi', 'initrd', string)
if tweaker_class:
tweaker = tweaker_class(tweaker_params)
tweaker = tweaker_class(distro, tweaker_params)
string = tweaker.tweak(string)
elif distro == 'grml':
@ -608,26 +610,22 @@ class ConfigTweakerParam:
def __init__(self, distro_name, distro_path, persistence_size,
usb_uuid, usb_mount, usb_disk):
self.distro_name = distro_name
assert distro_path[0] == '/'
self.distro_path = distro_path # drive relative
self.persistence_size = persistence_size
self.usb_uuid = usb_uuid
self.usb_mount = usb_mount
self.usb_disk = usb_disk
class ConfigTweaker:
BOOT_PARAMS_STARTER = 'kernel|append|linux'
def __init__(self, setup_params):
def __init__(self, distro_type, setup_params):
self.disto_type = distro_type
self.setup_params = setup_params
def config_is_persistence_aware(self, content):
""" Used to restrict update of boot parameters to persistent-aware
menu entries if the distribution provides any.
"""
return self.persistence_awareness_checking_re.search(content) \
is not None
def tweak_first_match(self, content, kernel_param_line_pattern,
apply_persistence_to_all_lines,
param_operations,
@ -643,13 +641,16 @@ class ConfigTweaker:
start, end = m.span()
upto_match, rest_of_content = content[:start], content[end:]
starter_part, starter_token, params_part = [m.group(i) for i in [1,2,3]]
starter_part, starter_token, params_part = [
m.group(i) for i in [1,2,3]]
params = params_part.split(' ')
if apply_persistence_to_all_lines or self.has_persistency_param(params):
param_operations = param_operations + \
param_operations_for_persistence
for op_or_op_list, precondition in param_operations:
if apply_persistence_to_all_lines or \
self.has_persistency_param(params):
ops_to_apply = param_operations + \
param_operations_for_persistence
else:
ops_to_apply = param_operations
for op_or_op_list, precondition in ops_to_apply:
if not precondition(starter_token, params):
continue
try:
@ -698,23 +699,42 @@ class ConfigTweaker:
def add_op_if_file_exists(self, op_list, op_creator_func, key,
candidate_relative_path_list, predicate):
for candidate in candidate_relative_path_list:
relpath = os.path.join(self.setup_params.distro_path, candidate)
relpath = os.path.join(self.setup_params.distro_path[1:],
candidate)
if os.path.exists(os.path.join(
self.setup_params.usb_mount, relpath)):
normalized_relpath = relpath.replace('\\','/')
normalized_relpath = '/' + relpath.replace('\\','/')
op_list.append((op_creator_func(key, normalized_relpath),
predicate))
break
def file_is_installed(self, path):
p = self.setup_params
fullpath = os.path.join(p.usb_mount, p.distro_path[1:], path)
return os.path.exists(fullpath)
class PersistenceConfigTweaker(ConfigTweaker):
def __init__(self, pac_re, *args, **kw):
self.persistence_awareness_checking_re = pac_re
super(PersistenceConfigTweaker, self).__init__(*args, **kw)
def config_is_persistence_aware(self, content):
""" Used to restrict update of boot parameters to persistent-aware
menu entries if the distribution provides any.
"""
return self.persistence_awareness_checking_re.search(content) \
is not None
class ConfigTweakerWithDebianStylePersistenceParam(ConfigTweaker):
class ConfigTweakerWithDebianStylePersistenceParam(PersistenceConfigTweaker):
def __init__(self, *args, **kw):
super(ConfigTweakerWithDebianStylePersistenceParam,
self).__init__(*args, **kw)
self.persistence_awareness_checking_re = re.compile(
persistence_awareness_checking_re = re.compile(
r'^\s*(%s).*?\s%s(\s.*|)$' % \
(self.BOOT_PARAMS_STARTER, self.PERSISTENCY_TOKEN),
flags=re.I|re.MULTILINE)
super(ConfigTweakerWithDebianStylePersistenceParam,
self).__init__(persistence_awareness_checking_re, *args, **kw)
def has_persistency_param(self, params):
return self.PERSISTENCY_TOKEN in params
@ -793,8 +813,6 @@ class GentooConfigTweaker(NoPersistenceTweaker):
],
starter_is_either('append', 'linux')),
]
sfs_path = os.path.join(self.setup_params.distro_path,
'liberte','boot', 'root-x86.sfs')
self.add_op_if_file_exists(
ops, add_or_replace_kv,
'loop=', ['liberte/boot/root-x86.sfs', 'image.squashfs'],
@ -802,13 +820,86 @@ class GentooConfigTweaker(NoPersistenceTweaker):
return ops
class CentosConfigTweaker(PersistenceConfigTweaker):
def __init__(self, *args, **kw):
persistence_awareness_checking_re = re.compile(
r'^\s*(%s).*?\s(rd.live.overlay|overlay)=.+?' %
self.BOOT_PARAMS_STARTER, flags=re.I|re.MULTILINE)
super(CentosConfigTweaker, self).__init__(
persistence_awareness_checking_re, *args, **kw)
def has_persistency_param(self, params):
return any(p.startswith(('overlay=', 'rd.live.overlay='))
for p in params)
def param_operations(self):
uuid_spec = 'UUID=%s' % self.setup_params.usb_uuid
escaped_distro_path = self.setup_params.distro_path \
.replace(' ', '\\0x20')
live_path = escaped_distro_path + '/LiveOS'
ops = [(replace_kv('inst.stage2=', 'hd:%s:%s' %
(uuid_spec, escaped_distro_path)), always),
(add_or_replace_kv('inst.repo=',
'http://mirror.centos.org'
'/centos/7/os/x86_64/'),
contains_key('inst.stage2=')),
(replace_kv('root=', 'live:' + uuid_spec), always),
(add_or_replace_kv('rd.live.dir=', live_path),
contains_any_token('rd.live.image', 'Solus')),
(add_or_replace_kv('live_dir=', live_path),
contains_token('liveimage')), ]
if self.file_is_installed('.treeinfo'):
# Add or replace value of 'inst.repo=' with reference
# to the copied iso.
ops.append(
(add_or_replace_kv(
'inst.repo=',
'hd:UUID=%s:%s' % (
self.setup_params.usb_uuid,
self.setup_params.distro_path + '/'
+ self.setup_params.distro_name + '.iso')),
starter_is_either('append', 'linux')))
return ops
def param_operations_for_persistence(self):
uuid_spec = 'UUID=%s' % self.setup_params.usb_uuid
return [
(remove_tokens('ro'), always),
(add_or_replace_kv('overlay=', uuid_spec),
contains_token('liveimage')),
([add_tokens('rw'),
add_or_replace_kv('rd.live.overlay=', uuid_spec)],
contains_token('rd.live.image'))
]
def test_tweak_objects():
def os_path_exists(f):
if f.endswith('liberte/boot/root-x86.sfs'):
return False
if f.endswith('image.squashfs'):
return True
return False
saved = os.path.exists
os.path.exists = os_path_exists
try:
_test_tweak_objects()
finally:
os.path.exists = saved
def _test_tweak_objects():
usb_mount = 'L:'
usb_disk = 'L:'
setup_params_no_persistence = ConfigTweakerParam(
'debian', '/multibootusb/debian', 0, '{usb-uuid}', usb_mount, usb_disk)
debian_tweaker = DebianConfigTweaker(setup_params_no_persistence)
ubuntu_tweaker = UbuntuConfigTweaker(setup_params_no_persistence)
'{iso-name}', '/multibootusb/{iso-name}', 0,
'{usb-uuid}', usb_mount, usb_disk)
debian_tweaker = DebianConfigTweaker('debian', setup_params_no_persistence)
ubuntu_tweaker = UbuntuConfigTweaker('ubuntu', setup_params_no_persistence)
centos_tweaker = CentosConfigTweaker('centos', setup_params_no_persistence)
# Test awareness on 'persistent'
content = """
@ -825,20 +916,40 @@ def test_tweak_objects():
print ("Testing awareness on 'persistence' of debian tweaker.")
assert debian_tweaker.config_is_persistence_aware(content)
print ("Testing awareness on 'overlay=' of centos tweaker.")
content = """
append boot=live foo baz=1 overlay=UUID:2234-1224 double-spaced ignore_bootid persistence more stuff""".lstrip()
assert centos_tweaker.config_is_persistence_aware(content)
print ("Testing awareness on 'rd.live.overlay=' of centos tweaker.")
content = """
append boot=live foo baz=1 rd.live.overlay=UUID:2234-1224 double-spaced ignore_bootid persistence more stuff""".lstrip()
assert centos_tweaker.config_is_persistence_aware(content)
print ("Testing indefference on persistence keys of centos tweaker.")
content = """
append boot=live foo baz=1 double-spaced ignore_bootid persistence more stuff""".lstrip()
assert not centos_tweaker.config_is_persistence_aware(content)
print ("Testing awareness on 'overlay=' of centos tweaker.")
content = """
append boot=live foo baz=1 double-spaced ignore_bootid persistence more stuff""".lstrip()
assert not centos_tweaker.config_is_persistence_aware(content)
print ("Testing if 'persistence' token is left at the original place.")
content = "\tlinux\tfoo persistence boot=live in the middle"
assert debian_tweaker.tweak(content) == "\tlinux\tfoo persistence boot=live in the middle ignore_bootid live-media-path=/multibootusb/debian/live persistence-path=/multibootusb/debian"""
assert debian_tweaker.tweak(content) == "\tlinux\tfoo persistence boot=live in the middle ignore_bootid live-media-path=/multibootusb/{iso-name}/live persistence-path=/multibootusb/{iso-name}"""
print ("Testing if 'boot=live' at the very end is recognized.")
content = "menu\n\tlinux\tfoo persistence in the middle boot=live"
assert debian_tweaker.tweak(content) == "menu\n\tlinux\tfoo persistence in the middle boot=live ignore_bootid live-media-path=/multibootusb/debian/live persistence-path=/multibootusb/debian"""
assert debian_tweaker.tweak(content) == "menu\n\tlinux\tfoo persistence in the middle boot=live ignore_bootid live-media-path=/multibootusb/{iso-name}/live persistence-path=/multibootusb/{iso-name}"""
print ("Testing if 'boot=live' at a line end is recognized.")
content = """append zoo
\tappend\tfoo persistence in the middle boot=live
append foo"""
assert debian_tweaker.tweak(content) == """append zoo
\tappend\tfoo persistence in the middle boot=live ignore_bootid live-media-path=/multibootusb/debian/live persistence-path=/multibootusb/debian
\tappend\tfoo persistence in the middle boot=live ignore_bootid live-media-path=/multibootusb/{iso-name}/live persistence-path=/multibootusb/{iso-name}
append foo"""
print ("Testing if replacement of 'live-media=' happens on non-boot lines.")
@ -848,26 +959,28 @@ append foo"""
print ("Testing if \\tappend is recognized as a starter.")
content = """\tappend foo boot=live ignore_bootid persistence in the middle live-media-path=/foo/bar"""
assert debian_tweaker.tweak(content) == """\tappend foo boot=live ignore_bootid persistence in the middle live-media-path=/multibootusb/debian/live persistence-path=/multibootusb/debian"""
assert debian_tweaker.tweak(content) == """\tappend foo boot=live ignore_bootid persistence in the middle live-media-path=/multibootusb/{iso-name}/live persistence-path=/multibootusb/{iso-name}"""
print ("Testing if debian tweaker does not get tickled by 'persistent'.")
content = """\tappend boot=live foo ignore_bootid persistent in the middle live-media-path=/foo/bar"""
assert debian_tweaker.tweak(content) == """\tappend boot=live foo ignore_bootid persistent in the middle live-media-path=/multibootusb/debian/live"""
assert debian_tweaker.tweak(content) == """\tappend boot=live foo ignore_bootid persistent in the middle live-media-path=/multibootusb/{iso-name}/live"""
print ("Testing replacement of 'live-media-path' value.")
content = " append boot=live foo live-media-path=/foo/bar more"
assert debian_tweaker.tweak(content) == """ append boot=live foo live-media-path=/multibootusb/debian/live more ignore_bootid"""
assert debian_tweaker.tweak(content) == """ append boot=live foo live-media-path=/multibootusb/{iso-name}/live more ignore_bootid"""
print ("Testing rewriting of 'file=' param by debian_tweaker.")
content = " kernel file=/cdrom/preseed/ubuntu.seed boot=live"
setup_params_persistent = ConfigTweakerParam(
'debian', '/multibootusb/debian', 128*1024*1024, '{usb-uuid}',
'debian', '/multibootusb/{iso-name}', 128*1024*1024, '{usb-uuid}',
usb_mount, usb_disk)
debian_persistence_tweaker = DebianConfigTweaker(
setup_params_persistent)
'debian', setup_params_persistent)
ubuntu_persistence_tweaker = UbuntuConfigTweaker(
setup_params_persistent)
'ubuntu', setup_params_persistent)
centos_persistence_tweaker = CentosConfigTweaker(
'centos', setup_params_persistent)
print ("Testing if debian tweaker appends persistence parameters.")
content = """label foo
@ -876,7 +989,7 @@ append foo"""
"""
assert debian_persistence_tweaker.tweak(content) == """label foo
kernel foo bar
append boot=live foo live-media-path=/multibootusb/debian/live more ignore_bootid persistence persistence-path=/multibootusb/debian
append boot=live foo live-media-path=/multibootusb/{iso-name}/live more ignore_bootid persistence persistence-path=/multibootusb/{iso-name}
"""
print ("Testing if ubuntu tweaker selectively appends persistence params.")
@ -886,7 +999,7 @@ append foo"""
"""
assert ubuntu_persistence_tweaker.tweak(content) == """label foo
kernel foo bar
append boot=casper foo live-media-path=/multibootusb/debian/casper more ignore_bootid cdrom-detect/try-usb=true floppy.allowed_drive_mask=0 ignore_uuid root=UUID={usb-uuid} persistent persistent-path=/multibootusb/debian
append boot=casper foo live-media-path=/multibootusb/{iso-name}/casper more ignore_bootid cdrom-detect/try-usb=true floppy.allowed_drive_mask=0 ignore_uuid root=UUID={usb-uuid} persistent persistent-path=/multibootusb/{iso-name}
"""
# Test rewrite of persistence-aware configuration.
@ -910,50 +1023,115 @@ label live-persistence
menu label Live (^forensic mode)
linux /live/vmlinuz
initrd /live/initrd.img
append boot=live noconfig=sudo username=root hostname=kali noswap noautomount ignore_bootid live-media-path=/multibootusb/debian/live
append boot=live noconfig=sudo username=root hostname=kali noswap noautomount ignore_bootid live-media-path=/multibootusb/{iso-name}/live
label live-persistence
menu label ^Live USB Persistence (check kali.org/prst)
linux /live/vmlinuz
initrd /live/initrd.img
append boot=live noconfig=sudo username=root hostname=kali persistence ignore_bootid live-media-path=/multibootusb/debian/live persistence-path=/multibootusb/debian
append boot=live noconfig=sudo username=root hostname=kali persistence ignore_bootid live-media-path=/multibootusb/{iso-name}/live persistence-path=/multibootusb/{iso-name}
"""
setup_params = ConfigTweakerParam(
'debian', '/multibootusb/pentoo-amd64-hardened-2018.0_RC5.8_pre20180305/', 0, '{usb-uuid}', usb_mount, usb_disk)
gentoo_tweaker = GentooConfigTweaker(setup_params)
'{iso-name}', '/multibootusb/{iso-name}',
0, '{usb-uuid}', usb_mount, usb_disk)
gentoo_tweaker = GentooConfigTweaker('gentoo', setup_params)
print ("Testing Gentoo-tweaker on syslinux config.")
content = """label pentoo
menu label Pentoo Defaults (verify) 
menu label Pentoo Defaults (verify)
kernel /isolinux/pentoo
append initrd=/isolinux/pentoo.igz root=/dev/ram0 init=/linuxrc nox nodhcp overlayfs max_loop=256 dokeymap looptype=squashfs loop=/image.squashfs cdroot video=uvesafb:mtrr:3,ywrap,1024x768-16 usbcore.autosuspend=1 console=tty0 net.ifnames=0 scsi_mod.use_blk_mq=1 ipv6.autoconf=0 verify
"""
# Note that you'll have pentoo installed on the flash drive
# for this test to succeed.
assert gentoo_tweaker.tweak(content)=="""label pentoo
menu label Pentoo Defaults (verify) 
menu label Pentoo Defaults (verify)
kernel /isolinux/pentoo
append initrd=/isolinux/pentoo.igz root=/dev/ram0 init=/linuxrc nox nodhcp overlayfs max_loop=256 dokeymap looptype=squashfs loop=/multibootusb/pentoo-amd64-hardened-2018.0_RC5.8_pre20180305/image.squashfs cdroot video=uvesafb:mtrr:3,ywrap,1024x768-16 usbcore.autosuspend=1 console=tty0 net.ifnames=0 scsi_mod.use_blk_mq=1 ipv6.autoconf=0 verify real_root=%s slowusb subdir=/multibootusb/pentoo-amd64-hardened-2018.0_RC5.8_pre20180305/
append initrd=/isolinux/pentoo.igz root=/dev/ram0 init=/linuxrc nox nodhcp overlayfs max_loop=256 dokeymap looptype=squashfs loop=/multibootusb/{iso-name}/image.squashfs cdroot video=uvesafb:mtrr:3,ywrap,1024x768-16 usbcore.autosuspend=1 console=tty0 net.ifnames=0 scsi_mod.use_blk_mq=1 ipv6.autoconf=0 verify real_root=%s slowusb subdir=/multibootusb/{iso-name}
""" % usb_disk
print ("Testing Gentoo-tweaker on grub config.")
content = """insmod all_video
menuentry 'Boot LiveCD (kernel: pentoo)' --class gnu-linux --class os {
linux /isolinux/pentoo root=/dev/ram0 init=/linuxrc nox aufs max_loop=256 dokeymap looptype=squashfs loop=/image.squashfs cdroot cdroot_hash=xxx
initrd /isolinux/pentoo.igz
linux /isolinux/pentoo root=/dev/ram0 init=/linuxrc nox aufs max_loop=256 dokeymap looptype=squashfs loop=/image.squashfs cdroot cdroot_hash=xxx
initrd /isolinux/pentoo.igz
}
"""
assert gentoo_tweaker.tweak(content)=="""insmod all_video
menuentry 'Boot LiveCD (kernel: pentoo)' --class gnu-linux --class os {
linux /isolinux/pentoo root=/dev/ram0 init=/linuxrc nox max_loop=256 dokeymap looptype=squashfs loop=/multibootusb/pentoo-amd64-hardened-2018.0_RC5.8_pre20180305/image.squashfs cdroot real_root=%s slowusb subdir=/multibootusb/pentoo-amd64-hardened-2018.0_RC5.8_pre20180305/ overlayfs
initrd /isolinux/pentoo.igz
linux /isolinux/pentoo root=/dev/ram0 init=/linuxrc nox max_loop=256 dokeymap looptype=squashfs loop=/multibootusb/{iso-name}/image.squashfs cdroot real_root=%s slowusb subdir=/multibootusb/{iso-name} overlayfs
initrd /isolinux/pentoo.igz
}
""" % usb_disk
print ("Testing centos tweaker on DVD-installer")
saved = os.path.exists
os.path.exists = lambda f: f.endswith('/.treeinfo') or saved(f)
try:
content = r"""label linux
menu label ^Install CentOS 7
kernel vmlinuz
append initrd=initrd.img inst.stage2=hd:LABEL=CentOS\x207\x20x86_64 quiet
"""
assert centos_tweaker.tweak(content)=="""label linux
menu label ^Install CentOS 7
kernel vmlinuz
append initrd=initrd.img inst.stage2=hd:UUID={usb-uuid}:/multibootusb/{iso-name} quiet inst.repo=hd:UUID={usb-uuid}:/multibootusb/{iso-name}/{iso-name}.iso
"""
finally:
os.path.exists = saved
print ("Testing centos tweaker on Net-installer")
assert centos_tweaker.tweak(content)=="""label linux
menu label ^Install CentOS 7
kernel vmlinuz
append initrd=initrd.img inst.stage2=hd:UUID={usb-uuid}:/multibootusb/{iso-name} quiet inst.repo=http://mirror.centos.org/centos/7/os/x86_64/
"""
content = r"""label linux0
menu label ^Start CentOS
kernel vmlinuz0
append initrd=initrd0.img root=live:CDLABEL=CentOS-7-x86_64-LiveGNOME-1708 rootfstype=auto ro rd.live.image quiet rhgb rd.luks=0 rd.md=0 rd.dm=0
menu default
"""
print ("Testing centos tweaker on Live")
assert centos_tweaker.tweak(content)=="""label linux0
menu label ^Start CentOS
kernel vmlinuz0
append initrd=initrd0.img root=live:UUID={usb-uuid} rootfstype=auto ro rd.live.image quiet rhgb rd.luks=0 rd.md=0 rd.dm=0 rd.live.dir=/multibootusb/{iso-name}/LiveOS
menu default
"""
print ("Testing persistent centos tweaker on non-persistence config.")
content = r"""label linux0
menu label ^Start CentOS
kernel vmlinuz0
append initrd=initrd0.img root=live:CDLABEL=CentOS-7-x86_64-LiveGNOME-1708 rootfstype=auto ro rd.live.image quiet rhgb rd.luks=0 rd.md=0 rd.dm=0
menu default
"""
assert centos_persistence_tweaker.tweak(content)=="""label linux0
menu label ^Start CentOS
kernel vmlinuz0
append initrd=initrd0.img root=live:UUID={usb-uuid} rootfstype=auto rd.live.image quiet rhgb rd.luks=0 rd.md=0 rd.dm=0 rd.live.dir=/multibootusb/{iso-name}/LiveOS rw rd.live.overlay=UUID={usb-uuid}
menu default
"""
print ("Testing persistent centos tweaker not touching "
"non-persistent line")
content = r"""label linux0
menu label ^Start CentOS
append kenel=vmlinuz0
append rd.live.overlay=UUID:2234-2223 ro rd.live.image
append initrd=initrd0.img root=live:CDLABEL=CentOS-7-x86_64-LiveGNOME-1708 rootfstype=auto ro rd.live.image quiet rhgb rd.luks=0 rd.md=0 rd.dm=0
menu default
"""
assert centos_persistence_tweaker.tweak(content)=="""label linux0
menu label ^Start CentOS
append kenel=vmlinuz0
append rd.live.overlay=UUID={usb-uuid} rd.live.image rd.live.dir=/multibootusb/{iso-name}/LiveOS rw
append initrd=initrd0.img root=live:UUID={usb-uuid} rootfstype=auto ro rd.live.image quiet rhgb rd.luks=0 rd.md=0 rd.dm=0 rd.live.dir=/multibootusb/{iso-name}/LiveOS
menu default
"""
def do_test_abspath_rewrite():
@ -976,7 +1154,8 @@ def test_abspath_rewrite():
path = path.replace('\\', '/')
if path.endswith('.efi'):
return False
if path.startswith('g:/multibootusb/ubuntu-14.04.5-desktop-amd64/boot'):
if path.startswith('g:/multibootusb/ubuntu-14.04.5-desktop-amd64'
'/boot'):
return True
if path.endswith('/boot/grub/grub.cfg'):
return True

Loading…
Cancel
Save