2 # -*- coding: utf-8 -*-
3 # pylint: disable-msg=C0302
8 This script installs a grml system (either a running system or ISO[s]) to a USB device
10 :copyright: (c) 2009, 2010, 2011 by Michael Prokop <mika@grml.org>
11 :license: GPL v2 or any later version
12 :bugreports: http://grml.org/bugs/
16 from optparse import OptionParser
17 from inspect import isroutine, isclass
18 import datetime, logging, os, re, subprocess, sys, tempfile, time, os.path
24 # The line following this line is patched by debian/rules and tarball.sh.
25 PROG_VERSION='***UNRELEASED***'
28 MOUNTED = set() # register mountpoints
29 TMPFILES = set() # register tmpfiles
30 DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
31 GRML_FLAVOURS = set() # which flavours are being installed?
34 SYSLINUX_LIBS = "/usr/lib/syslinux/"
36 def syslinux_warning(option, opt, value, opt_parser):
37 """A helper function for printing a warning about deprecated option
39 # pylint: disable-msg=W0613
40 sys.stderr.write("Note: the --syslinux option is deprecated as syslinux "
41 "is grml2usb's default. Continuing anyway.\n")
42 setattr(opt_parser.values, option.dest, True)
44 # if grub option is set, unset syslinux option
45 def grub_option(option, opt, value, opt_parser):
46 """A helper function adjusting other option values
48 # pylint: disable-msg=W0613
49 setattr(opt_parser.values, option.dest, True)
50 setattr(opt_parser.values, 'syslinux', False)
53 USAGE = "Usage: %prog [options] <[ISO[s] | /live/image]> </dev/sdX#>\n\
55 %prog installs grml ISO[s] to an USB device to be able to boot from it.\n\
56 Make sure you have at least one grml ISO or a running grml system (/live/image),\n\
57 grub or syslinux and root access.\n\
59 Run %prog --help for usage hints, further information via: man grml2usb"
61 # pylint: disable-msg=C0103
62 # pylint: disable-msg=W0603
63 parser = OptionParser(usage=USAGE)
64 parser.add_option("--bootoptions", dest="bootoptions",
65 action="append", type="string",
66 help="use specified bootoptions as default")
67 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
68 help="do not copy files but just install a bootloader")
69 parser.add_option("--copy-only", dest="copyonly", action="store_true",
70 help="copy files only but do not install bootloader")
71 parser.add_option("--dry-run", dest="dryrun", action="store_true",
72 help="avoid executing commands")
73 parser.add_option("--fat16", dest="fat16", action="store_true",
74 help="format specified partition with FAT16")
75 parser.add_option("--force", dest="force", action="store_true",
76 help="force any actions requiring manual interaction")
77 parser.add_option("--grub", dest="grub", action="callback",
79 help="install grub bootloader instead of (default) syslinux")
80 parser.add_option("--grub-mbr", dest="grubmbr", action="store_true",
81 help="install grub into MBR instead of (default) PBR")
82 parser.add_option("--mbr-menu", dest="mbrmenu", action="store_true",
83 help="enable interactive boot menu in MBR")
84 parser.add_option("--quiet", dest="quiet", action="store_true",
85 help="do not output anything but just errors on console")
86 parser.add_option("--remove-bootoption", dest="removeoption", action="append",
87 help="regex for removing existing bootoptions")
88 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
89 help="do not install /boot/addons/ files")
90 parser.add_option("--skip-grub-config", dest="skipgrubconfig", action="store_true",
91 help="skip generation of grub configuration files")
92 parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
93 help="do not install a master boot record (MBR) on the device")
94 parser.add_option("--skip-syslinux-config", dest="skipsyslinuxconfig", action="store_true",
95 help="skip generation of syslinux configuration files")
96 parser.add_option("--syslinux", dest="syslinux", action="callback", default=True,
97 callback=syslinux_warning,
98 help="install syslinux bootloader (deprecated as it's the default)")
99 parser.add_option("--syslinux-mbr", dest="syslinuxmbr", action="store_true",
100 help="install syslinux master boot record (MBR) instead of default")
101 parser.add_option("--verbose", dest="verbose", action="store_true",
102 help="enable verbose mode")
103 parser.add_option("-v", "--version", dest="version", action="store_true",
104 help="display version and exit")
105 (options, args) = parser.parse_args()
108 GRML2USB_BASE = '/usr/share/grml2usb'
109 if not os.path.isdir(GRML2USB_BASE):
110 GRML2USB_BASE = os.path.dirname(os.path.realpath(__file__))
113 class CriticalException(Exception):
114 """Throw critical exception if the exact error is not known but fatal."
116 @Exception: message"""
120 # The following two functions help to operate on strings as
121 # array (list) of bytes (octets). In Python 3000, the bytes
122 # datatype will need to be used. This is intended for using
123 # with manipulation of files on the octet level, like shell
124 # arrays, e.g. in MBR creation.
127 def array2string(*a):
128 """Convert a list of integers [0;255] to a string."""
129 return struct.pack("%sB" % len(a), *a)
133 """Convert a (bytes) string into a list of integers."""
134 return struct.unpack("%sB" % len(s), s)
138 """Cleanup function to make sure there aren't any mounted devices left behind.
141 logging.info("Cleaning up before exiting...")
142 proc = subprocess.Popen(["sync"])
146 for device in MOUNTED:
148 for tmpfile in TMPFILES:
150 # ignore: RuntimeError: Set changed size during iteration
152 logging.debug('caught expection RuntimeError, ignoring')
155 def register_tmpfile(path):
163 def unregister_tmpfile(path):
165 remove registered tmpfile
169 TMPFILES.remove(path)
174 def register_mountpoint(target):
175 """register specified target in a set() for handling clean exiting
177 @target: destination target of mountpoint
183 def unregister_mountpoint(target):
184 """unregister specified target in a set() for handling clean exiting
186 @target: destination target of mountpoint
189 if target in MOUNTED:
190 MOUNTED.remove(target)
193 def get_function_name(obj):
194 """Helper function for use in execute() to retrive name of a function
196 @obj: the function object
198 if not (isroutine(obj) or isclass(obj)):
200 return obj.__module__ + '.' + obj.__name__
203 def execute(f, *exec_arguments):
204 """Wrapper for executing a command. Either really executes
205 the command (default) or when using --dry-run commandline option
206 just displays what would be executed."""
207 # usage: execute(subprocess.Popen, (["ls", "-la"]))
209 # pylint: disable-msg=W0141
210 logging.debug('dry-run only: %s(%s)', get_function_name(f), ', '.join(map(repr, exec_arguments)))
212 # pylint: disable-msg=W0142
213 return f(*exec_arguments)
217 """Check whether a given file can be executed
219 @fpath: full path to file
221 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
225 """Check whether a given program is available in PATH
227 @program: name of executable"""
228 fpath = os.path.split(program)[0]
233 for path in os.environ["PATH"].split(os.pathsep):
234 exe_file = os.path.join(path, program)
241 def get_defaults_file(iso_mount, flavour, name):
242 """get the default file for syslinux
244 bootloader_dirs = ['/boot/isolinux/', '/boot/syslinux/']
245 for directory in bootloader_dirs:
247 "%s_%s" % (get_flavour_filename(flavour), name):
248 if os.path.isfile(iso_mount + directory + name):
249 return (directory, name)
252 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
253 """Given a search path, find file
255 @filename: name of file to search for
256 @search_path: path where searching for the specified filename"""
258 paths = search_path.split(os.pathsep)
259 current_dir = '' # make pylint happy :)
262 """Helper function ffor testing if specified file exists in cwd
264 @cwd: current working directory
266 return os.path.exists(os.path.join(cwd, filename))
270 if match_file(current_dir):
273 # pylint: disable-msg=W0612
274 for current_dir, directories, files in os.walk(path):
275 if match_file(current_dir):
279 return os.path.abspath(os.path.join(current_dir, filename))
284 def check_uid_root():
285 """Check for root permissions"""
286 if not os.geteuid()==0:
287 sys.exit("Error: please run this script with uid 0 (root).")
290 def mkfs_fat16(device):
291 """Format specified device with VFAT/FAT16 filesystem.
293 @device: partition that should be formated"""
296 logging.info("Would execute mkfs.vfat -F 16 %s now.", device)
299 logging.info("Formating partition with fat16 filesystem")
300 logging.debug("mkfs.vfat -F 16 %s", device)
301 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
303 if proc.returncode != 0:
304 raise CriticalException("error executing mkfs.vfat")
307 def generate_isolinux_splash(grml_flavour):
308 """Generate bootsplash for isolinux/syslinux
310 @grml_flavour: name of grml flavour the configuration should be generated for"""
312 grml_name = grml_flavour
315 \ f17
\f\18/boot/syslinux/logo.16
317 Some information and boot options available via keys F2 - F10. http://grml.org/
319 """ % {'grml_name': grml_name} )
322 def generate_main_syslinux_config(*arg):
323 """Generate main configuration for use in syslinux.cfg
325 @*arg: just for backward compatibility"""
326 # pylint: disable-msg=W0613
327 # remove warning about unused arg
331 menu label Default boot modes:
340 menu label Additional boot entries for:
342 include additional.cfg
349 include promptname.cfg
352 Jump to old style isolinux prompt
353 featuring further information
354 regarding available boot options.
362 def generate_flavour_specific_syslinux_config(grml_flavour):
363 """Generate flavour specific configuration for use in syslinux.cfg
365 @grml_flavour: name of grml flavour the configuration should be generated for"""
369 menu begin grml %(grml_flavour)s
370 menu title %(display_name)s
372 menu label ^Back to main menu...
375 # include config for boot parameters from disk
376 include %(grml_flavour)s_grml.cfg
379 """ % {'grml_flavour': grml_flavour, 'display_name' : grml_flavour.replace('_', '-') } )
382 def install_grub(device):
383 """Install grub on specified device.
385 @mntpoint: mountpoint of device where grub should install its files to
386 @device: partition where grub should be installed to"""
389 logging.info("Would execute grub-install [--root-directory=mount_point] %s now.", device)
391 device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
392 register_tmpfile(device_mountpoint)
395 mount(device, device_mountpoint, "")
397 # If using --grub-mbr then make sure we install grub in MBR instead of PBR
399 logging.debug("Using option --grub-mbr ...")
400 if device[-1:].isdigit():
401 grub_device = re.match(r'(.*?)\d*$', device).group(1)
407 logging.info("Installing grub as bootloader")
408 for opt in ["", "--force" ]:
409 logging.debug("grub-install --recheck %s --no-floppy --root-directory=%s %s",
410 opt, device_mountpoint, grub_device)
411 proc = subprocess.Popen(["grub-install", "--recheck", opt, "--no-floppy",
412 "--root-directory=%s" % device_mountpoint, grub_device],
413 stdout=file(os.devnull, "r+"))
415 if proc.returncode == 0:
418 if proc.returncode != 0:
419 # raise Exception("error executing grub-install")
420 logging.critical("Fatal: error executing grub-install "
421 + "(please check the grml2usb FAQ or drop the --grub option)")
422 logging.critical("Note: if using grub2 consider using "
423 + "the --grub-mbr option as grub considers PBR problematic.")
426 except CriticalException, error:
427 logging.critical("Fatal: %s", error)
432 unmount(device_mountpoint, "")
433 os.rmdir(device_mountpoint)
434 unregister_tmpfile(device_mountpoint)
437 def install_syslinux(device):
438 """Install syslinux on specified device.
440 @device: partition where syslinux should be installed to"""
443 logging.info("Would install syslinux as bootloader on %s", device)
446 # syslinux -d boot/isolinux /dev/sdb1
447 logging.info("Installing syslinux as bootloader")
448 logging.debug("syslinux -d boot/syslinux %s", device)
449 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
451 if proc.returncode != 0:
452 raise CriticalException("Error executing syslinux (either try --fat16 or use grub?)")
455 def install_bootloader(device):
456 """Install bootloader on specified device.
458 @device: partition where bootloader should be installed to"""
460 # by default we use grub, so install syslinux only on request
464 except CriticalException, error:
465 logging.critical("Fatal: %s", error)
470 install_syslinux(device)
471 except CriticalException, error:
472 logging.critical("Fatal: %s", error)
477 def install_mbr(mbrtemplate, device, partition, ismirbsdmbr=True):
478 """install 'mbr' master boot record (MBR) on a device
480 Retrieve the partition table from "device", install an MBR from the
481 "mbrtemplate" file, set the "partition" (0..3) active, and install the
482 result back to "device".
484 @mbrtemplate: default MBR file
486 @device: name of a file assumed to be a hard disc (or USB stick) image, or
487 something like "/dev/sdb"
489 @partition: must be a number between 0 and 3, inclusive
491 @mbrtemplate: must be a valid MBR file of at least 440 (or 439 if
494 @ismirbsdmbr: if true then ignore the active flag, set the mirbsdmbr
495 specific flag to 0/1/2/3 and set the MBR's default value accordingly. If
496 false then leave the mirbsdmbr specific flag set to FFh, set all
497 active flags to 0 and set the active flag of the partition to 80h. Note:
498 behaviour of mirbsdmbr: if flag = 0/1/2/3 then use it, otherwise search for
501 logging.info("Installing default MBR")
503 if not os.path.isfile(mbrtemplate):
504 logging.critical("Error: %s can not be read.", mbrtemplate)
505 raise CriticalException("Error installing MBR (either try --syslinux-mbr or install missing file \"%s\"?)" % mbrtemplate)
507 if partition is not None and ((partition < 0) or (partition > 3)):
508 logging.warn("Cannot activate partition %d" % partition)
516 tmpf = tempfile.NamedTemporaryFile()
518 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1", device, tmpf.name)
519 proc = subprocess.Popen(["dd", "if=%s" % device, "of=%s" % tmpf.name, "bs=512", "count=1"],
520 stderr=file(os.devnull, "r+"))
522 if proc.returncode != 0:
523 raise Exception("error executing dd (first run)")
525 logging.debug("executing: dd if=%s of=%s bs=%s count=1 conv=notrunc", mbrtemplate,
526 tmpf.name, nmbrbytes)
527 proc = subprocess.Popen(["dd", "if=%s" % mbrtemplate, "of=%s" % tmpf.name, "bs=%s" % nmbrbytes,
528 "count=1", "conv=notrunc"], stderr=file(os.devnull, "r+"))
530 if proc.returncode != 0:
531 raise Exception("error executing dd (second run)")
533 mbrcode = tmpf.file.read(512)
534 if len(mbrcode) < 512:
535 raise EOFError("MBR size (%d) < 512" % len(mbrcode))
537 if partition is not None:
539 mbrcode = mbrcode[0:439] + chr(partition) + \
540 mbrcode[440:510] + "\x55\xAA"
542 actives = ["\x00", "\x00", "\x00", "\x00"]
543 actives[partition] = "\x80"
544 mbrcode = mbrcode[0:446] + actives[0] + \
545 mbrcode[447:462] + actives[1] + \
546 mbrcode[463:478] + actives[2] + \
547 mbrcode[479:494] + actives[3] + \
548 mbrcode[495:510] + "\x55\xAA"
552 tmpf.file.write(mbrcode)
555 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1 conv=notrunc", tmpf.name, device)
556 proc = subprocess.Popen(["dd", "if=%s" % tmpf.name, "of=%s" % device, "bs=512", "count=1",
557 "conv=notrunc"], stderr=file(os.devnull, "r+"))
559 if proc.returncode != 0:
560 raise Exception("error executing dd (third run)")
564 def is_writeable(device):
565 """Check if the device is writeable for the current user
567 @device: partition where bootloader should be installed to"""
571 #raise Exception("no device for checking write permissions")
573 if not os.path.exists(device):
576 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
579 def mount(source, target, mount_options):
580 """Mount specified source on given target
582 @source: name of device/ISO that should be mounted
583 @target: directory where the ISO should be mounted to
584 @options: mount specific options"""
586 # note: options.dryrun does not work here, as we have to
587 # locate files and identify the grml flavour
589 for x in file('/proc/mounts').readlines():
590 if x.startswith(source):
591 raise CriticalException("Error executing mount: %s already mounted - " % source
592 + "please unmount before invoking grml2usb")
594 if os.path.isdir(source):
595 logging.debug("Source %s is not a device, therefore not mounting.", source)
598 logging.debug("mount %s %s %s", mount_options, source, target)
599 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
601 if proc.returncode != 0:
602 raise CriticalException("Error executing mount (no filesystem on the partition?)")
604 logging.debug("register_mountpoint(%s)", target)
605 register_mountpoint(target)
608 def unmount(target, unmount_options):
609 """Unmount specified target
611 @target: target where something is mounted on and which should be unmounted
612 @options: options for umount command"""
614 # make sure we unmount only already mounted targets
615 target_unmount = False
616 mounts = open('/proc/mounts').readlines()
617 mountstring = re.compile(".*%s.*" % re.escape(os.path.realpath(target)))
619 if re.match(mountstring, line):
620 target_unmount = True
622 if not target_unmount:
623 logging.debug("%s not mounted anymore", target)
625 logging.debug("umount %s %s", list(unmount_options), target)
626 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
628 if proc.returncode != 0:
629 raise Exception("Error executing umount")
631 logging.debug("unregister_mountpoint(%s)", target)
632 unregister_mountpoint(target)
635 def check_for_usbdevice(device):
636 """Check whether the specified device is a removable USB device
638 @device: device name, like /dev/sda1 or /dev/sda
641 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
643 usbdev = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
644 if not os.path.isfile(usbdev):
645 # Ubuntu with kernel 2.6.24 for example:
646 usbdev = os.path.realpath('/sys/block/' + usbdevice + '/removable')
648 if os.path.isfile(usbdev):
649 is_usb = open(usbdev).readline()
656 def check_for_fat(partition):
657 """Check whether specified partition is a valid VFAT/FAT16 filesystem
659 @partition: device name of partition"""
661 if not os.access(partition, os.R_OK):
662 raise CriticalException("Failed to read device %s"
663 " (wrong UID/permissions or device/directory not present?)" % partition)
666 udev_info = subprocess.Popen(["/sbin/blkid", "-s", "TYPE", "-o", "value", partition],
667 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
668 filesystem = udev_info.communicate()[0].rstrip()
670 if filesystem != "vfat":
671 raise CriticalException(
672 "Partition %s does not contain a FAT16 filesystem. "
673 "(Use --fat16 or run mkfs.vfat %s)" % (partition, partition))
676 raise CriticalException("Sorry, /sbin/blkid not available (install e2fsprogs?)")
679 def mkdir(directory):
680 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
682 # just silently pass as it's just fine it the directory exists
683 if not os.path.isdir(directory):
685 os.makedirs(directory)
686 # pylint: disable-msg=W0704
691 def exec_rsync(source, target):
692 """Simple wrapper around rsync to install files
694 @source: source file/directory
695 @target: target file/directory"""
696 logging.debug("Source: %s / Target: %s", source, target)
697 proc = subprocess.Popen(["rsync", "-rlptDH", "--inplace", source, target])
699 if proc.returncode == 12:
700 logging.critical("Fatal: No space left on device")
704 if proc.returncode != 0:
705 logging.critical("Fatal: could not install %s", source)
710 def write_uuid(target_file):
711 """Generates an returns uuid and write it to the specified file
713 @target_file: filename to write the uuid to
716 fileh = open(target_file, 'w')
717 uid = str(uuid.uuid4())
723 def get_uuid(target):
724 """Get the uuid of the specified target. Will generate an uuid if none exist.
726 @target: directory/mountpoint containing the grml layout
729 conf_target = target + "/conf/"
730 uuid_file_name = conf_target + "/bootid.txt"
731 if os.path.isdir(conf_target):
732 if os.path.isfile(uuid_file_name):
733 uuid_file = open(uuid_file_name, 'r')
734 uid = uuid_file.readline().strip()
738 return write_uuid(uuid_file_name)
740 execute(mkdir, conf_target)
741 return write_uuid(uuid_file_name)
744 def copy_system_files(grml_flavour, iso_mount, target):
745 """copy grml's main files (like squashfs, kernel and initrd) to a given target
747 @grml_flavour: name of grml flavour the configuration should be generated for
748 @iso_mount: path where a grml ISO is mounted on
749 @target: path where grml's main files should be copied to"""
751 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
753 logging.critical("Fatal: squashfs file not found"
754 ", please check that your iso is not corrupt")
755 raise CriticalException("error locating squashfs file")
757 squashfs_target = target + '/live/' + grml_flavour + '/'
758 execute(mkdir, squashfs_target)
759 exec_rsync(squashfs, squashfs_target + grml_flavour + '.squashfs')
761 for prefix in grml_flavour + "/", "":
762 filesystem_module = search_file(prefix + 'filesystem.module', iso_mount)
763 if filesystem_module:
765 if filesystem_module is None:
766 logging.critical("Fatal: filesystem.module not found")
767 raise CriticalException("error locating filesystem.module file")
769 exec_rsync(filesystem_module, squashfs_target + 'filesystem.module')
771 cleaned_flavour = re.sub(r'[,._-]', '', grml_flavour)
773 if os.path.isdir(iso_mount + '/boot/' + cleaned_flavour):
774 exec_rsync(iso_mount + '/boot/' + cleaned_flavour, target + '/boot')
776 kernel = search_file('vmlinuz', iso_mount)
778 # compat for releases < 2011.12
779 kernel = search_file('linux26', iso_mount)
782 logging.critical("Fatal: kernel not found")
783 raise CriticalException("error locating kernel file")
785 source = os.path.dirname(kernel) + '/'
786 dest = target + '/' + os.path.dirname(kernel).replace(iso_mount,'') + '/'
788 exec_rsync(source, dest)
791 def update_grml_versions(iso_mount, target):
792 """Update the grml version file on a cd
793 Returns true if version was updated successfully,
794 False if grml-version does not exist yet on the mountpoint
796 @iso_mount: string of the iso mount point
797 @target: path of the target mount point
799 grml_target = target + '/grml/'
800 target_grml_version_file = search_file('grml-version', grml_target)
801 if target_grml_version_file:
802 iso_grml_version_file = search_file('grml-version', iso_mount)
803 if not iso_grml_version_file:
804 logging.warn("Warning: %s could not be found - can not install it", iso_grml_version_file)
807 # read the flavours from the iso image
809 iso_file = open(iso_grml_version_file, 'r')
810 for line in iso_file:
811 iso_versions[get_flavour(line)] = line.strip()
813 # update the existing flavours on the target
814 for line in fileinput.input([target_grml_version_file], inplace=1):
815 flavour = get_flavour(line)
816 if flavour in iso_versions.keys():
817 print iso_versions.pop(flavour)
822 target_file = open(target_grml_version_file, 'a')
823 # add the new flavours from the current iso
824 for flavour in iso_versions:
825 target_file.write("%s\n" % iso_versions[flavour])
827 logging.warn("Warning: Could not write file")
835 def copy_grml_files(grml_flavour, iso_mount, target):
836 """copy some minor grml files to a given target
838 @grml_flavour: the current grml_flavour
839 @iso_mount: path where a grml ISO is mounted on
840 @target: path where grml's main files should be copied to"""
842 grml_target = target + '/grml/'
843 execute(mkdir, grml_target)
845 grml_prefixe = ["GRML", "grml"]
846 for prefix in grml_prefixe:
847 filename = "{0}/{1}/{2}".format(iso_mount, prefix, grml_flavour)
848 if os.path.exists(filename):
849 exec_rsync(filename, grml_target)
852 logging.warn("Warning: could not find flavour directory for %s ", grml_flavour)
855 def handle_addon_copy(filename, dst, iso_mount, ignore_errors=False):
856 """handle copy of optional addons
858 @filename: filename of the addon
859 @dst: destination directory
860 @iso_mount: location of the iso mount
861 @ignore_errors: don't report missing files
863 file_location = search_file(filename, iso_mount)
864 if file_location is None:
865 if not ignore_errors:
866 logging.warn("Warning: %s not found (that's fine if you don't need it)", filename)
868 exec_rsync(file_location, dst)
871 def copy_addons(iso_mount, target):
872 """copy grml's addons files (like allinoneimg, bsd4grml,..) to a given target
874 @iso_mount: path where a grml ISO is mounted on
875 @target: path where grml's main files should be copied to"""
877 addons = target + '/boot/addons/'
878 execute(mkdir, addons)
880 # grub all-in-one image
881 handle_addon_copy('allinone.img', addons, iso_mount)
884 handle_addon_copy('bsd4grml', addons, iso_mount)
886 handle_addon_copy('balder10.imz', addons, iso_mount)
888 # install hdt and pci.ids only when using syslinux (grub doesn't support it)
890 # hdt (hardware detection tool) image
891 hdtimg = search_file('hdt.c32', iso_mount)
893 exec_rsync(hdtimg, addons + '/hdt.c32')
896 picids = search_file('pci.ids', iso_mount)
898 exec_rsync(picids, addons + '/pci.ids')
901 handle_addon_copy('memdisk', addons, iso_mount)
904 handle_addon_copy('memtest', addons, iso_mount)
906 # gpxe.lkrn: got replaced by ipxe
907 handle_addon_copy('gpxe.lkrn', addons, iso_mount, ignore_errors=True)
910 handle_addon_copy('ipxe.lkrn', addons, iso_mount)
912 def glob_and_copy(filepattern, dst):
913 """Glob on specified filepattern and copy the result to dst
915 @filepattern: globbing pattern
916 @dst: target directory
918 for name in glob.glob(filepattern):
919 copy_if_exist(name, dst)
921 def search_and_copy(filename, search_path, dst):
922 """Search for the specified filename at searchpath and copy it to dst
924 @filename: filename to look for
925 @search_path: base search file
926 @dst: destionation to copy the file to
928 file_location = search_file(filename, search_path)
929 copy_if_exist(file_location, dst)
931 def copy_if_exist(filename, dst):
932 """Copy filename to dst if filename is set.
934 @filename: a filename
937 if filename and (os.path.isfile(filename) or os.path.isdir(filename)):
938 exec_rsync(filename, dst)
940 def copy_bootloader_files(iso_mount, target, grml_flavour):
941 """Copy grml's bootloader files to a given target
943 @iso_mount: path where a grml ISO is mounted on
944 @target: path where grml's main files should be copied to
945 @grml_flavour: name of the current processed grml_flavour
948 syslinux_target = target + '/boot/syslinux/'
949 execute(mkdir, syslinux_target)
951 grub_target = target + '/boot/grub/'
952 execute(mkdir, grub_target)
954 logo = search_file('logo.16', iso_mount)
955 exec_rsync(logo, syslinux_target + 'logo.16')
957 bootx64_efi = search_file('bootx64.efi', iso_mount)
959 mkdir(target + '/efi/boot/')
960 exec_rsync(bootx64_efi, target + '/efi/boot/bootx64.efi')
962 efi_img = search_file('efi.img', iso_mount)
964 mkdir(target + '/boot/')
965 exec_rsync(efi_img, target + '/boot/efi.img')
967 for ffile in ['f%d' % number for number in range(1, 11) ]:
968 search_and_copy(ffile, iso_mount, syslinux_target + ffile)
970 loopback_cfg = search_file("loopback.cfg", iso_mount)
972 directory = os.path.dirname(loopback_cfg)
973 directory = directory.replace(iso_mount, "")
974 mkdir(os.path.join(target, directory))
975 exec_rsync(loopback_cfg, target + os.path.sep + directory)
977 # avoid the "file is read only, overwrite anyway (y/n) ?" question
978 # of mtools by syslinux ("mmove -D o -D O s:/ldlinux.sys $target_file")
979 if os.path.isfile(syslinux_target + 'ldlinux.sys'):
980 os.unlink(syslinux_target + 'ldlinux.sys')
982 (source_dir, name) = get_defaults_file(iso_mount, grml_flavour, "default.cfg")
983 (source_dir, defaults_file) = get_defaults_file(iso_mount, grml_flavour, "grml.cfg")
986 logging.critical("Fatal: file default.cfg could not be found.")
987 logging.critical("Note: this grml2usb version requires an ISO generated by grml-live >=0.9.24 ...")
988 logging.critical(" ... either use grml releases >=2009.10 or switch to an older grml2usb version.")
991 if not os.path.exists(iso_mount + '/boot/grub/footer.cfg'):
992 logging.warning("Warning: Grml releases older than 2011.12 support only one flavour in grub.")
994 for expr in name, 'distri.cfg', \
995 defaults_file, 'grml.png', 'hd.cfg', 'isolinux.cfg', 'isolinux.bin', \
996 'isoprompt.cfg', 'options.cfg', \
997 'prompt.cfg', 'vesamenu.cfg', 'grml.png', '*.c32':
998 glob_and_copy(iso_mount + source_dir + expr, syslinux_target)
1000 for filename in glob.glob1(syslinux_target, "*.c32"):
1001 copy_if_exist(os.path.join(SYSLINUX_LIBS, filename), syslinux_target)
1004 # copy the addons_*.cfg file to the new syslinux directory
1005 glob_and_copy(iso_mount + source_dir + 'addon*.cfg', syslinux_target)
1007 search_and_copy('hidden.cfg', iso_mount + source_dir, syslinux_target + "new_" + 'hidden.cfg')
1009 # copy all grub files from ISO
1010 glob_and_copy(iso_mount + '/boot/grub/*', grub_target)
1012 def install_iso_files(grml_flavour, iso_mount, device, target):
1013 """Copy files from ISO to given target
1015 @grml_flavour: name of grml flavour the configuration should be generated for
1016 @iso_mount: path where a grml ISO is mounted on
1017 @device: device/partition where bootloader should be installed to
1018 @target: path where grml's main files should be copied to"""
1021 GRML_DEFAULT = GRML_DEFAULT or grml_flavour
1024 elif not options.bootloaderonly:
1025 logging.info("Copying files. This might take a while....")
1027 copy_system_files(grml_flavour, iso_mount, target)
1028 copy_grml_files(grml_flavour, iso_mount, target)
1029 except CriticalException, error:
1030 logging.critical("Execution failed: %s", error)
1033 if not options.skipaddons:
1034 if not search_file('addons', iso_mount):
1035 logging.info("Could not find addons, therefore not installing.")
1037 copy_addons(iso_mount, target)
1039 if not options.copyonly:
1040 copy_bootloader_files(iso_mount, target, grml_flavour)
1042 if not options.dryrun:
1043 handle_bootloader_config(grml_flavour, device, target)
1045 # make sure we sync filesystems before returning
1046 proc = subprocess.Popen(["sync"])
1050 def get_flavour(flavour_str):
1051 """Returns the flavour of a grml version string
1053 return re.match(r'[\w-]*', flavour_str).group()
1055 def identify_grml_flavour(mountpath):
1056 """Get name of grml flavour
1058 @mountpath: path where the grml ISO is mounted to
1059 @return: name of grml-flavour"""
1061 version_file = search_file('grml-version', mountpath)
1063 if version_file == "":
1064 logging.critical("Error: could not find grml-version file.")
1070 tmpfile = open(version_file, 'r')
1071 for line in tmpfile.readlines():
1072 flavours.append(get_flavour(line))
1073 except TypeError, e:
1075 except Exception, e:
1076 logging.critical("Unexpected error: %s", e)
1085 def get_bootoptions(grml_flavour):
1086 """Returns bootoptions for specific flavour
1088 @grml_flavour: name of the grml_flavour
1090 # do NOT write "None" in kernel cmdline
1091 if not options.bootoptions:
1094 bootopt = " ".join(options.bootoptions)
1095 bootopt = bootopt.replace("%flavour", grml_flavour)
1099 def handle_grub_config(grml_flavour, device, target):
1100 """Main handler for generating grub (v1 and v2) configuration
1102 @grml_flavour: name of grml flavour the configuration should be generated for
1103 @device: device/partition where grub should be installed to
1104 @target: path of grub's configuration files"""
1108 logging.debug("Updating grub configuration")
1110 grub_target = target + '/boot/grub/'
1112 bootid_re = re.compile("bootid=[\w_-]+")
1113 live_media_path_re = re.compile("live-media-path=[\w_/-]+")
1115 bootopt = get_bootoptions(grml_flavour)
1118 option_re = re.compile(r'(.*/boot/.*(linux26|vmlinuz).*)')
1120 if options.removeoption:
1121 for regex in options.removeoption:
1122 remove_regexes.append(re.compile(regex))
1124 for filename in glob.glob(grub_target + grml_flavour + '*.cfg'):
1125 for line in fileinput.input(filename, inplace=1):
1126 line = line.rstrip("\r\n")
1127 if option_re.search(line):
1128 line = bootid_re.sub('', line)
1129 line = live_media_path_re.sub('', line)
1130 line = line.rstrip() + r' live-media-path=/live/%s/ bootid=%s %s ' % (grml_flavour, UUID, bootopt)
1131 for regex in remove_regexes:
1132 line = regex.sub(' ', line)
1137 def initial_syslinux_config(target):
1138 """Generates intial syslinux configuration
1140 @target path of syslinux's configuration files"""
1142 target = target + "/"
1143 filename = target + "grmlmain.cfg"
1144 if os.path.isfile(target + "grmlmain.cfg"):
1146 data = open(filename, "w")
1147 data.write(generate_main_syslinux_config())
1150 filename = target + "hiddens.cfg"
1151 data = open(filename, "w")
1152 data.write("include hidden.cfg\n")
1155 def add_entry_if_not_present(filename, entry):
1156 """Write entry into filename if entry is not already in the file
1158 @filanme: name of the file
1159 @entry: data to write to the file
1161 data = open(filename, "a+")
1170 def get_flavour_filename(flavour):
1171 """Generate a iso9960 save filename out of the specified flavour
1173 @flavour: grml flavour
1175 return flavour.replace('-', '_')
1177 def adjust_syslinux_bootoptions(src, flavour):
1178 """Adjust existing bootoptions of specified syslinux config to
1179 grml2usb specific ones, e.g. change the location of the kernel...
1181 @src: config file to alter
1182 @flavour: grml flavour
1185 append_re = re.compile("^(\s*append.*/boot/.*)$", re.I)
1186 # flavour_re = re.compile("(label.*)(grml\w+)")
1187 default_re = re.compile("(default.cfg)")
1188 bootid_re = re.compile("bootid=[\w_-]+")
1189 live_media_path_re = re.compile("live-media-path=[\w_/-]+")
1191 bootopt = get_bootoptions(flavour)
1195 if options.removeoption:
1196 option_re = re.compile(r'/boot/.*/(initrd.gz|initrd.img)')
1198 for regex in options.removeoption:
1199 regexe.append(re.compile(r'%s' % regex))
1201 for line in fileinput.input(src, inplace=1):
1202 # line = flavour_re.sub(r'\1 %s-\2' % flavour, line)
1203 line = default_re.sub(r'%s-\1' % flavour, line)
1204 line = bootid_re.sub('', line)
1205 line = live_media_path_re.sub('', line)
1206 line = append_re.sub(r'\1 live-media-path=/live/%s/ ' % flavour, line)
1207 line = append_re.sub(r'\1 boot=live %s ' % bootopt, line)
1208 line = append_re.sub(r'\1 %s=%s ' % ("bootid", UUID), line)
1209 if option_re and option_re.search(line):
1210 for regex in regexe:
1211 line = regex.sub(' ', line)
1212 sys.stdout.write(line)
1215 def adjust_labels(src, replacement):
1216 """Adjust the specified labels in the syslinux config file src with
1217 specified replacement
1219 label_re = re.compile("^(\s*label\s*) ([a-zA-Z0-9_-]+)", re.I)
1220 for line in fileinput.input(src, inplace=1):
1221 line = label_re.sub(replacement, line)
1222 sys.stdout.write(line)
1226 def add_syslinux_entry(filename, grml_flavour):
1227 """Add includes for a specific grml_flavour to the specified filename
1229 @filename: syslinux config file
1230 @grml_flavour: grml flavour to add
1233 entry_filename = "option_%s.cfg" % grml_flavour
1234 entry = "include %s\n" % entry_filename
1236 add_entry_if_not_present(filename, entry)
1237 path = os.path.dirname(filename)
1239 data = open(path + "/" + entry_filename, "w")
1240 data.write(generate_flavour_specific_syslinux_config(grml_flavour))
1243 def modify_filenames(grml_flavour, target, filenames):
1244 """Replace the standard filenames with the new ones
1246 @grml_flavour: grml-flavour strin
1247 @target: directory where the files are located
1248 @filenames: list of filenames to alter
1250 grml_filename = grml_flavour.replace('-', '_')
1251 for filename in filenames:
1252 old_filename = "%s/%s" % (target, filename)
1253 new_filename = "%s/%s_%s" % (target, grml_filename, filename)
1254 os.rename(old_filename, new_filename)
1257 def remove_default_entry(filename):
1258 """Remove the default entry from specified syslinux file
1260 @filename: syslinux config file
1262 default_re = re.compile("^(\s*menu\s*default\s*)$", re.I)
1263 for line in fileinput.input(filename, inplace=1):
1264 if default_re.match(line):
1266 sys.stdout.write(line)
1270 def handle_syslinux_config(grml_flavour, target):
1271 """Main handler for generating syslinux configuration
1273 @grml_flavour: name of grml flavour the configuration should be generated for
1274 @target: path of syslinux's configuration files"""
1276 logging.debug("Generating syslinux configuration")
1277 syslinux_target = target + '/boot/syslinux/'
1278 # should be present via copy_bootloader_files(), but make sure it exits:
1279 execute(mkdir, syslinux_target)
1280 syslinux_cfg = syslinux_target + 'syslinux.cfg'
1283 # install main configuration only *once*, no matter how many ISOs we have:
1284 syslinux_config_file = open(syslinux_cfg, 'w')
1285 syslinux_config_file.write("TIMEOUT 300\n")
1286 syslinux_config_file.write("include vesamenu.cfg\n")
1287 syslinux_config_file.close()
1289 prompt_name = open(syslinux_target + 'promptname.cfg', 'w')
1290 prompt_name.write('menu label S^yslinux prompt\n')
1293 initial_syslinux_config(syslinux_target)
1294 flavour_filename = grml_flavour.replace('-', '_')
1296 if search_file('default.cfg', syslinux_target):
1297 modify_filenames(grml_flavour, syslinux_target, ['grml.cfg', 'default.cfg'])
1299 filename = search_file("new_hidden.cfg", syslinux_target)
1302 # process hidden file
1303 if not search_file("hidden.cfg", syslinux_target):
1304 new_hidden = syslinux_target + "hidden.cfg"
1305 os.rename(filename, new_hidden)
1306 adjust_syslinux_bootoptions(new_hidden, grml_flavour)
1308 new_hidden_file = "%s/%s_hidden.cfg" % (syslinux_target, flavour_filename)
1309 os.rename(filename, new_hidden_file)
1310 adjust_labels(new_hidden_file, r'\1 %s-\2' % grml_flavour)
1311 adjust_syslinux_bootoptions(new_hidden_file, grml_flavour)
1312 entry = 'include %s_hidden.cfg\n' % flavour_filename
1313 add_entry_if_not_present("%s/hiddens.cfg" % syslinux_target, entry)
1317 new_default = "%s_default.cfg" % (flavour_filename)
1318 entry = 'include %s\n' % new_default
1319 defaults_file = '%s/defaults.cfg' % syslinux_target
1320 new_default_with_path = "%s/%s" % (syslinux_target, new_default)
1321 new_grml_cfg = "%s/%s_grml.cfg" % (syslinux_target, flavour_filename)
1323 if os.path.isfile(defaults_file):
1325 # remove default menu entry in menu
1326 remove_default_entry(new_default_with_path)
1328 # adjust all labels for additional isos
1329 adjust_labels(new_default_with_path, r'\1 %s' % grml_flavour)
1330 adjust_labels(new_grml_cfg, r'\1 %s-\2' % grml_flavour)
1332 # always adjust bootoptions
1333 adjust_syslinux_bootoptions(new_default_with_path, grml_flavour)
1334 adjust_syslinux_bootoptions(new_grml_cfg, grml_flavour)
1336 add_entry_if_not_present("%s/defaults.cfg" % syslinux_target, entry)
1338 add_syslinux_entry("%s/additional.cfg" % syslinux_target, flavour_filename)
1341 def handle_bootloader_config(grml_flavour, device, target):
1342 """Main handler for generating bootloader's configuration
1344 @grml_flavour: name of grml flavour the configuration should be generated for
1345 @device: device/partition where bootloader should be installed to
1346 @target: path of bootloader's configuration files"""
1349 UUID = get_uuid(target)
1350 if options.skipsyslinuxconfig:
1351 logging.info("Skipping generation of syslinux configuration as requested.")
1354 handle_syslinux_config(grml_flavour, target)
1355 except CriticalException, error:
1356 logging.critical("Fatal: %s", error)
1359 if options.skipgrubconfig:
1360 logging.info("Skipping generation of grub configuration as requested.")
1363 handle_grub_config(grml_flavour, device, target)
1364 except CriticalException, error:
1365 logging.critical("Fatal: %s", error)
1370 def install(image, device):
1371 """Install a grml image to the specified device
1373 @image: directory or is file
1374 @device: partition or directory to install the device
1376 iso_mountpoint = image
1377 remove_image_mountpoint = False
1378 if os.path.isdir(image):
1379 logging.info("Using %s as install base", image)
1381 logging.info("Using ISO %s", image)
1382 iso_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
1383 register_tmpfile(iso_mountpoint)
1384 remove_image_mountpoint = True
1386 mount(image, iso_mountpoint, ["-o", "loop,ro", "-t", "iso9660"])
1387 except CriticalException, error:
1388 logging.critical("Fatal: %s", error)
1392 install_grml(iso_mountpoint, device)
1394 if remove_image_mountpoint:
1396 remove_mountpoint(iso_mountpoint)
1397 except CriticalException, error:
1398 logging.critical("Fatal: %s", error)
1403 def install_grml(mountpoint, device):
1404 """Main logic for copying files of the currently running grml system.
1406 @mountpoin: directory where currently running live system resides (usually /live/image)
1407 @device: partition where the specified ISO should be installed to"""
1409 device_mountpoint = device
1410 if os.path.isdir(device):
1411 logging.info("Specified device is not a directory, therefore not mounting.")
1412 remove_device_mountpoint = False
1414 device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
1415 register_tmpfile(device_mountpoint)
1416 remove_device_mountpoint = True
1418 check_for_fat(device)
1419 mount(device, device_mountpoint, ['-o', 'utf8,iocharset=iso8859-1'])
1420 except CriticalException, error:
1422 mount(device, device_mountpoint, "")
1423 except CriticalException, error:
1424 logging.critical("Fatal: %s", error)
1427 grml_flavours = identify_grml_flavour(mountpoint)
1428 for flavour in set(grml_flavours):
1430 logging.warning("No valid flavour found, please check your iso")
1431 logging.info("Identified grml flavour \"%s\".", flavour)
1432 install_iso_files(flavour, mountpoint, device, device_mountpoint)
1433 GRML_FLAVOURS.add(flavour)
1435 if remove_device_mountpoint:
1436 remove_mountpoint(device_mountpoint)
1438 def remove_mountpoint(mountpoint):
1439 """remove a registred mountpoint
1443 unmount(mountpoint, "")
1444 if os.path.isdir(mountpoint):
1445 os.rmdir(mountpoint)
1446 unregister_tmpfile(mountpoint)
1447 except CriticalException, error:
1448 logging.critical("Fatal: %s", error)
1451 def handle_mbr(device):
1452 """Main handler for installing master boot record (MBR)
1454 @device: device where the MBR should be installed to"""
1457 logging.info("Would install MBR")
1460 if device[-1:].isdigit():
1461 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
1462 partition_number = int(device[-1:]) - 1
1464 logging.warn("Could not detect partition number, not activating partition")
1465 partition_number = None
1467 # if we get e.g. /dev/loop1 as device we don't want to put the MBR
1468 # into /dev/loop of course, therefore use /dev/loop1 as mbr_device
1469 if mbr_device == "/dev/loop":
1471 logging.info("Detected loop device - using %s as MBR device therefore", mbr_device)
1473 mbrcode = GRML2USB_BASE + '/mbr/mbrldr'
1474 if options.syslinuxmbr:
1475 mbrcode = '/usr/lib/syslinux/mbr.bin'
1476 elif options.mbrmenu:
1477 mbrcode = GRML2USB_BASE + '/mbr/mbrldr'
1480 install_mbr(mbrcode, mbr_device, partition_number, True)
1481 except IOError, error:
1482 logging.critical("Execution failed: %s", error)
1484 except Exception, error:
1485 logging.critical("Execution failed: %s", error)
1489 def handle_vfat(device):
1490 """Check for FAT specific settings and options
1492 @device: device that should checked / formated"""
1494 # make sure we have mkfs.vfat available
1496 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
1497 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
1498 logging.critical('Please make sure to install dosfstools.')
1502 print "Forcing mkfs.fat16 on %s as requested via option --force." % device
1504 # make sure the user is aware of what he is doing
1505 f = raw_input("Are you sure you want to format the specified partition with fat16? y/N ")
1506 if f == "y" or f == "Y":
1507 logging.info("Note: you can skip this question using the option --force")
1512 except CriticalException, error:
1513 logging.critical("Execution failed: %s", error)
1516 # check for vfat filesystem
1517 if device is not None and not os.path.isdir(device) and options.syslinux:
1519 check_for_fat(device)
1520 except CriticalException, error:
1521 logging.critical("Execution failed: %s", error)
1524 if not os.path.isdir(device) and not check_for_usbdevice(device) and not options.force:
1525 print "Warning: the specified device %s does not look like a removable usb device." % device
1526 f = raw_input("Do you really want to continue? y/N ")
1527 if f == "y" or f == "Y":
1533 def handle_compat_warning(device):
1534 """Backwards compatible checks
1536 @device: device that should be checked"""
1538 # make sure we can replace old grml2usb script and warn user when using old way of life:
1539 if device.startswith("/media/external") or device.startswith("/media/usb") or \
1540 device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1541 print "Warning: the semantics of grml2usb has changed."
1542 print "Instead of using grml2usb /path/to/iso %s you might" % device
1543 print "want to use grml2usb /path/to/iso /dev/... instead."
1544 print "Please check out the grml2usb manpage for details."
1545 f = raw_input("Do you really want to continue? y/N ")
1546 if f == "y" or f == "Y":
1552 def handle_logging():
1553 """Log handling and configuration"""
1555 if options.verbose and options.quiet:
1556 parser.error("please use either verbose (--verbose) or quiet (--quiet) option")
1559 FORMAT = "Debug: %(asctime)-15s %(message)s"
1560 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1562 FORMAT = "Critical: %(message)s"
1563 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1565 FORMAT = "%(message)s"
1566 logging.basicConfig(level=logging.INFO, format=FORMAT)
1569 def handle_bootloader(device):
1570 """wrapper for installing bootloader
1572 @device: device where bootloader should be installed to"""
1574 # Install bootloader only if not using the --copy-only option
1575 if options.copyonly:
1576 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1577 elif os.path.isdir(device):
1578 logging.info("Not installing bootloader as %s is a directory.", device)
1580 install_bootloader(device)
1583 def check_options(opts):
1584 """Check compability of provided user opts
1586 @opts option dict from OptionParser
1588 if opts.grubmbr and not opts.grub:
1589 logging.critical("Error: --grub-mbr requires --grub option.")
1593 def check_programs():
1594 """check if all needed programs are installed"""
1596 if not which("grub-install"):
1597 logging.critical("Fatal: grub-install not available (please install the "
1598 + "grub package or drop the --grub option)")
1601 if options.syslinux:
1602 if not which("syslinux"):
1603 logging.critical("Fatal: syslinux not available (please install the "
1604 + "syslinux package or use the --grub option)")
1607 if not which("rsync"):
1608 logging.critical("Fatal: rsync not available, can not continue - sorry.")
1612 """Runs modprobe loop and throws away it's output"""
1613 proc = subprocess.Popen(["modprobe", "loop"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1617 """Main function [make pylint happy :)]"""
1620 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1624 parser.error("invalid usage")
1629 # make sure we have the appropriate permissions
1632 check_options(options)
1636 logging.info("Executing grml2usb version %s", PROG_VERSION)
1639 logging.info("Running in simulation mode as requested via option dry-run.")
1643 # specified arguments
1644 device = os.path.realpath(args[len(args) - 1])
1645 isos = args[0:len(args) - 1]
1647 if not os.path.isdir(device):
1648 if device[-1:].isdigit():
1649 if int(device[-1:]) > 4 or device[-2:].isdigit():
1650 logging.critical("Fatal: installation on partition number >4 not supported. (BIOS won't support it.)")
1653 # provide upgrade path
1654 handle_compat_warning(device)
1656 # check for vfat partition
1659 # main operation (like installing files)
1661 install(iso, device)
1664 is_superfloppy = not device[-1:].isdigit()
1666 logging.info("Detected superfloppy format - not installing MBR")
1668 if not options.skipmbr and not os.path.isdir(device) and not is_superfloppy:
1671 handle_bootloader(device)
1673 logging.info("Note: grml flavour %s was installed as the default booting system.", GRML_DEFAULT)
1675 for flavour in GRML_FLAVOURS:
1676 logging.info("Note: you can boot flavour %s using '%s' on the commandline.", flavour, flavour)
1678 # finally be politely :)
1679 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system.", PROG_VERSION)
1682 if __name__ == "__main__":
1685 except KeyboardInterrupt:
1686 logging.info("Received KeyboardInterrupt")
1689 ## END OF FILE #################################################################
1690 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8