2 # -*- coding: utf-8 -*-
7 This script installs a grml system (either a running system or ISO[s]) to a USB device
9 :copyright: (c) 2009 by Michael Prokop <mika@grml.org>
10 :license: GPL v2 or any later version
11 :bugreports: http://grml.org/bugs/
15 from __future__ import with_statement
16 from optparse import OptionParser
17 from inspect import isroutine, isclass
18 import datetime, logging, os, re, subprocess, sys, tempfile, time
21 PROG_VERSION = "0.9.2(pre1)"
22 MOUNTED = set() # register mountpoints
23 TMPFILES = set() # register tmpfiles
24 DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
27 USAGE = "Usage: %prog [options] <[ISO[s] | /live/image]> </dev/sdX#>\n\
29 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
30 Make sure you have at least one grml ISO or a running grml system (/live/image),\n\
31 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
32 and root access. Further information can be found in: man grml2usb"
34 # pylint: disable-msg=C0103
35 parser = OptionParser(usage=USAGE)
36 parser.add_option("--bootoptions", dest="bootoptions",
37 action="store", type="string",
38 help="use specified bootoptions as default")
39 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
40 help="do not copy files but just install a bootloader")
41 parser.add_option("--copy-only", dest="copyonly", action="store_true",
42 help="copy files only but do not install bootloader")
43 parser.add_option("--dry-run", dest="dryrun", action="store_true",
44 help="avoid executing commands")
45 parser.add_option("--fat16", dest="fat16", action="store_true",
46 help="format specified partition with FAT16")
47 parser.add_option("--force", dest="force", action="store_true",
48 help="force any actions requiring manual interaction")
49 parser.add_option("--grub", dest="grub", action="store_true",
50 help="install grub bootloader instead of syslinux")
51 parser.add_option("--initrd", dest="initrd", action="store", type="string",
52 help="install specified initrd instead of the default [TODO]")
53 parser.add_option("--kernel", dest="kernel", action="store", type="string",
54 help="install specified kernel instead of the default [TODO]")
55 parser.add_option("--lilo", dest="lilo", action="store", type="string",
56 help="lilo executable to be used for installing MBR")
57 parser.add_option("--quiet", dest="quiet", action="store_true",
58 help="do not output anything but just errors on console")
59 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
60 help="do not install /boot/addons/ files")
61 parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
62 help="do not install a master boot record (MBR) on the device")
63 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
64 help="install specified squashfs file instead of the default [TODO]")
65 parser.add_option("--uninstall", dest="uninstall", action="store_true",
66 help="remove grml ISO files from specified device [TODO]")
67 parser.add_option("--verbose", dest="verbose", action="store_true",
68 help="enable verbose mode")
69 parser.add_option("-v", "--version", dest="version", action="store_true",
70 help="display version and exit")
71 (options, args) = parser.parse_args()
74 class CriticalException(Exception):
75 """Throw critical exception if the exact error is not known but fatal."
77 @Exception: message"""
82 """Cleanup function to make sure there aren't any mounted devices left behind.
85 logging.info("Cleaning up before exiting...")
86 proc = subprocess.Popen(["sync"])
90 for device in MOUNTED:
92 # ignore: RuntimeError: Set changed size during iteration
94 logging.debug('caught expection RuntimeError, ignoring')
97 def register_tmpfile(path):
104 def unregister_tmpfile(path):
109 TMPFILES.remove(path)
112 def register_mountpoint(target):
119 def unregister_mountpoint(target):
123 if target in MOUNTED:
124 MOUNTED.remove(target)
127 def get_function_name(obj):
128 """Helper function for use in execute() to retrive name of a function
130 @obj: the function object
132 if not (isroutine(obj) or isclass(obj)):
134 return obj.__module__ + '.' + obj.__name__
137 def execute(f, *exec_arguments):
138 """Wrapper for executing a command. Either really executes
139 the command (default) or when using --dry-run commandline option
140 just displays what would be executed."""
141 # usage: execute(subprocess.Popen, (["ls", "-la"]))
142 # TODO: doesn't work for proc = execute(subprocess.Popen...() -> any ideas?
144 # pylint: disable-msg=W0141
145 logging.debug('dry-run only: %s(%s)' % (get_function_name(f), ', '.join(map(repr, exec_arguments))))
147 # pylint: disable-msg=W0142
148 return f(*exec_arguments)
152 """Check whether a given file can be executed
154 @fpath: full path to file
156 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
160 """Check whether a given program is available in PATH
162 @program: name of executable"""
163 fpath = os.path.split(program)[0]
168 for path in os.environ["PATH"].split(os.pathsep):
169 exe_file = os.path.join(path, program)
176 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
177 """Given a search path, find file
179 @filename: name of file to search for
180 @search_path: path where searching for the specified filename"""
182 paths = search_path.split(os.pathsep)
183 current_dir = '' # make pylint happy :)
185 # pylint: disable-msg=W0612
186 for current_dir, directories, files in os.walk(path):
187 if os.path.exists(os.path.join(current_dir, filename)):
191 return os.path.abspath(os.path.join(current_dir, filename))
196 def check_uid_root():
197 """Check for root permissions"""
198 if not os.geteuid()==0:
199 sys.exit("Error: please run this script with uid 0 (root).")
202 def mkfs_fat16(device):
203 """Format specified device with VFAT/FAT16 filesystem.
205 @device: partition that should be formated"""
207 # syslinux -d boot/isolinux /dev/sdb1
208 logging.info("Formating partition with fat16 filesystem")
209 logging.debug("mkfs.vfat -F 16 %s" % device)
210 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
212 if proc.returncode != 0:
213 raise Exception("error executing mkfs.vfat")
216 def generate_main_grub2_config(grml_flavour, install_partition, bootoptions):
217 """Generate grub2 configuration for use via grub.cfg
221 @grml_flavour: name of grml flavour the configuration should be generated for"""
223 local_datestamp = DATESTAMP
232 if background_image (hd0, %(install_partition)s)/boot/grub/grml.png ; then
233 set color_normal=black/black
234 set color_highlight=magenta/black
236 set menu_color_normal=cyan/blue
237 set menu_color_highlight=white/blue
240 ## main grub2 configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
241 menuentry "%(grml_flavour)s (default)" {
242 set root=(hd0,%(install_partition)s)
243 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s %(bootoptions)s
244 initrd /boot/release/%(grml_flavour)s/initrd.gz
247 menuentry "Memory test (memtest86+)" {
248 linux /boot/addons/memtest
251 menuentry "Grub - all in one image" {
252 linux /boot/addons/memdisk
253 initrd /boot/addons/allinone.img
256 menuentry "FreeDOS" {
257 linux /boot/addons/memdisk
258 initrd /boot/addons/balder10.imz
261 #menuentry "Operating System on first partition of first disk" {
266 #menuentry "Operating System on second partition of first disk" {
271 #menuentry "Operating System on first partition of second disk" {
275 #menuentry "Operating System on second partition of second disk" {
280 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions, 'install_partition': install_partition } )
283 def generate_flavour_specific_grub2_config(grml_flavour, install_partition, bootoptions):
284 """Generate grub2 configuration for use via grub.cfg
288 @grml_flavour: name of grml flavour the configuration should be generated for"""
290 local_datestamp = DATESTAMP
293 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
294 menuentry "%(grml_flavour)s" {
295 set root=(hd0,%(install_partition)s)
296 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
297 initrd /boot/release/%(grml_flavour)s/initrd.gz
300 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
301 menuentry "%(grml_flavour)s2ram" {
302 set root=(hd0,%(install_partition)s)
303 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s toram=%(grml_flavour)s %(bootoptions)s
304 initrd /boot/release/%(grml_flavour)s/initrd.gz
306 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
307 menuentry "%(grml_flavour)s-debug" {
308 set root=(hd0,%(install_partition)s)
309 linux /boot/release/%(grml_flavour)s/linux26
310 initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s debug boot=live initcall_debug%(bootoptions)s
313 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
314 menuentry "%(grml_flavour)s-x" {
315 set root=(hd0,%(install_partition)s)
316 linux /boot/release/%(grml_flavour)s/linux26
317 initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s startx=wm-ng %(bootoptions)s
320 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
321 menuentry "%(grml_flavour)s-nofb" {
322 set root=(hd0,%(install_partition)s)
323 linux /boot/release/%(grml_flavour)s/linux26
324 initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=ofonly %(bootoptions)s
327 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
328 menuentry "%(grml_flavour)s-failsafe" {
329 set root=(hd0,%(install_partition)s)
330 linux /boot/release/%(grml_flavour)s/linux26
331 initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal lang=us boot=live noautoconfig atapicd noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia maxcpus=1 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm %(bootoptions)s
334 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
335 menuentry "%(grml_flavour)s-forensic" {
336 set root=(hd0,%(install_partition)s)
337 linux /boot/release/%(grml_flavour)s/linux26
338 initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s nofstab noraid nolvm noautoconfig noswap raid=noautodetect %(bootoptions)s
341 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
342 menuentry "%(grml_flavour)s-serial" {
343 set root=(hd0,%(install_partition)s)
344 linux /boot/release/%(grml_flavour)s/linux26
345 initrd /boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
348 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions, 'install_partition': install_partition } )
351 def generate_grub1_config(grml_flavour, install_partition, bootoptions):
352 """Generate grub1 configuration for use via menu.lst
354 @grml_flavour: name of grml flavour the configuration should be generated for"""
356 local_datestamp = DATESTAMP
361 # color red/blue green/black
362 splashimage=/boot/grub/splash.xpm.gz
367 title %(grml_flavour)s - Default boot (using 1024x768 framebuffer)
368 kernel /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s
369 initrd /boot/release/%(grml_flavour)s/initrd.gz
371 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
374 def generate_isolinux_splash(grml_flavour):
375 """Generate bootsplash for isolinux/syslinux
377 @grml_flavour: name of grml flavour the configuration should be generated for"""
379 # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
381 grml_name = grml_flavour
384 \ f17
\f\18/boot/syslinux/logo.16
386 Some information and boot options available via keys F2 - F10. http://grml.org/
388 """ % {'grml_name': grml_name} )
391 def generate_main_syslinux_config(grml_flavour, bootoptions):
392 """Generate main configuration for use in syslinux.cfg
394 @grml_flavour: name of grml flavour the configuration should be generated for
395 @bootoptions: bootoptions that should be used as a default"""
397 local_datestamp = DATESTAMP
400 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
401 # use this to control the bootup via a serial port
406 DISPLAY /boot/syslinux/boot.msg
407 F1 /boot/syslinux/boot.msg
416 F10 /boot/syslinux/f10
417 ## end of main configuration
419 ## global configuration
420 # the default option (using %(grml_flavour)s)
422 KERNEL /boot/release/%(grml_flavour)s/linux26
423 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
427 KERNEL /boot/addons/memtest
432 KERNEL /boot/addons/memdisk
433 APPEND initrd=/boot/addons/allinone.img
438 KERNEL /boot/addons/memdisk
439 APPEND initrd=/boot/addons/balder10.imz
441 ## end of global configuration
442 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
445 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
446 """Generate flavour specific configuration for use in syslinux.cfg
448 @grml_flavour: name of grml flavour the configuration should be generated for
449 @bootoptions: bootoptions that should be used as a default"""
451 local_datestamp = DATESTAMP
455 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
456 LABEL %(grml_flavour)s
457 KERNEL /boot/release/%(grml_flavour)s/linux26
458 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
460 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
461 LABEL %(grml_flavour)s2ram
462 KERNEL /boot/release/%(grml_flavour)s/linux26
463 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s toram=%(grml_flavour)s %(bootoptions)s
465 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
466 LABEL %(grml_flavour)s-debug
467 KERNEL /boot/release/%(grml_flavour)s/linux26
468 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s debug boot=live initcall_debug%(bootoptions)s
470 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
471 LABEL %(grml_flavour)s-x
472 KERNEL /boot/release/%(grml_flavour)s/linux26
473 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s startx=wm-ng %(bootoptions)s
475 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
476 LABEL %(grml_flavour)s-nofb
477 KERNEL /boot/release/%(grml_flavour)s/linux26
478 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=ofonly %(bootoptions)s
480 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
481 LABEL %(grml_flavour)s-failsafe
482 KERNEL /boot/release/%(grml_flavour)s/linux26
483 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal lang=us boot=live noautoconfig atapicd noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia maxcpus=1 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm %(bootoptions)s
485 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
486 LABEL %(grml_flavour)s-forensic
487 KERNEL /boot/release/%(grml_flavour)s/linux26
488 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s nofstab noraid nolvm noautoconfig noswap raid=noautodetect %(bootoptions)s
490 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
491 LABEL %(grml_flavour)s-serial
492 KERNEL /boot/release/%(grml_flavour)s/linux26
493 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
494 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
497 def install_grub(device):
498 """Install grub on specified device.
500 @mntpoint: mountpoint of device where grub should install its files to
501 @device: partition where grub should be installed to"""
504 logging.info("Would execute grub-install [--root-directory=mount_point] %s now.", device)
506 device_mountpoint = tempfile.mkdtemp()
507 register_tmpfile(device_mountpoint)
509 mount(device, device_mountpoint, "")
510 logging.debug("grub-install --root-directory=%s %s", device_mountpoint, device)
511 proc = subprocess.Popen(["grub-install", "--root-directory=%s" % device_mountpoint, device])
513 if proc.returncode != 0:
514 raise Exception("error executing grub-install")
515 except CriticalException, error:
516 logging.critical("Fatal: %s" % error)
521 unmount(device_mountpoint, "")
522 os.rmdir(device_mountpoint)
523 unregister_tmpfile(device_mountpoint)
526 def install_syslinux(device):
527 """Install syslinux on specified device.
529 @device: partition where syslinux should be installed to"""
532 logging.info("Would install syslinux as bootloader on %s", device)
535 # syslinux -d boot/isolinux /dev/sdb1
536 logging.info("Installing syslinux as bootloader")
537 logging.debug("syslinux -d boot/syslinux %s" % device)
538 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
540 if proc.returncode != 0:
541 raise CriticalException("Error executing syslinux (either try --fat16 or --grub?)")
544 def install_bootloader(device):
545 """Install bootloader on specified device.
547 @device: partition where bootloader should be installed to"""
549 # Install bootloader on the device (/dev/sda),
550 # not on the partition itself (/dev/sda1)?
551 #if partition[-1:].isdigit():
552 # device = re.match(r'(.*?)\d*$', partition).group(1)
560 install_syslinux(device)
561 except CriticalException, error:
562 logging.critical("Fatal: %s" % error)
567 def install_lilo_mbr(lilo, device):
570 # TODO: check out the *real* difference between:
571 # * mbr-install /dev/ice
572 # * lilo -S /dev/null -M /dev/ice ext && lilo -S /dev/null -A /dev/ice 1
573 # * cat /usr/lib/syslinux/mbr.bin > /dev/ice
574 # * syslinux -sf /dev/iceX
577 # to support -A for extended partitions:
578 logging.info("Installing MBR")
579 logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
580 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
582 if proc.returncode != 0:
583 raise Exception("error executing lilo")
585 # activate partition:
586 logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
587 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
589 if proc.returncode != 0:
590 raise Exception("error executing lilo")
593 def install_syslinux_mbr(device):
596 # lilo's mbr is broken, use the one from syslinux instead:
597 if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
598 raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
600 logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
602 # TODO -> use Popen instead?
603 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
605 logging.critical("Error copying MBR to device (%s)" % retcode)
606 except OSError, error:
607 logging.critical("Execution failed:", error)
610 def install_mbr(device):
611 """Install a default master boot record on given device
613 @device: device where MBR should be installed to"""
615 if not is_writeable(device):
616 raise IOError("device not writeable for user")
618 # try to use system's lilo
622 # otherwise fall back to our static version
623 from platform import architecture
624 if architecture()[0] == '64bit':
625 lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
627 lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
628 # finally prefer a specified lilo executable
633 raise Exception("lilo executable can not be execute")
636 logging.info("Would install MBR running lilo and using syslinux.")
639 install_lilo_mbr(lilo, device)
640 install_syslinux_mbr(device)
643 def is_writeable(device):
644 """Check if the device is writeable for the current user
646 @device: partition where bootloader should be installed to"""
650 #raise Exception("no device for checking write permissions")
652 if not os.path.exists(device):
655 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
658 def mount(source, target, mount_options):
659 """Mount specified source on given target
661 @source: name of device/ISO that should be mounted
662 @target: directory where the ISO should be mounted to
663 @options: mount specific options"""
665 # notice: options.dryrun does not work here, as we have to
666 # locate files and identify the grml flavour
667 logging.debug("mount %s %s %s" % (mount_options, source, target))
668 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
670 if proc.returncode != 0:
671 raise CriticalException("Error executing mount")
673 logging.debug("register_mountpoint(%s)" % target)
674 register_mountpoint(target)
677 def unmount(target, unmount_options):
678 """Unmount specified target
680 @target: target where something is mounted on and which should be unmounted
681 @options: options for umount command"""
683 # make sure we unmount only already mounted targets
684 target_unmount = False
685 mounts = open('/proc/mounts').readlines()
686 mountstring = re.compile(".*%s.*" % re.escape(target))
688 if re.match(mountstring, line):
689 target_unmount = True
691 if not target_unmount:
692 logging.debug("%s not mounted anymore" % target)
694 logging.debug("umount %s %s" % (list(unmount_options), target))
695 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
697 if proc.returncode != 0:
698 raise Exception("Error executing umount")
700 logging.debug("unregister_mountpoint(%s)" % target)
701 unregister_mountpoint(target)
704 def check_for_usbdevice(device):
705 """Check whether the specified device is a removable USB device
707 @device: device name, like /dev/sda1 or /dev/sda
710 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
711 usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
712 if os.path.isfile(usbdevice):
713 is_usb = open(usbdevice).readline()
720 def check_for_fat(partition):
721 """Check whether specified partition is a valid VFAT/FAT16 filesystem
723 @partition: device name of partition"""
726 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition],
727 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
728 filesystem = udev_info.communicate()[0].rstrip()
730 if udev_info.returncode == 2:
731 raise CriticalException("Failed to read device %s"
732 "(wrong UID/permissions or device not present?)" % partition)
734 if filesystem != "vfat":
735 raise CriticalException("Device %s does not contain a FAT16 partition." % partition)
738 raise CriticalException("Sorry, /lib/udev/vol_id not available.")
741 def mkdir(directory):
742 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
744 # just silently pass as it's just fine it the directory exists
745 if not os.path.isdir(directory):
747 os.makedirs(directory)
748 # pylint: disable-msg=W0704
753 def copy_system_files(grml_flavour, iso_mount, target):
756 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
758 logging.critical("Fatal: squashfs file not found")
760 squashfs_target = target + '/live/'
761 execute(mkdir, squashfs_target)
762 # use install(1) for now to make sure we can write the files afterwards as normal user as well
763 logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
764 proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
767 filesystem_module = search_file('filesystem.module', iso_mount)
768 if filesystem_module is None:
769 logging.critical("Fatal: filesystem.module not found")
771 logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
772 proc = subprocess.Popen(["install", "--mode=664", filesystem_module,
773 squashfs_target + grml_flavour + '.module'])
776 release_target = target + '/boot/release/' + grml_flavour
777 execute(mkdir, release_target)
779 kernel = search_file('linux26', iso_mount)
781 logging.critical("Fatal kernel not found")
783 logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
784 proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
787 initrd = search_file('initrd.gz', iso_mount)
789 logging.critical("Fatal: initrd not found")
791 logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
792 proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
796 def copy_grml_files(iso_mount, target):
799 grml_target = target + '/grml/'
800 execute(mkdir, grml_target)
802 for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
803 grml_file = search_file(myfile, iso_mount)
804 if grml_file is None:
805 logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
807 logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
808 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
811 grml_web_target = grml_target + '/web/'
812 execute(mkdir, grml_web_target)
814 for myfile in 'index.html', 'style.css':
815 grml_file = search_file(myfile, iso_mount)
816 if grml_file is None:
817 logging.warn("Warning: myfile %s could not be found - can not install it")
819 logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
820 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
823 grml_webimg_target = grml_web_target + '/images/'
824 execute(mkdir, grml_webimg_target)
826 for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
827 grml_file = search_file(myfile, iso_mount)
828 if grml_file is None:
829 logging.warn("Warning: myfile %s could not be found - can not install it")
831 logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
832 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
836 def copy_addons(iso_mount, target):
838 addons = target + '/boot/addons/'
839 execute(mkdir, addons)
841 # grub all-in-one image
842 allinoneimg = search_file('allinone.img', iso_mount)
843 if allinoneimg is None:
844 logging.warn("Warning: allinone.img not found - can not install it")
846 logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
847 proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
851 balderimg = search_file('balder10.imz', iso_mount)
852 if balderimg is None:
853 logging.warn("Warning: balder10.imz not found - can not install it")
855 logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
856 proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
860 memdiskimg = search_file('memdisk', iso_mount)
861 if memdiskimg is None:
862 logging.warn("Warning: memdisk not found - can not install it")
864 logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
865 proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
869 memtestimg = search_file('memtest', iso_mount)
870 if memtestimg is None:
871 logging.warn("Warning: memtest not found - can not install it")
873 logging.debug("cp %s %s" % (memtestimg, addons + '/memtest'))
874 proc = subprocess.Popen(["install", "--mode=664", memtestimg, addons + 'memtest'])
878 def copy_bootloader_files(iso_mount, target):
881 syslinux_target = target + '/boot/syslinux/'
882 execute(mkdir, syslinux_target)
884 logo = search_file('logo.16', iso_mount)
885 logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
886 proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
889 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
890 bootsplash = search_file(ffile, iso_mount)
891 logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
892 proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
895 grub_target = target + '/boot/grub/'
896 execute(mkdir, grub_target)
898 if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
899 logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
902 logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
903 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz',
904 grub_target + 'splash.xpm.gz'])
907 if not os.path.isfile("/usr/share/grml2usb/grub/stage2_eltorito"):
908 logging.critical("Error: /usr/share/grml2usb/grub/stage2_eltorito can not be read.")
911 logging.debug("cp /usr/share/grml2usb/grub/stage2_eltorito to %s" % grub_target + 'stage2_eltorito')
912 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/stage2_eltorito',
913 grub_target + 'stage2_eltorito'])
917 def install_iso_files(grml_flavour, iso_mount, device, target):
918 """Copy files from ISO on given target"""
921 # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
922 # * provide alternative search_file() if file information is stored in a config.ini file?
923 # * catch "install: .. No space left on device" & CO
924 # * abstract copy logic to make the code shorter and get rid of spaghettis ;)
927 logging.info("Would copy files to %s", iso_mount)
929 elif not options.bootloaderonly:
930 logging.info("Copying files. This might take a while....")
931 copy_system_files(grml_flavour, iso_mount, target)
932 copy_grml_files(iso_mount, target)
934 if not options.skipaddons:
935 copy_addons(iso_mount, target)
937 if not options.copyonly:
938 copy_bootloader_files(iso_mount, target)
940 if not options.dryrun:
941 handle_bootloader_config(grml_flavour, device, target) # FIXME
943 # make sure we sync filesystems before returning
944 proc = subprocess.Popen(["sync"])
948 def uninstall_files(device):
949 """Get rid of all grml files on specified device
951 @device: partition where grml2usb files should be removed from"""
954 logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
957 def identify_grml_flavour(mountpath):
958 """Get name of grml flavour
960 @mountpath: path where the grml ISO is mounted to
961 @return: name of grml-flavour"""
963 version_file = search_file('grml-version', mountpath)
965 if version_file == "":
966 logging.critical("Error: could not find grml-version file.")
970 tmpfile = open(version_file, 'r')
971 grml_info = tmpfile.readline()
972 grml_flavour = re.match(r'[\w-]*', grml_info).group()
976 logging.critical("Unexpected error:", sys.exc_info()[0])
982 def handle_bootloader_config(grml_flavour, device, target):
985 logging.debug("Generating grub configuration")
986 #with open("...", "w") as f:
987 #f.write("bla bla bal")
989 grub_target = target + '/boot/grub/'
990 # should be present via copy_bootloader_files(), but make sure it exists:
991 execute(mkdir, grub_target)
992 # we have to adjust root() inside grub configuration
993 if device[-1:].isdigit():
994 install_partition = device[-1:]
997 logging.debug("Creating grub1 configuration file")
998 grub_config_file = open(grub_target + 'menu.lst', 'w')
999 grub_config_file.write(generate_grub1_config(grml_flavour, install_partition, options.bootoptions))
1000 grub_config_file.close()
1002 # TODO => generate_main_grub1_config() && generate_flavour_specific_grub1_config()
1005 grub2_cfg = grub_target + 'grub.cfg'
1006 logging.debug("Creating grub2 configuration file")
1008 # install main configuration only *once*, no matter how many ISOs we have:
1009 if os.path.isfile(grub2_cfg):
1010 string = open(grub2_cfg).readline()
1011 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1012 if not re.match(main_identifier, string):
1013 grub2_config_file = open(grub2_cfg, 'w')
1014 logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
1015 grub2_config_file.write(generate_main_grub2_config(grml_flavour, install_partition, options.bootoptions))
1016 grub2_config_file.close()
1018 grub2_config_file = open(grub2_cfg, 'w')
1019 grub2_config_file.write(generate_main_grub2_config(grml_flavour, install_partition, options.bootoptions))
1020 grub2_config_file.close()
1022 grub_flavour_config = True
1023 if os.path.isfile(grub2_cfg):
1024 string = open(grub2_cfg).readlines()
1025 logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
1026 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1028 if flavour.match(line):
1029 grub_flavour_config = False
1031 if grub_flavour_config:
1032 grub2_config_file = open(grub2_cfg, 'a')
1033 grub2_config_file.write(generate_flavour_specific_grub2_config(grml_flavour, install_partition, options.bootoptions))
1034 grub2_config_file.close( )
1037 logging.info("Generating syslinux configuration")
1038 syslinux_target = target + '/boot/syslinux/'
1039 # should be present via copy_bootloader_files(), but make sure it exits:
1040 execute(mkdir, syslinux_target)
1041 syslinux_cfg = syslinux_target + 'syslinux.cfg'
1043 # install main configuration only *once*, no matter how many ISOs we have:
1044 if os.path.isfile(syslinux_cfg):
1045 string = open(syslinux_cfg).readline()
1046 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1047 if not re.match(main_identifier, string):
1048 syslinux_config_file = open(syslinux_cfg, 'w')
1049 logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
1050 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
1051 syslinux_config_file.close()
1053 syslinux_config_file = open(syslinux_cfg, 'w')
1054 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
1055 syslinux_config_file.close()
1057 # install flavour specific configuration only *once* as well
1058 # kind of ugly - I'm pretty sure this could be smoother...
1059 syslinux_flavour_config = True
1060 if os.path.isfile(syslinux_cfg):
1061 string = open(syslinux_cfg).readlines()
1062 logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
1063 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1065 if flavour.match(line):
1066 syslinux_flavour_config = False
1068 if syslinux_flavour_config:
1069 syslinux_config_file = open(syslinux_cfg, 'a')
1070 syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, options.bootoptions))
1071 syslinux_config_file.close( )
1073 logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
1074 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
1075 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
1076 isolinux_splash.close( )
1079 def handle_iso(iso, device):
1080 """Main logic for mounting ISOs and copying files.
1082 @iso: full path to the ISO that should be installed to the specified device
1083 @device: partition where the specified ISO should be installed to"""
1085 logging.info("Using ISO %s" % iso)
1087 if os.path.isdir(iso):
1088 logging.critical("TODO: /live/image handling not yet implemented - sorry") # TODO
1091 iso_mountpoint = tempfile.mkdtemp()
1092 register_tmpfile(iso_mountpoint)
1093 remove_iso_mountpoint = True
1095 if not os.path.isfile(iso):
1096 logging.critical("Fatal: specified ISO %s could not be read" % iso)
1101 mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
1102 except CriticalException, error:
1103 logging.critical("Fatal: %s" % error)
1106 if os.path.isdir(device):
1107 logging.info("Specified target is a directory, not mounting therefor.")
1108 device_mountpoint = device
1109 remove_device_mountpoint = False
1112 device_mountpoint = tempfile.mkdtemp()
1113 register_tmpfile(device_mountpoint)
1114 remove_device_mountpoint = True
1116 mount(device, device_mountpoint, "")
1117 except CriticalException, error:
1118 logging.critical("Fatal: %s" % error)
1123 grml_flavour = identify_grml_flavour(iso_mountpoint)
1124 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
1125 install_iso_files(grml_flavour, iso_mountpoint, device, device_mountpoint)
1127 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
1130 if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
1131 unmount(iso_mountpoint, "")
1132 os.rmdir(iso_mountpoint)
1133 unregister_tmpfile(iso_mountpoint)
1134 if remove_device_mountpoint:
1135 unmount(device_mountpoint, "")
1136 if os.path.isdir(device_mountpoint):
1137 os.rmdir(device_mountpoint)
1138 unregister_tmpfile(device_mountpoint)
1141 def handle_mbr(device):
1145 # if not options.mbr:
1146 # logging.info("You are NOT using the --mbr option. Consider using it if your device does not boot.")
1148 # make sure we install MBR on /dev/sdX and not /dev/sdX#
1150 # make sure we have syslinux available
1152 if not options.skipmbr:
1153 if not which("syslinux") and not options.copyonly and not options.dryrun:
1154 logging.critical('Sorry, syslinux not available. Exiting.')
1155 logging.critical('Please install syslinux or consider using the --grub option.')
1158 if not options.skipmbr:
1159 if device[-1:].isdigit():
1160 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
1163 install_mbr(mbr_device)
1164 except IOError, error:
1165 logging.critical("Execution failed: %s", error)
1167 except Exception, error:
1168 logging.critical("Execution failed: %s", error)
1172 def handle_vfat(device):
1175 # make sure we have mkfs.vfat available
1176 if options.fat16 and not options.force:
1177 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
1178 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
1179 logging.critical('Please make sure to install dosfstools.')
1182 # make sure the user is aware of what he is doing
1183 f = raw_input("Are you sure you want to format the device with a fat16 filesystem? y/N ")
1184 if f == "y" or f == "Y":
1185 logging.info("Note: you can skip this question using the option --force")
1190 # check for vfat filesystem
1191 if device is not None and not os.path.isdir(device):
1193 check_for_fat(device)
1194 except CriticalException, error:
1195 logging.critical("Execution failed: %s", error)
1198 if not check_for_usbdevice(device):
1199 print "Warning: the specified device %s does not look like a removable usb device." % device
1200 f = raw_input("Do you really want to continue? y/N ")
1201 if f == "y" or f == "Y":
1207 def handle_compat_warning(device):
1210 # make sure we can replace old grml2usb script and warn user when using old way of life:
1211 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1212 print "Warning: the semantics of grml2usb has changed."
1213 print "Instead of using grml2usb /path/to/iso %s you might" % device
1214 print "want to use grml2usb /path/to/iso /dev/... instead."
1215 print "Please check out the grml2usb manpage for details."
1216 f = raw_input("Do you really want to continue? y/N ")
1217 if f == "y" or f == "Y":
1223 def handle_logging():
1227 FORMAT = "%(asctime)-15s %(message)s"
1228 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1230 FORMAT = "Critial: %(message)s"
1231 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1233 FORMAT = "Info: %(message)s"
1234 logging.basicConfig(level=logging.INFO, format=FORMAT)
1237 def handle_bootloader(device):
1239 # Install bootloader only if not using the --copy-only option
1240 if options.copyonly:
1241 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1243 install_bootloader(device)
1247 """Main function [make pylint happy :)]"""
1250 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1254 parser.error("invalid usage")
1259 # make sure we have the appropriate permissions
1263 logging.info("Running in simulate mode as requested via option dry-run.")
1265 # specified arguments
1266 device = args[len(args) - 1]
1267 isos = args[0:len(args) - 1]
1269 # provide upgrade path
1270 handle_compat_warning(device)
1272 # check for vfat partition
1275 # main operation (like installing files)
1277 handle_iso(iso, device)
1282 handle_bootloader(device)
1284 # finally be politely :)
1285 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1288 if __name__ == "__main__":
1291 except KeyboardInterrupt:
1292 logging.info("Received KeyboardInterrupt")
1295 ## END OF FILE #################################################################
1296 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8