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.8"
22 MOUNTED = set() # register mountpoints
23 TMPFILES = set() # register tmpfiles
24 DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
25 GRML_FLAVOURS = set() # which flavours are being installed?
29 USAGE = "Usage: %prog [options] <[ISO[s] | /live/image]> </dev/sdX#>\n\
31 %prog installs grml ISO[s] to an USB device to be able to boot from it.\n\
32 Make sure you have at least one grml ISO or a running grml system (/live/image),\n\
33 grub or syslinux and root access.\n\
35 Run %prog --help for usage hints, further information via: man grml2usb"
37 # pylint: disable-msg=C0103
38 parser = OptionParser(usage=USAGE)
39 parser.add_option("--bootoptions", dest="bootoptions",
40 action="store", type="string",
41 help="use specified bootoptions as default")
42 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
43 help="do not copy files but just install a bootloader")
44 parser.add_option("--copy-only", dest="copyonly", action="store_true",
45 help="copy files only but do not install bootloader")
46 parser.add_option("--dry-run", dest="dryrun", action="store_true",
47 help="avoid executing commands")
48 parser.add_option("--fat16", dest="fat16", action="store_true",
49 help="format specified partition with FAT16")
50 parser.add_option("--force", dest="force", action="store_true",
51 help="force any actions requiring manual interaction")
52 #parser.add_option("--initrd", dest="initrd", action="store", type="string",
53 # help="install specified initrd instead of the default [TODO - not implemented yet]")
54 #parser.add_option("--kernel", dest="kernel", action="store", type="string",
55 # help="install specified kernel instead of the default [TODO - not implemented yet]")
56 parser.add_option("--lilo-binary", dest="lilobin", action="store", type="string",
57 help="lilo executable to be used for installing MBR")
58 parser.add_option("--mbr-menu", dest="mbrmenu", action="store_true",
59 help="enable interactive boot menu in MBR")
60 parser.add_option("--quiet", dest="quiet", action="store_true",
61 help="do not output anything but just errors on console")
62 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
63 help="do not install /boot/addons/ files")
64 parser.add_option("--skip-grub-config", dest="skipgrubconfig", action="store_true",
65 help="skip generation of grub configuration files")
66 parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
67 help="do not install a master boot record (MBR) on the device")
68 parser.add_option("--skip-syslinux-config", dest="skipsyslinuxconfig", action="store_true",
69 help="skip generation of syslinux configuration files")
70 parser.add_option("--syslinux", dest="syslinux", action="store_true",
71 help="install syslinux bootloader instead of grub")
72 parser.add_option("--syslinux-mbr", dest="syslinuxmbr", action="store_true",
73 help="install syslinux master boot record (MBR) instead of default")
74 #parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
75 # help="install specified squashfs file instead of the default [TODO - not implemented yet]")
76 #parser.add_option("--uninstall", dest="uninstall", action="store_true",
77 # help="remove grml ISO files from specified device [TODO - not implemented yet]")
78 parser.add_option("--verbose", dest="verbose", action="store_true",
79 help="enable verbose mode")
80 parser.add_option("-v", "--version", dest="version", action="store_true",
81 help="display version and exit")
82 (options, args) = parser.parse_args()
85 class CriticalException(Exception):
86 """Throw critical exception if the exact error is not known but fatal."
88 @Exception: message"""
93 """Cleanup function to make sure there aren't any mounted devices left behind.
96 logging.info("Cleaning up before exiting...")
97 proc = subprocess.Popen(["sync"])
101 for device in MOUNTED:
103 # ignore: RuntimeError: Set changed size during iteration
105 logging.debug('caught expection RuntimeError, ignoring')
108 def register_tmpfile(path):
110 TODO - not implemented yet
116 def unregister_tmpfile(path):
118 TODO - not implemented yet
122 TMPFILES.remove(path)
125 def register_mountpoint(target):
126 """register specified target in a set() for handling clean exiting
128 @target: destination target of mountpoint
134 def unregister_mountpoint(target):
135 """unregister specified target in a set() for handling clean exiting
137 @target: destination target of mountpoint
140 if target in MOUNTED:
141 MOUNTED.remove(target)
144 def get_function_name(obj):
145 """Helper function for use in execute() to retrive name of a function
147 @obj: the function object
149 if not (isroutine(obj) or isclass(obj)):
151 return obj.__module__ + '.' + obj.__name__
154 def execute(f, *exec_arguments):
155 """Wrapper for executing a command. Either really executes
156 the command (default) or when using --dry-run commandline option
157 just displays what would be executed."""
158 # usage: execute(subprocess.Popen, (["ls", "-la"]))
159 # TODO: doesn't work for proc = execute(subprocess.Popen...() -> any ideas?
161 # pylint: disable-msg=W0141
162 logging.debug('dry-run only: %s(%s)' % (get_function_name(f), ', '.join(map(repr, exec_arguments))))
164 # pylint: disable-msg=W0142
165 return f(*exec_arguments)
169 """Check whether a given file can be executed
171 @fpath: full path to file
173 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
177 """Check whether a given program is available in PATH
179 @program: name of executable"""
180 fpath = os.path.split(program)[0]
185 for path in os.environ["PATH"].split(os.pathsep):
186 exe_file = os.path.join(path, program)
193 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
194 """Given a search path, find file
196 @filename: name of file to search for
197 @search_path: path where searching for the specified filename"""
199 paths = search_path.split(os.pathsep)
200 current_dir = '' # make pylint happy :)
202 # pylint: disable-msg=W0612
203 for current_dir, directories, files in os.walk(path):
204 if os.path.exists(os.path.join(current_dir, filename)):
208 return os.path.abspath(os.path.join(current_dir, filename))
213 def check_uid_root():
214 """Check for root permissions"""
215 if not os.geteuid()==0:
216 sys.exit("Error: please run this script with uid 0 (root).")
219 def mkfs_fat16(device):
220 """Format specified device with VFAT/FAT16 filesystem.
222 @device: partition that should be formated"""
224 # syslinux -d boot/isolinux /dev/sdb1
226 logging.info("Would execute mkfs.vfat -F 16 %s now.", device)
229 logging.info("Formating partition with fat16 filesystem")
230 logging.debug("mkfs.vfat -F 16 %s" % device)
231 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
233 if proc.returncode != 0:
234 raise CriticalException("error executing mkfs.vfat")
237 def generate_main_grub2_config(grml_flavour, bootoptions):
238 """Generate grub2 configuration for use via grub.cfg
240 @grml_flavour: name of grml flavour the configuration should be generated for
241 @bootoptions: additional bootoptions that should be used by default"""
243 local_datestamp = DATESTAMP
246 ## main grub2 configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
252 if font /boot/grub/ascii.pff ; then
260 if background_image /boot/grub/grml.png ; then
261 set color_normal=black/black
262 set color_highlight=red/black
264 set menu_color_normal=white/black
265 set menu_color_highlight=black/yellow
268 menuentry "%(grml_flavour)s (default)" {
269 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off vga=791 quiet boot=live nomce live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
270 initrd /boot/release/%(grml_flavour)s/initrd.gz
273 menuentry "Memory test (memtest86+)" {
274 linux /boot/addons/memtest
277 menuentry "Grub - all in one image" {
278 linux /boot/addons/memdisk
279 initrd /boot/addons/allinone.img
282 menuentry "FreeDOS" {
283 linux /boot/addons/memdisk
284 initrd /boot/addons/balder10.imz
287 menuentry "MirOS BSD" {
288 multiboot /boot/addons/bsd4grml/ldbsd.com
291 menuentry "Boot OS of first partition on first disk" {
296 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
297 'bootoptions': bootoptions } )
300 def generate_flavour_specific_grub2_config(grml_flavour, bootoptions):
301 """Generate grub2 configuration for use via grub.cfg
303 @grml_flavour: name of grml flavour the configuration should be generated for
304 @bootoptions: additional bootoptions that should be used by default"""
306 local_datestamp = DATESTAMP
309 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
310 menuentry "%(grml_flavour)s" {
311 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
312 initrd /boot/release/%(grml_flavour)s/initrd.gz
315 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
316 menuentry "%(grml_flavour)s-persistent" {
317 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet persistent live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
318 initrd /boot/release/%(grml_flavour)s/initrd.gz
321 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
322 menuentry "%(grml_flavour)s2ram" {
323 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ toram=%(grml_flavour)s.squashfs %(bootoptions)s
324 initrd /boot/release/%(grml_flavour)s/initrd.gz
327 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
328 menuentry "%(grml_flavour)s-debug" {
329 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ debug boot=live initcall_debug%(bootoptions)s
330 initrd /boot/release/%(grml_flavour)s/initrd.gz
333 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
334 menuentry "%(grml_flavour)s-x" {
335 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ startx=wm-ng %(bootoptions)s
336 initrd /boot/release/%(grml_flavour)s/initrd.gz
339 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
340 menuentry "%(grml_flavour)s-nofb" {
341 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal video=ofonly %(bootoptions)s
342 initrd /boot/release/%(grml_flavour)s/initrd.gz
345 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
346 menuentry "%(grml_flavour)s-failsafe" {
347 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal boot=live noautoconfig atapicd noapic noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia nosmp maxcpus=0 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm noresume selinux=0 edd=off %(bootoptions)s
348 initrd /boot/release/%(grml_flavour)s/initrd.gz
351 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
352 menuentry "%(grml_flavour)s-forensic" {
353 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ nofstab noraid nolvm noautoconfig noswap raid=noautodetect forensic readonly %(bootoptions)s
354 initrd /boot/release/%(grml_flavour)s/initrd.gz
357 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
358 menuentry "%(grml_flavour)s-serial" {
359 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
360 initrd /boot/release/%(grml_flavour)s/initrd.gz
363 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
364 'bootoptions': bootoptions } )
367 def generate_flavour_specific_grub1_config(grml_flavour, install_partition, bootoptions):
368 """Generate grub1 configuration for use via menu.lst
370 @grml_flavour: name of grml flavour the configuration should be generated for
371 @install_partition: partition number for use in (hd0,X)
372 @bootoptions: additional bootoptions that should be used by default"""
374 local_datestamp = DATESTAMP
377 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
378 title %(grml_flavour)s
379 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
380 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
382 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
383 title %(grml_flavour)s-persistent
384 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet persistent live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
385 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
387 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
388 title %(grml_flavour)s2ram
389 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ toram=%(grml_flavour)s.squashfs %(bootoptions)s
390 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
392 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
393 title %(grml_flavour)s-debug
394 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ debug boot=live initcall_debug%(bootoptions)s
395 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
397 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
398 title %(grml_flavour)s-x
399 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ startx=wm-ng %(bootoptions)s
400 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
402 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
403 title %(grml_flavour)s-nofb
404 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal video=ofonly %(bootoptions)s
405 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
407 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
408 title %(grml_flavour)s-failsafe
409 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal boot=live noautoconfig atapicd noapic noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia nosmp maxcpus=0 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm noresume selinux=0 edd=off %(bootoptions)s
410 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
412 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
413 title %(grml_flavour)s-forensic
414 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ nofstab noraid nolvm noautoconfig noswap raid=noautodetect forensic readonly %(bootoptions)s
415 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
417 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
418 title %(grml_flavour)s-serial
419 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
420 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
422 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
423 'bootoptions': bootoptions, 'install_partition': install_partition } )
426 def generate_main_grub1_config(grml_flavour, install_partition, bootoptions):
427 """Generate grub1 configuration for use via menu.lst
429 @grml_flavour: name of grml flavour the configuration should be generated for"""
431 local_datestamp = DATESTAMP
434 ## main grub1 configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
437 # color red/blue green/black
438 splashimage=(hd0,%(install_partition)s)/boot/grub/splash.xpm.gz
443 title %(grml_flavour)s - Default boot (using 1024x768 framebuffer)
444 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off vga=791 quiet boot=live nomce live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
445 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
447 title Memory test (memtest86+)
448 kernel (hd0,%(install_partition)s)/boot/addons/memtest
450 title Grub - all in one image
451 kernel (hd0,%(install_partition)s)/boot/addons/memdisk
452 initrd (hd0,%(install_partition)s)/boot/addons/allinone.img
455 kernel (hd0,%(install_partition)s)/boot/addons/memdisk
456 initrd (hd0,%(install_partition)s)/boot/addons/balder10.imz
459 kernel (hd0,%(install_partition)s)/boot/addons/bsd4grml/ldbsd.com
461 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
462 'bootoptions': bootoptions, 'install_partition': install_partition } )
465 def generate_isolinux_splash(grml_flavour):
466 """Generate bootsplash for isolinux/syslinux
468 @grml_flavour: name of grml flavour the configuration should be generated for"""
470 # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
472 grml_name = grml_flavour
475 \ f17
\f\18/boot/syslinux/logo.16
477 Some information and boot options available via keys F2 - F10. http://grml.org/
479 """ % {'grml_name': grml_name} )
482 def generate_main_syslinux_config(grml_flavour, bootoptions):
483 """Generate main configuration for use in syslinux.cfg
485 @grml_flavour: name of grml flavour the configuration should be generated for
486 @bootoptions: additional bootoptions that should be used by default"""
488 local_datestamp = DATESTAMP
491 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
492 # use this to control the bootup via a serial port
497 DISPLAY /boot/syslinux/boot.msg
498 F1 /boot/syslinux/boot.msg
507 F10 /boot/syslinux/f10
508 ## end of main configuration
510 ## global configuration
511 # the default option (using %(grml_flavour)s)
513 KERNEL /boot/release/%(grml_flavour)s/linux26
514 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
518 KERNEL /boot/addons/memtest
523 KERNEL /boot/addons/memdisk
524 APPEND initrd=/boot/addons/allinone.img
529 KERNEL /boot/addons/memdisk
530 APPEND initrd=/boot/addons/balder10.imz
535 KERNEL /boot/addons/bsd4grml/ldbsd.com
537 # hardware detection tool
539 KERNEL /boot/addons/hdt.c32
540 APPEND pciids=/boot/addons/pci.ids
542 ## end of global configuration
543 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
546 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
547 """Generate flavour specific configuration for use in syslinux.cfg
549 @grml_flavour: name of grml flavour the configuration should be generated for
550 @bootoptions: bootoptions that should be used as a default"""
552 local_datestamp = DATESTAMP
556 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
557 LABEL %(grml_flavour)s
558 KERNEL /boot/release/%(grml_flavour)s/linux26
559 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
561 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
562 LABEL %(grml_flavour)s-persistent
563 KERNEL /boot/release/%(grml_flavour)s/linux26
564 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet persistent live-media-path=/live/%(grml_flavour)s/ %(bootoptions)s
566 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
567 LABEL %(grml_flavour)s2ram
568 KERNEL /boot/release/%(grml_flavour)s/linux26
569 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ toram=%(grml_flavour)s.squashfs %(bootoptions)s
571 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
572 LABEL %(grml_flavour)s-debug
573 KERNEL /boot/release/%(grml_flavour)s/linux26
574 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ debug boot=live initcall_debug%(bootoptions)s
576 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
577 LABEL %(grml_flavour)s-x
578 KERNEL /boot/release/%(grml_flavour)s/linux26
579 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ startx=wm-ng %(bootoptions)s
581 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
582 LABEL %(grml_flavour)s-nofb
583 KERNEL /boot/release/%(grml_flavour)s/linux26
584 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal video=ofonly %(bootoptions)s
586 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
587 LABEL %(grml_flavour)s-failsafe
588 KERNEL /boot/release/%(grml_flavour)s/linux26
589 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal boot=live noautoconfig atapicd noapic noacpi acpi=off nomodules nofirewire noudev nousb nohotplug noapm nopcmcia nosmp maxcpus=0 noscsi noagp nodma ide=nodma noswap nofstab nosound nogpm nosyslog nodhcp nocpu nodisc nomodem xmodule=vesa noraid nolvm noresume selinux=0 edd=off %(bootoptions)s
591 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
592 LABEL %(grml_flavour)s-forensic
593 KERNEL /boot/release/%(grml_flavour)s/linux26
594 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet live-media-path=/live/%(grml_flavour)s/ nofstab noraid nolvm noautoconfig noswap raid=noautodetect forensic readonly %(bootoptions)s
596 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
597 LABEL %(grml_flavour)s-serial
598 KERNEL /boot/release/%(grml_flavour)s/linux26
599 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet live-media-path=/live/%(grml_flavour)s/ vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
600 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
603 def install_grub(device):
604 """Install grub on specified device.
606 @mntpoint: mountpoint of device where grub should install its files to
607 @device: partition where grub should be installed to"""
610 logging.info("Would execute grub-install [--root-directory=mount_point] %s now.", device)
612 device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
613 register_tmpfile(device_mountpoint)
615 mount(device, device_mountpoint, "")
616 logging.debug("grub-install --recheck --no-floppy --root-directory=%s %s", device_mountpoint, device)
617 proc = subprocess.Popen(["grub-install", "--recheck", "--no-floppy",
618 "--root-directory=%s" % device_mountpoint, device], stdout=file(os.devnull, "r+"))
620 if proc.returncode != 0:
621 # raise Exception("error executing grub-install")
622 logging.critical("Fatal: error executing grub-install (please check the grml2usb FAQ)")
625 except CriticalException, error:
626 logging.critical("Fatal: %s" % error)
631 unmount(device_mountpoint, "")
632 os.rmdir(device_mountpoint)
633 unregister_tmpfile(device_mountpoint)
636 def install_syslinux(device):
637 """Install syslinux on specified device.
639 @device: partition where syslinux should be installed to"""
642 logging.info("Would install syslinux as bootloader on %s", device)
645 # syslinux -d boot/isolinux /dev/sdb1
646 logging.info("Installing syslinux as bootloader")
647 logging.debug("syslinux -d boot/syslinux %s" % device)
648 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
650 if proc.returncode != 0:
651 raise CriticalException("Error executing syslinux (either try --fat16 or --grub?)")
654 def install_bootloader(device):
655 """Install bootloader on specified device.
657 @device: partition where bootloader should be installed to"""
659 # by default we use grub, so install syslinux only on request
662 install_syslinux(device)
663 except CriticalException, error:
664 logging.critical("Fatal: %s" % error)
668 if not which("grub-install"):
669 logging.critical("Fatal: grub-install not available (please install the grub package or use the --syslinux option)")
675 except CriticalException, error:
676 logging.critical("Fatal: %s" % error)
681 def execute_lilo(lilo, device):
682 """execute lilo for activating the partitions in the MBR
684 @lilo: path of lilo executable
685 @device: device where lilo should be executed on"""
687 # to support -A for extended partitions:
688 logging.info("Activating partitions in MBR via lilo")
689 logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
690 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
692 if proc.returncode != 0:
693 raise Exception("error executing lilo")
695 # activate partition:
696 logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
697 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
699 if proc.returncode != 0:
700 raise Exception("error executing lilo")
703 def install_syslinux_mbr(device):
704 """install syslinux's master boot record (MBR) on the specified device
706 @device: device where MBR of syslinux should be installed to"""
708 # make sure we have syslinux available
709 if not which("syslinux") and not options.copyonly:
710 raise Exception("syslinux not available (either install it or consider dropping the --syslinux option)")
712 # lilo's mbr is broken, use the one from syslinux instead:
713 if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
714 raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
716 logging.info("Installing syslinux MBR")
717 logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
719 # TODO -> use Popen instead?
720 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
722 logging.critical("Error copying MBR to device (%s)" % retcode)
723 except OSError, error:
724 logging.critical("Execution failed:", error)
727 def install_mir_mbr(mbrtemplate, device, partition, ismirbsdmbr=True):
728 """install 'mbr' master boot record (MBR) on a device
730 Retrieve the partition table from "device", install an MBR from the
731 "mbrtemplate" file, set the "partition" (0..3) active, and install the
732 result back to "device".
734 @mbrtemplate: default MBR file
736 @device: name of a file assumed to be a hard disc (or USB stick) image, or
737 something like "/dev/sdb"
739 @partition: must be a number between 0 and 3, inclusive
741 @mbrtemplate: must be a valid MBR file of at least 440 (or 439 if
744 @ismirbsdmbr: if true then ignore the active flag, set the mirbsdmbr
745 specific flag to 0/1/2/3 and set the MBR's default value accordingly. If
746 false then leave the mirbsdmbr specific flag set to FFh, set all
747 active flags to 0 and set the active flag of the partition to 80h. Note:
748 behaviour of mirbsdmbr: if flag = 0/1/2/3 then use it, otherwise search for
751 logging.info("Installing default MBR")
753 if not os.path.isfile(mbrtemplate):
754 logging.critical("Error: %s can not be read." % mbrtemplate)
755 raise CriticalException("Error installing MBR (either try --syslinux-mbr or install missing file?)")
757 if (partition < 0) or (partition > 3):
758 raise ValueError("partition must be between 0 and 3")
765 tmpf = tempfile.NamedTemporaryFile()
767 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1" % (device, tmpf.name))
768 proc = subprocess.Popen(["dd", "if=%s" % device, "of=%s" % tmpf.name, "bs=512", "count=1"], stderr=file(os.devnull, "r+"))
770 if proc.returncode != 0:
771 raise Exception("error executing dd (first run)")
773 logging.debug("executing: dd if=%s of=%s bs=%s count=1 conv=notrunc" % (mbrtemplate,
774 tmpf.name, nmbrbytes))
775 proc = subprocess.Popen(["dd", "if=%s" % mbrtemplate, "of=%s" % tmpf.name, "bs=%s" % nmbrbytes,
776 "count=1", "conv=notrunc"], stderr=file(os.devnull, "r+"))
778 if proc.returncode != 0:
779 raise Exception("error executing dd (second run)")
781 mbrcode = tmpf.file.read(512)
782 if len(mbrcode) < 512:
783 raise EOFError("MBR size (%d) < 512" % len(mbrcode))
786 mbrcode = mbrcode[0:439] + chr(partition) + \
787 mbrcode[440:510] + "\x55\xAA"
789 actives = ["\x00", "\x00", "\x00", "\x00"]
790 actives[partition] = "\x80"
791 mbrcode = mbrcode[0:446] + actives[0] + \
792 mbrcode[447:462] + actives[1] + \
793 mbrcode[463:478] + actives[2] + \
794 mbrcode[479:494] + actives[3] + \
795 mbrcode[495:510] + "\x55\xAA"
799 tmpf.file.write(mbrcode)
802 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1 conv=notrunc" % (tmpf.name, device))
803 proc = subprocess.Popen(["dd", "if=%s" % tmpf.name, "of=%s" % device, "bs=512", "count=1",
804 "conv=notrunc"], stderr=file(os.devnull, "r+"))
806 if proc.returncode != 0:
807 raise Exception("error executing dd (third run)")
811 def handle_syslinux_mbr(device):
812 """Install syslinux master boot record on given device
814 @device: device where MBR should be installed to"""
816 if not is_writeable(device):
817 raise IOError("device not writeable for user")
819 # try to use system's lilo
823 # otherwise fall back to our static version
824 from platform import architecture
825 if architecture()[0] == '64bit':
826 lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
828 lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
829 # finally prefer a specified lilo executable
831 lilo = options.lilobin
834 raise Exception("lilo executable can not be execute")
837 logging.info("Would install MBR running lilo and using syslinux.")
840 execute_lilo(lilo, device)
841 install_syslinux_mbr(device)
844 def is_writeable(device):
845 """Check if the device is writeable for the current user
847 @device: partition where bootloader should be installed to"""
851 #raise Exception("no device for checking write permissions")
853 if not os.path.exists(device):
856 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
859 def mount(source, target, mount_options):
860 """Mount specified source on given target
862 @source: name of device/ISO that should be mounted
863 @target: directory where the ISO should be mounted to
864 @options: mount specific options"""
866 # note: options.dryrun does not work here, as we have to
867 # locate files and identify the grml flavour
869 for x in file('/proc/mounts').readlines():
870 if x.startswith(source):
871 raise CriticalException("Error executing mount: %s already mounted - please unmount before invoking grml2usb" % source)
873 if os.path.isdir(source):
874 logging.debug("Source %s is not a device, therefore not mounting." % source)
877 logging.debug("mount %s %s %s" % (mount_options, source, target))
878 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
880 if proc.returncode != 0:
881 raise CriticalException("Error executing mount (no filesystem on the partition?)")
883 logging.debug("register_mountpoint(%s)" % target)
884 register_mountpoint(target)
887 def unmount(target, unmount_options):
888 """Unmount specified target
890 @target: target where something is mounted on and which should be unmounted
891 @options: options for umount command"""
893 # make sure we unmount only already mounted targets
894 target_unmount = False
895 mounts = open('/proc/mounts').readlines()
896 mountstring = re.compile(".*%s.*" % re.escape(os.path.realpath(target)))
898 if re.match(mountstring, line):
899 target_unmount = True
901 if not target_unmount:
902 logging.debug("%s not mounted anymore" % target)
904 logging.debug("umount %s %s" % (list(unmount_options), target))
905 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
907 if proc.returncode != 0:
908 raise Exception("Error executing umount")
910 logging.debug("unregister_mountpoint(%s)" % target)
911 unregister_mountpoint(target)
914 def check_for_usbdevice(device):
915 """Check whether the specified device is a removable USB device
917 @device: device name, like /dev/sda1 or /dev/sda
920 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
922 usbdev = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
923 if not os.path.isfile(usbdev):
924 # Ubuntu with kernel 2.6.24 for example:
925 usbdev = os.path.realpath('/sys/block/' + usbdevice + '/removable')
927 if os.path.isfile(usbdev):
928 is_usb = open(usbdev).readline()
935 def check_for_fat(partition):
936 """Check whether specified partition is a valid VFAT/FAT16 filesystem
938 @partition: device name of partition"""
941 udev_info = subprocess.Popen(["/sbin/blkid", "-s", "TYPE", "-o", "value", partition],
942 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
943 filesystem = udev_info.communicate()[0].rstrip()
945 if udev_info.returncode == 2:
946 raise CriticalException("Failed to read device %s"
947 " (wrong UID/permissions or device/directory not present?)" % partition)
949 if options.syslinux and filesystem != "vfat":
950 raise CriticalException("Partition %s does not contain a FAT16 filesystem. (Use --fat16 or run mkfs.vfat %s)" % (partition, partition))
953 raise CriticalException("Sorry, /sbin/blkid not available (install e2fsprogs?)")
956 def mkdir(directory):
957 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
959 # just silently pass as it's just fine it the directory exists
960 if not os.path.isdir(directory):
962 os.makedirs(directory)
963 # pylint: disable-msg=W0704
968 def copy_system_files(grml_flavour, iso_mount, target):
969 """copy grml's main files (like squashfs, kernel and initrd) to a given target
971 @grml_flavour: name of grml flavour the configuration should be generated for
972 @iso_mount: path where a grml ISO is mounted on
973 @target: path where grml's main files should be copied to"""
975 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
977 logging.critical("Fatal: squashfs file not found")
978 raise CriticalException("error locating squashfs file")
980 squashfs_target = target + '/live/' + grml_flavour + '/'
981 execute(mkdir, squashfs_target)
982 logging.debug("rsync -aHS %s %s" % (squashfs, squashfs_target + grml_flavour + '.squashfs'))
983 proc = subprocess.Popen(["rsync", "-aHS", squashfs, squashfs_target + grml_flavour + ".squashfs"])
986 filesystem_module = search_file('filesystem.module', iso_mount)
987 if filesystem_module is None:
988 logging.critical("Fatal: filesystem.module not found")
990 logging.debug("rsync -aHS %s %s" % (filesystem_module, squashfs_target + 'filesystem.module'))
991 proc = subprocess.Popen(["rsync", "-aHS", filesystem_module, squashfs_target + 'filesystem.module'])
994 release_target = target + '/boot/release/' + grml_flavour
995 execute(mkdir, release_target)
997 kernel = search_file('linux26', iso_mount)
999 logging.critical("Fatal kernel not found")
1001 logging.debug("rsync -aHS %s %s" % (kernel, release_target + '/linux26'))
1002 proc = subprocess.Popen(["rsync", "-aHS", kernel, release_target + '/linux26'])
1005 initrd = search_file('initrd.gz', iso_mount)
1007 logging.critical("Fatal: initrd not found")
1009 logging.debug("rsync -aHS %s %s" % (initrd, release_target + '/initrd.gz'))
1010 proc = subprocess.Popen(["rsync", "-aHS", initrd, release_target + '/initrd.gz'])
1014 def copy_grml_files(iso_mount, target):
1015 """copy some minor grml files to a given target
1017 @iso_mount: path where a grml ISO is mounted on
1018 @target: path where grml's main files should be copied to"""
1020 grml_target = target + '/grml/'
1021 execute(mkdir, grml_target)
1023 for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
1024 grml_file = search_file(myfile, iso_mount)
1025 if grml_file is None:
1026 logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
1028 logging.debug("rsync -aHS %s %s" % (grml_file, grml_target + grml_file))
1029 proc = subprocess.Popen(["rsync", "-aHS", grml_file, grml_target + myfile])
1032 grml_web_target = grml_target + '/web/'
1033 execute(mkdir, grml_web_target)
1035 for myfile in 'index.html', 'style.css':
1036 grml_file = search_file(myfile, iso_mount)
1037 if grml_file is None:
1038 logging.warn("Warning: myfile %s could not be found - can not install it")
1040 logging.debug("rsync -aHS %s %s" % (grml_file, grml_web_target + grml_file))
1041 proc = subprocess.Popen(["rsync", "-aHS", grml_file, grml_web_target + myfile])
1044 grml_webimg_target = grml_web_target + '/images/'
1045 execute(mkdir, grml_webimg_target)
1047 for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
1048 grml_file = search_file(myfile, iso_mount)
1049 if grml_file is None:
1050 logging.warn("Warning: myfile %s could not be found - can not install it")
1052 logging.debug("rsync -aHS %s %s" % (grml_file, grml_webimg_target + grml_file))
1053 proc = subprocess.Popen(["rsync", "-aHS", grml_file, grml_webimg_target + myfile])
1057 def copy_addons(iso_mount, target):
1058 """copy grml's addons files (like allinoneimg, bsd4grml,..) to a given target
1060 @iso_mount: path where a grml ISO is mounted on
1061 @target: path where grml's main files should be copied to"""
1063 addons = target + '/boot/addons/'
1064 execute(mkdir, addons)
1066 # grub all-in-one image
1067 allinoneimg = search_file('allinone.img', iso_mount)
1068 if allinoneimg is None:
1069 logging.warn("Warning: allinone.img not found (that's fine if you don't need it)")
1071 logging.debug("rsync -aHS %s %s" % (allinoneimg, addons + '/allinone.img'))
1072 proc = subprocess.Popen(["rsync", "-aHS", allinoneimg, addons + 'allinone.img'])
1076 bsdimg = search_file('bsd4grml', iso_mount)
1078 logging.warn("Warning: bsd4grml not found (that's fine if you don't need it)")
1080 logging.debug("rsync -aHS %s %s" % (bsdimg, addons + '/'))
1081 proc = subprocess.Popen(["rsync", "-aHS", bsdimg, addons + '/'])
1085 balderimg = search_file('balder10.imz', iso_mount)
1086 if balderimg is None:
1087 logging.warn("Warning: balder10.imz not found (that's fine if you don't need it)")
1089 logging.debug("rsync -aHS %s %s" % (balderimg, addons + '/balder10.imz'))
1090 proc = subprocess.Popen(["rsync", "-aHS", balderimg, addons + 'balder10.imz'])
1093 # install hdt and pci.ids only when using syslinux (grub doesn't support it)
1094 if options.syslinux:
1095 # hdt (hardware detection tool) image
1096 hdtimg = search_file('hdt.c32', iso_mount)
1098 logging.debug("rsync -aHS %s %s" % (hdtimg, addons + '/hdt.c32'))
1099 proc = subprocess.Popen(["rsync", "-aHS", hdtimg, addons + '/hdt.c32'])
1103 picids = search_file('pci.ids', iso_mount)
1105 logging.debug("rsync -aHS %s %s" % (picids, addons + '/pci.ids'))
1106 proc = subprocess.Popen(["rsync", "-aHS", picids, addons + '/pci.ids'])
1110 memdiskimg = search_file('memdisk', iso_mount)
1111 if memdiskimg is None:
1112 logging.warn("Warning: memdisk not found (that's fine if you don't need it)")
1114 logging.debug("rsync -aHS %s %s" % (memdiskimg, addons + '/memdisk'))
1115 proc = subprocess.Popen(["rsync", "-aHS", memdiskimg, addons + 'memdisk'])
1119 memtestimg = search_file('memtest', iso_mount)
1120 if memtestimg is None:
1121 logging.warn("Warning: memtest not found (that's fine if you don't need it)")
1123 logging.debug("rsync -aHS %s %s" % (memtestimg, addons + '/memtest'))
1124 proc = subprocess.Popen(["rsync", "-aHS", memtestimg, addons + 'memtest'])
1128 def copy_bootloader_files(iso_mount, target):
1129 """copy grml's bootloader files to a given target
1131 @iso_mount: path where a grml ISO is mounted on
1132 @target: path where grml's main files should be copied to"""
1134 syslinux_target = target + '/boot/syslinux/'
1135 execute(mkdir, syslinux_target)
1137 logo = search_file('logo.16', iso_mount)
1138 logging.debug("rsync -aHS %s %s" % (logo, syslinux_target + 'logo.16'))
1139 proc = subprocess.Popen(["rsync", "-aHS", logo, syslinux_target + 'logo.16'])
1142 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
1143 bootsplash = search_file(ffile, iso_mount)
1144 logging.debug("rsync -aHS %s %s" % (bootsplash, syslinux_target + ffile))
1145 proc = subprocess.Popen(["rsync", "-aHS", bootsplash, syslinux_target + ffile])
1148 grub_target = target + '/boot/grub/'
1149 execute(mkdir, grub_target)
1151 if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
1152 logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
1153 logging.critical("Please make sure you've the grml2usb Debian package installed!")
1156 logging.debug("rsync -aHS /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
1157 proc = subprocess.Popen(["rsync", "-aHS", '/usr/share/grml2usb/grub/splash.xpm.gz',
1158 grub_target + 'splash.xpm.gz'])
1161 # grml splash in grub
1162 if os.path.isfile("/usr/share/grml2usb/grub/grml.png"):
1163 logging.debug("rsync -aHS /usr/share/grml2usb/grub/grml.png to %s" % grub_target + 'grml.png')
1164 proc = subprocess.Popen(["rsync", "-aHS", '/usr/share/grml2usb/grub/grml.png',
1165 grub_target + 'grml.png'])
1168 # font file for graphical bootsplash in grub
1169 if os.path.isfile("/usr/share/grub/ascii.pff"):
1170 logging.debug("rsync -aHS /usr/share/grub/ascii.pff to %s" % grub_target + 'ascii.pff')
1171 proc = subprocess.Popen(["rsync", "-aHS", '/usr/share/grub/ascii.pff',
1172 grub_target + 'ascii.pff'])
1176 def install_iso_files(grml_flavour, iso_mount, device, target):
1177 """Copy files from ISO to given target
1179 @grml_flavour: name of grml flavour the configuration should be generated for
1180 @iso_mount: path where a grml ISO is mounted on
1181 @device: device/partition where bootloader should be installed to
1182 @target: path where grml's main files should be copied to"""
1184 # TODO => several improvements:
1185 # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
1186 # * provide alternative search_file() if file information is stored in a config.ini file?
1187 # * catch "install: .. No space left on device" & CO
1191 elif not options.bootloaderonly:
1192 logging.info("Copying files. This might take a while....")
1194 copy_system_files(grml_flavour, iso_mount, target)
1195 copy_grml_files(iso_mount, target)
1196 except CriticalException, error:
1197 logging.critical("Execution failed: %s", error)
1200 if not options.skipaddons:
1201 if grml_flavour.endswith('-small'):
1202 logging.info("Note: grml-small doesn't provide any addons, not installing them therefore.")
1204 copy_addons(iso_mount, target)
1206 if not options.copyonly:
1207 copy_bootloader_files(iso_mount, target)
1209 if not options.dryrun:
1210 handle_bootloader_config(grml_flavour, device, target)
1212 # make sure we sync filesystems before returning
1213 proc = subprocess.Popen(["sync"])
1217 def uninstall_files(device):
1218 """Get rid of all grml files on specified device
1220 @device: partition where grml2usb files should be removed from"""
1222 # TODO - not implemented yet
1223 logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
1226 def identify_grml_flavour(mountpath):
1227 """Get name of grml flavour
1229 @mountpath: path where the grml ISO is mounted to
1230 @return: name of grml-flavour"""
1232 version_file = search_file('grml-version', mountpath)
1234 if version_file == "":
1235 logging.critical("Error: could not find grml-version file.")
1239 tmpfile = open(version_file, 'r')
1240 grml_info = tmpfile.readline()
1241 grml_flavour = re.match(r'[\w-]*', grml_info).group()
1245 logging.critical("Unexpected error:", sys.exc_info()[0])
1251 def handle_grub1_config(grml_flavour, install_partition, grub_target, bootopt):
1252 """Main handler for generating grub1 configuration
1254 @grml_flavour: name of grml flavour the configuration should be generated for
1255 @install_partition: partition number for use in (hd0,X)
1256 @grub_target: path of grub's configuration files
1257 @bootoptions: additional bootoptions that should be used by default"""
1260 grub1_cfg = grub_target + 'menu.lst'
1261 logging.debug("Creating grub1 configuration file (menu.lst)")
1263 # install main configuration only *once*, no matter how many ISOs we have:
1264 if os.path.isfile(grub1_cfg):
1265 string = open(grub1_cfg).readline()
1266 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1267 if not re.match(main_identifier, string):
1268 grub1_config_file = open(grub1_cfg, 'w')
1269 grub1_config_file.write(generate_main_grub1_config(grml_flavour, install_partition, bootopt))
1270 grub1_config_file.close()
1272 grub1_config_file = open(grub1_cfg, 'w')
1273 grub1_config_file.write(generate_main_grub1_config(grml_flavour, install_partition, bootopt))
1274 grub1_config_file.close()
1276 grub_flavour_config = True
1277 if os.path.isfile(grub1_cfg):
1278 string = open(grub1_cfg).readlines()
1279 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1281 if flavour.match(line):
1282 grub_flavour_config = False
1284 if grub_flavour_config:
1285 grub1_config_file = open(grub1_cfg, 'a')
1286 grub1_config_file.write(generate_flavour_specific_grub1_config(grml_flavour, install_partition, bootopt))
1287 grub1_config_file.close()
1290 def handle_grub2_config(grml_flavour, grub_target, bootopt):
1291 """Main handler for generating grub2 configuration
1293 @grml_flavour: name of grml flavour the configuration should be generated for
1294 @grub_target: path of grub's configuration files
1295 @bootoptions: additional bootoptions that should be used by default"""
1298 grub2_cfg = grub_target + 'grub.cfg'
1299 logging.debug("Creating grub2 configuration file (grub.lst)")
1303 # install main configuration only *once*, no matter how many ISOs we have:
1304 grub_flavour_is_default = False
1305 if os.path.isfile(grub2_cfg):
1306 string = open(grub2_cfg).readline()
1307 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1308 if not re.match(main_identifier, string):
1309 grub2_config_file = open(grub2_cfg, 'w')
1310 GRML_DEFAULT = grml_flavour
1311 grub_flavour_is_default = True
1312 grub2_config_file.write(generate_main_grub2_config(grml_flavour, bootopt))
1313 grub2_config_file.close()
1315 grub2_config_file = open(grub2_cfg, 'w')
1316 GRML_DEFAULT = grml_flavour
1317 grub_flavour_is_default = True
1318 grub2_config_file.write(generate_main_grub2_config(grml_flavour, bootopt))
1319 grub2_config_file.close()
1321 # install flavour specific configuration only *once* as well
1322 grub_flavour_config = True
1323 if os.path.isfile(grub2_cfg):
1324 string = open(grub2_cfg).readlines()
1325 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1327 if flavour.match(line):
1328 grub_flavour_config = False
1330 if grub_flavour_config:
1331 grub2_config_file = open(grub2_cfg, 'a')
1332 # display only if the grml flavour isn't the default
1333 if not grub_flavour_is_default:
1334 GRML_FLAVOURS.add(grml_flavour)
1335 grub2_config_file.write(generate_flavour_specific_grub2_config(grml_flavour, bootopt))
1336 grub2_config_file.close()
1339 def handle_grub_config(grml_flavour, device, target):
1340 """Main handler for generating grub (v1 and v2) configuration
1342 @grml_flavour: name of grml flavour the configuration should be generated for
1343 @device: device/partition where grub should be installed to
1344 @target: path of grub's configuration files"""
1346 logging.debug("Generating grub configuration")
1348 grub_target = target + '/boot/grub/'
1349 execute(mkdir, grub_target)
1351 if os.path.isdir(device):
1352 install_grub1_partition = None
1354 if device[-1:].isdigit():
1355 install_grub1_partition = int(device[-1:]) - 1
1357 raise CriticalException("error validating partition schema (raw device?)")
1359 # do NOT write "None" in kernel cmdline
1360 if options.bootoptions is None:
1363 bootopt = options.bootoptions
1366 if install_grub1_partition:
1367 handle_grub1_config(grml_flavour, install_grub1_partition, grub_target, bootopt)
1369 handle_grub2_config(grml_flavour, grub_target, bootopt)
1372 def handle_syslinux_config(grml_flavour, target):
1373 """Main handler for generating syslinux configuration
1375 @grml_flavour: name of grml flavour the configuration should be generated for
1376 @target: path of syslinux's configuration files"""
1378 # do NOT write "None" in kernel cmdline
1379 if options.bootoptions is None:
1382 bootopt = options.bootoptions
1384 logging.debug("Generating syslinux configuration")
1385 syslinux_target = target + '/boot/syslinux/'
1386 # should be present via copy_bootloader_files(), but make sure it exits:
1387 execute(mkdir, syslinux_target)
1388 syslinux_cfg = syslinux_target + 'syslinux.cfg'
1392 # install main configuration only *once*, no matter how many ISOs we have:
1393 syslinux_flavour_is_default = False
1394 if os.path.isfile(syslinux_cfg):
1395 string = open(syslinux_cfg).readline()
1396 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1397 if not re.match(main_identifier, string):
1398 syslinux_config_file = open(syslinux_cfg, 'w')
1399 GRML_DEFAULT = grml_flavour
1400 syslinux_flavour_is_default = True
1401 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, bootopt))
1402 syslinux_config_file.close()
1404 syslinux_config_file = open(syslinux_cfg, 'w')
1405 GRML_DEFAULT = grml_flavour
1406 syslinux_flavour_is_default = True
1407 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, bootopt))
1408 syslinux_config_file.close()
1410 # install flavour specific configuration only *once* as well
1411 syslinux_flavour_config = True
1412 if os.path.isfile(syslinux_cfg):
1413 string = open(syslinux_cfg).readlines()
1414 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1416 if flavour.match(line):
1417 syslinux_flavour_config = False
1419 if syslinux_flavour_config:
1420 syslinux_config_file = open(syslinux_cfg, 'a')
1421 # display only if the grml flavour isn't the default
1422 if not syslinux_flavour_is_default:
1423 GRML_FLAVOURS.add(grml_flavour)
1424 syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, bootopt))
1425 syslinux_config_file.close()
1427 logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
1428 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
1429 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
1430 isolinux_splash.close()
1433 def handle_bootloader_config(grml_flavour, device, target):
1434 """Main handler for generating bootloader's configuration
1436 @grml_flavour: name of grml flavour the configuration should be generated for
1437 @device: device/partition where bootloader should be installed to
1438 @target: path of bootloader's configuration files"""
1440 if options.skipsyslinuxconfig:
1441 logging.info("Skipping generation of syslinux configuration as requested.")
1444 handle_syslinux_config(grml_flavour, target)
1445 except CriticalException, error:
1446 logging.critical("Fatal: %s" % error)
1449 if options.skipgrubconfig:
1450 logging.info("Skipping generation of grub configuration as requested.")
1453 handle_grub_config(grml_flavour, device, target)
1454 except CriticalException, error:
1455 logging.critical("Fatal: %s" % error)
1458 def handle_dir(live_image, device):
1459 """Main logic for copying files of the currently running grml system.
1461 @live_image: directory where currently running live system resides (usually /live/image)
1462 @device: partition where the specified ISO should be installed to"""
1464 logging.info("Using %s as install base" % live_image)
1466 if os.path.isdir(device):
1467 logging.info("Specified target is a directory, therefore not mounting.")
1468 device_mountpoint = device
1469 remove_device_mountpoint = False
1471 device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
1472 register_tmpfile(device_mountpoint)
1473 remove_device_mountpoint = True
1475 mount(device, device_mountpoint, "")
1476 except CriticalException, error:
1477 logging.critical("Fatal: %s" % error)
1482 grml_flavour = identify_grml_flavour(live_image)
1483 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
1484 install_iso_files(grml_flavour, live_image, device, device_mountpoint)
1486 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
1489 if remove_device_mountpoint:
1491 unmount(device_mountpoint, "")
1492 if os.path.isdir(device_mountpoint):
1493 os.rmdir(device_mountpoint)
1494 unregister_tmpfile(device_mountpoint)
1495 except CriticalException, error:
1496 logging.critical("Fatal: %s" % error)
1500 def handle_iso(iso, device):
1501 """Main logic for mounting ISOs and copying files.
1503 @iso: full path to the ISO that should be installed to the specified device
1504 @device: partition where the specified ISO should be installed to"""
1506 logging.info("Using ISO %s" % iso)
1508 iso_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
1509 register_tmpfile(iso_mountpoint)
1510 remove_iso_mountpoint = True
1512 if not os.path.isfile(iso):
1513 logging.critical("Fatal: specified ISO %s could not be read" % iso)
1518 mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
1519 except CriticalException, error:
1520 logging.critical("Fatal: %s" % error)
1523 if os.path.isdir(device):
1524 logging.info("Specified target is a directory, therefore not mounting.")
1525 device_mountpoint = device
1526 remove_device_mountpoint = False
1529 device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
1530 register_tmpfile(device_mountpoint)
1531 remove_device_mountpoint = True
1533 mount(device, device_mountpoint, "")
1534 except CriticalException, error:
1535 logging.critical("Fatal: %s" % error)
1540 grml_flavour = identify_grml_flavour(iso_mountpoint)
1541 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
1542 install_iso_files(grml_flavour, iso_mountpoint, device, device_mountpoint)
1544 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
1547 if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
1548 unmount(iso_mountpoint, "")
1549 os.rmdir(iso_mountpoint)
1550 unregister_tmpfile(iso_mountpoint)
1551 if remove_device_mountpoint:
1553 unmount(device_mountpoint, "")
1554 if os.path.isdir(device_mountpoint):
1555 os.rmdir(device_mountpoint)
1556 unregister_tmpfile(device_mountpoint)
1557 except CriticalException, error:
1558 logging.critical("Fatal: %s" % error)
1562 def handle_mbr(device):
1563 """Main handler for installing master boot record (MBR)
1565 @device: device where the MBR should be installed to"""
1568 logging.info("Would install MBR")
1571 if device[-1:].isdigit():
1572 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
1573 partition_number = int(device[-1:]) - 1
1574 skip_install_mir_mbr = False
1576 # if we get e.g. /dev/loop1 as device we don't want to put the MBR
1577 # into /dev/loop of course, therefore use /dev/loop1 as mbr_device
1578 if mbr_device == "/dev/loop":
1580 logging.info("Detected loop device - using %s as MBR device therefore" % mbr_device)
1581 skip_install_mir_mbr = True
1584 if options.syslinuxmbr:
1585 handle_syslinux_mbr(mbr_device)
1586 elif not skip_install_mir_mbr:
1588 install_mir_mbr('/usr/share/grml2usb/mbr/mbrmgr', mbr_device, partition_number, True)
1590 install_mir_mbr('/usr/share/grml2usb/mbr/mbrldr', mbr_device, partition_number, False)
1591 except IOError, error:
1592 logging.critical("Execution failed: %s", error)
1594 except Exception, error:
1595 logging.critical("Execution failed: %s", error)
1599 def handle_vfat(device):
1600 """Check for FAT specific settings and options
1602 @device: device that should checked / formated"""
1604 # make sure we have mkfs.vfat available
1605 if options.fat16 and not options.force:
1606 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
1607 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
1608 logging.critical('Please make sure to install dosfstools.')
1611 # make sure the user is aware of what he is doing
1612 f = raw_input("Are you sure you want to format the specified partition with fat16? y/N ")
1613 if f == "y" or f == "Y":
1614 logging.info("Note: you can skip this question using the option --force")
1617 except CriticalException, error:
1618 logging.critical("Execution failed: %s", error)
1623 # check for vfat filesystem
1624 if device is not None and not os.path.isdir(device):
1626 check_for_fat(device)
1627 except CriticalException, error:
1628 logging.critical("Execution failed: %s", error)
1631 if not os.path.isdir(device) and not check_for_usbdevice(device):
1632 print "Warning: the specified device %s does not look like a removable usb device." % device
1633 f = raw_input("Do you really want to continue? y/N ")
1634 if f == "y" or f == "Y":
1640 def handle_compat_warning(device):
1641 """Backwards compatible checks
1643 @device: device that should be checked"""
1645 # make sure we can replace old grml2usb script and warn user when using old way of life:
1646 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1647 print "Warning: the semantics of grml2usb has changed."
1648 print "Instead of using grml2usb /path/to/iso %s you might" % device
1649 print "want to use grml2usb /path/to/iso /dev/... instead."
1650 print "Please check out the grml2usb manpage for details."
1651 f = raw_input("Do you really want to continue? y/N ")
1652 if f == "y" or f == "Y":
1658 def handle_logging():
1659 """Log handling and configuration"""
1661 if options.verbose and options.quiet:
1662 parser.error("please use either verbose (--verbose) or quiet (--quiet) option")
1665 FORMAT = "Debug: %(asctime)-15s %(message)s"
1666 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1668 FORMAT = "Critical: %(message)s"
1669 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1671 FORMAT = "%(message)s"
1672 logging.basicConfig(level=logging.INFO, format=FORMAT)
1675 def handle_bootloader(device):
1676 """wrapper for installing bootloader
1678 @device: device where bootloader should be installed to"""
1680 # Install bootloader only if not using the --copy-only option
1681 if options.copyonly:
1682 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1683 elif os.path.isdir(device):
1684 logging.info("Not installing bootloader as %s is a directory." % device)
1686 install_bootloader(device)
1690 """Main function [make pylint happy :)]"""
1693 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1697 parser.error("invalid usage")
1702 # make sure we have the appropriate permissions
1705 logging.info("Executing grml2usb version %s", PROG_VERSION)
1708 logging.info("Running in simulation mode as requested via option dry-run.")
1710 # specified arguments
1711 device = args[len(args) - 1]
1712 isos = args[0:len(args) - 1]
1714 if not os.path.isdir(device):
1715 if device[-1:].isdigit():
1716 if int(device[-1:]) > 4 or device[-2:].isdigit():
1717 logging.critical("Fatal: installation on partition number >4 not supported. (BIOS won't support it.)")
1720 if os.path.exists(device):
1721 logging.critical("Fatal: installation on raw device not supported. (BIOS won't support it.)")
1724 if not which("rsync"):
1725 logging.critical("Fatal: rsync not available, can not continue - sorry.")
1728 # provide upgrade path
1729 handle_compat_warning(device)
1731 # check for vfat partition
1734 # main operation (like installing files)
1736 if os.path.isdir(iso):
1737 handle_dir(iso, device)
1739 handle_iso(iso, device)
1742 if not os.path.isdir(device):
1743 if not options.skipmbr:
1746 handle_bootloader(device)
1748 logging.info("Note: grml flavour %s was installed as the default booting system." % GRML_DEFAULT)
1750 for flavour in GRML_FLAVOURS:
1751 logging.info("Note: you can boot flavour %s using '%s' on the commandline." % (flavour, flavour))
1753 # finally be politely :)
1754 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1757 if __name__ == "__main__":
1760 except KeyboardInterrupt:
1761 logging.info("Received KeyboardInterrupt")
1764 ## END OF FILE #################################################################
1765 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8