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(pre2)"
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("--initrd", dest="initrd", action="store", type="string",
50 # help="install specified initrd instead of the default [TODO - not implemented yet]")
51 #parser.add_option("--kernel", dest="kernel", action="store", type="string",
52 # help="install specified kernel instead of the default [TODO - not implemented yet]")
53 parser.add_option("--lilo-binary", dest="lilobin", action="store", type="string",
54 help="lilo executable to be used for installing MBR")
55 parser.add_option("--mbr-manager", dest="mbrmgr", action="store_true",
56 help="enable interactive boot manager menu in 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("--syslinux", dest="syslinux", action="store_true",
64 help="install syslinux bootloader instead of grub")
65 parser.add_option("--syslinux-mbr", dest="syslinuxmbr", action="store_true",
66 help="install syslinux master boot record (MBR) instead of default")
67 #parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
68 # help="install specified squashfs file instead of the default [TODO - not implemented yet]")
69 #parser.add_option("--uninstall", dest="uninstall", action="store_true",
70 # help="remove grml ISO files from specified device [TODO - not implemented yet]")
71 parser.add_option("--verbose", dest="verbose", action="store_true",
72 help="enable verbose mode")
73 parser.add_option("-v", "--version", dest="version", action="store_true",
74 help="display version and exit")
75 (options, args) = parser.parse_args()
78 class CriticalException(Exception):
79 """Throw critical exception if the exact error is not known but fatal."
81 @Exception: message"""
86 """Cleanup function to make sure there aren't any mounted devices left behind.
89 logging.info("Cleaning up before exiting...")
90 proc = subprocess.Popen(["sync"])
94 for device in MOUNTED:
96 # ignore: RuntimeError: Set changed size during iteration
98 logging.debug('caught expection RuntimeError, ignoring')
101 def register_tmpfile(path):
103 TODO - not implemented yet
109 def unregister_tmpfile(path):
111 TODO - not implemented yet
115 TMPFILES.remove(path)
118 def register_mountpoint(target):
119 """register specified target in a set() for handling clean exiting
121 @target: destination target of mountpoint
127 def unregister_mountpoint(target):
128 """unregister specified target in a set() for handling clean exiting
130 @target: destination target of mountpoint
133 if target in MOUNTED:
134 MOUNTED.remove(target)
137 def get_function_name(obj):
138 """Helper function for use in execute() to retrive name of a function
140 @obj: the function object
142 if not (isroutine(obj) or isclass(obj)):
144 return obj.__module__ + '.' + obj.__name__
147 def execute(f, *exec_arguments):
148 """Wrapper for executing a command. Either really executes
149 the command (default) or when using --dry-run commandline option
150 just displays what would be executed."""
151 # usage: execute(subprocess.Popen, (["ls", "-la"]))
152 # TODO: doesn't work for proc = execute(subprocess.Popen...() -> any ideas?
154 # pylint: disable-msg=W0141
155 logging.debug('dry-run only: %s(%s)' % (get_function_name(f), ', '.join(map(repr, exec_arguments))))
157 # pylint: disable-msg=W0142
158 return f(*exec_arguments)
162 """Check whether a given file can be executed
164 @fpath: full path to file
166 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
170 """Check whether a given program is available in PATH
172 @program: name of executable"""
173 fpath = os.path.split(program)[0]
178 for path in os.environ["PATH"].split(os.pathsep):
179 exe_file = os.path.join(path, program)
186 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
187 """Given a search path, find file
189 @filename: name of file to search for
190 @search_path: path where searching for the specified filename"""
192 paths = search_path.split(os.pathsep)
193 current_dir = '' # make pylint happy :)
195 # pylint: disable-msg=W0612
196 for current_dir, directories, files in os.walk(path):
197 if os.path.exists(os.path.join(current_dir, filename)):
201 return os.path.abspath(os.path.join(current_dir, filename))
206 def check_uid_root():
207 """Check for root permissions"""
208 if not os.geteuid()==0:
209 sys.exit("Error: please run this script with uid 0 (root).")
212 def mkfs_fat16(device):
213 """Format specified device with VFAT/FAT16 filesystem.
215 @device: partition that should be formated"""
217 # syslinux -d boot/isolinux /dev/sdb1
218 logging.info("Formating partition with fat16 filesystem")
219 logging.debug("mkfs.vfat -F 16 %s" % device)
220 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
222 if proc.returncode != 0:
223 raise CriticalException("error executing mkfs.vfat")
226 def generate_main_grub2_config(grml_flavour, install_partition, bootoptions):
227 """Generate grub2 configuration for use via grub.cfg
229 @grml_flavour: name of grml flavour the configuration should be generated for
230 @install_partition: partition number for use in (hd0,X)
231 @bootoptions: additional bootoptions that should be used by default"""
233 local_datestamp = DATESTAMP
236 ## main grub2 configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
242 if font (hd0,%(install_partition)s)/boot/grub/ascii.pff ; then
250 if background_image (hd0,%(install_partition)s)/boot/grub/grml.png ; then
251 set color_normal=black/black
252 set color_highlight=red/black
254 set menu_color_normal=white/black
255 set menu_color_highlight=black/yellow
258 menuentry "%(grml_flavour)s (default)" {
259 set root=(hd0,%(install_partition)s)
260 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s %(bootoptions)s
261 initrd /boot/release/%(grml_flavour)s/initrd.gz
264 menuentry "Memory test (memtest86+)" {
265 set root=(hd0,%(install_partition)s)
266 linux /boot/addons/memtest
269 menuentry "Grub - all in one image" {
270 set root=(hd0,%(install_partition)s)
271 linux /boot/addons/memdisk
272 initrd /boot/addons/allinone.img
275 menuentry "FreeDOS" {
276 set root=(hd0,%(install_partition)s)
277 linux /boot/addons/memdisk
278 initrd /boot/addons/balder10.imz
282 set root=(hd0,%(install_partition)s)
283 linux /boot/addons/bsd4grml/ldbsd.com
286 menuentry "Boot OS of first partition on first disk" {
291 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
292 'bootoptions': bootoptions, 'install_partition': install_partition } )
295 def generate_flavour_specific_grub2_config(grml_flavour, install_partition, bootoptions):
296 """Generate grub2 configuration for use via grub.cfg
298 @grml_flavour: name of grml flavour the configuration should be generated for
299 @install_partition: partition number for use in (hd0,X)
300 @bootoptions: additional bootoptions that should be used by default"""
302 local_datestamp = DATESTAMP
305 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
306 menuentry "%(grml_flavour)s" {
307 set root=(hd0,%(install_partition)s)
308 linux /boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
309 initrd /boot/release/%(grml_flavour)s/initrd.gz
312 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
313 menuentry "%(grml_flavour)s2ram" {
314 set root=(hd0,%(install_partition)s)
315 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
316 initrd /boot/release/%(grml_flavour)s/initrd.gz
319 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
320 menuentry "%(grml_flavour)s-debug" {
321 set root=(hd0,%(install_partition)s)
322 linux /boot/release/%(grml_flavour)s/linux26
323 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
326 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
327 menuentry "%(grml_flavour)s-x" {
328 set root=(hd0,%(install_partition)s)
329 linux /boot/release/%(grml_flavour)s/linux26
330 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
333 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
334 menuentry "%(grml_flavour)s-nofb" {
335 set root=(hd0,%(install_partition)s)
336 linux /boot/release/%(grml_flavour)s/linux26
337 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
340 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
341 menuentry "%(grml_flavour)s-failsafe" {
342 set root=(hd0,%(install_partition)s)
343 linux /boot/release/%(grml_flavour)s/linux26
344 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
347 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
348 menuentry "%(grml_flavour)s-forensic" {
349 set root=(hd0,%(install_partition)s)
350 linux /boot/release/%(grml_flavour)s/linux26
351 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
354 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
355 menuentry "%(grml_flavour)s-serial" {
356 set root=(hd0,%(install_partition)s)
357 linux /boot/release/%(grml_flavour)s/linux26
358 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
361 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
362 'bootoptions': bootoptions, 'install_partition': install_partition } )
365 def generate_flavour_specific_grub1_config(grml_flavour, install_partition, bootoptions):
366 """Generate grub1 configuration for use via menu.lst
368 @grml_flavour: name of grml flavour the configuration should be generated for
369 @install_partition: partition number for use in (hd0,X)
370 @bootoptions: additional bootoptions that should be used by default"""
372 local_datestamp = DATESTAMP
375 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
376 title %(grml_flavour)s
377 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
378 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
380 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
381 title %(grml_flavour)s2ram
382 kernel (hd0,%(install_partition)s)/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
383 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
385 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
386 title %(grml_flavour)s-debug
387 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s debug boot=live initcall_debug%(bootoptions)s
388 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
390 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
391 title %(grml_flavour)s-x
392 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s startx=wm-ng %(bootoptions)s
393 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
395 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
396 title %(grml_flavour)s-nofb
397 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=ofonly %(bootoptions)s
398 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
400 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
401 title %(grml_flavour)s-failsafe
402 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 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
403 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
405 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
406 title %(grml_flavour)s-forensic
407 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s nofstab noraid nolvm noautoconfig noswap raid=noautodetect %(bootoptions)s
408 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
410 ## flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
411 title %(grml_flavour)s-serial
412 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off boot=live nomce quiet module=%(grml_flavour)s vga=normal video=vesafb:off console=tty1 console=ttyS0,9600n8 %(bootoptions)s
413 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
415 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
416 'bootoptions': bootoptions, 'install_partition': install_partition } )
419 def generate_main_grub1_config(grml_flavour, install_partition, bootoptions):
420 """Generate grub1 configuration for use via menu.lst
422 @grml_flavour: name of grml flavour the configuration should be generated for"""
424 local_datestamp = DATESTAMP
427 ## main grub1 configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
430 # color red/blue green/black
431 splashimage=(hd0,%(install_partition)s)/boot/grub/splash.xpm.gz
436 title %(grml_flavour)s - Default boot (using 1024x768 framebuffer)
437 kernel (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s
438 initrd (hd0,%(install_partition)s)/boot/release/%(grml_flavour)s/initrd.gz
440 title Memory test (memtest86+)
441 kernel (hd0,%(install_partition)s)/boot/addons/memtest
443 title Grub - all in one image
444 kernel (hd0,%(install_partition)s)/boot/addons/memdisk
445 initrd (hd0,%(install_partition)s)/boot/addons/allinone.img
448 kernel (hd0,%(install_partition)s)/boot/addons/memdisk
449 initrd (hd0,%(install_partition)s)/boot/addons/balder10.imz
452 kernel (hd0,%(install_partition)s)/boot/addons/bsd4grml/ldbsd.com
454 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp,
455 'bootoptions': bootoptions, 'install_partition': install_partition } )
458 def generate_isolinux_splash(grml_flavour):
459 """Generate bootsplash for isolinux/syslinux
461 @grml_flavour: name of grml flavour the configuration should be generated for"""
463 # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
465 grml_name = grml_flavour
468 \ f17
\f\18/boot/syslinux/logo.16
470 Some information and boot options available via keys F2 - F10. http://grml.org/
472 """ % {'grml_name': grml_name} )
475 def generate_main_syslinux_config(grml_flavour, bootoptions):
476 """Generate main configuration for use in syslinux.cfg
478 @grml_flavour: name of grml flavour the configuration should be generated for
479 @bootoptions: additional bootoptions that should be used by default"""
481 local_datestamp = DATESTAMP
484 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
485 # use this to control the bootup via a serial port
490 DISPLAY /boot/syslinux/boot.msg
491 F1 /boot/syslinux/boot.msg
500 F10 /boot/syslinux/f10
501 ## end of main configuration
503 ## global configuration
504 # the default option (using %(grml_flavour)s)
506 KERNEL /boot/release/%(grml_flavour)s/linux26
507 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
511 KERNEL /boot/addons/memtest
516 KERNEL /boot/addons/memdisk
517 APPEND initrd=/boot/addons/allinone.img
522 KERNEL /boot/addons/memdisk
523 APPEND initrd=/boot/addons/balder10.imz
528 KERNEL /boot/addons/bsd4grml/ldbsd.com
530 ## end of global configuration
531 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
534 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
535 """Generate flavour specific configuration for use in syslinux.cfg
537 @grml_flavour: name of grml flavour the configuration should be generated for
538 @bootoptions: bootoptions that should be used as a default"""
540 local_datestamp = DATESTAMP
544 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
545 LABEL %(grml_flavour)s
546 KERNEL /boot/release/%(grml_flavour)s/linux26
547 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
549 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
550 LABEL %(grml_flavour)s2ram
551 KERNEL /boot/release/%(grml_flavour)s/linux26
552 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
554 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
555 LABEL %(grml_flavour)s-debug
556 KERNEL /boot/release/%(grml_flavour)s/linux26
557 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
559 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
560 LABEL %(grml_flavour)s-x
561 KERNEL /boot/release/%(grml_flavour)s/linux26
562 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
564 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
565 LABEL %(grml_flavour)s-nofb
566 KERNEL /boot/release/%(grml_flavour)s/linux26
567 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
569 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
570 LABEL %(grml_flavour)s-failsafe
571 KERNEL /boot/release/%(grml_flavour)s/linux26
572 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
574 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
575 LABEL %(grml_flavour)s-forensic
576 KERNEL /boot/release/%(grml_flavour)s/linux26
577 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
579 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
580 LABEL %(grml_flavour)s-serial
581 KERNEL /boot/release/%(grml_flavour)s/linux26
582 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
583 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
586 def install_grub(device):
587 """Install grub on specified device.
589 @mntpoint: mountpoint of device where grub should install its files to
590 @device: partition where grub should be installed to"""
593 logging.info("Would execute grub-install [--root-directory=mount_point] %s now.", device)
595 device_mountpoint = tempfile.mkdtemp()
596 register_tmpfile(device_mountpoint)
598 mount(device, device_mountpoint, "")
599 logging.debug("grub-install --recheck --no-floppy --root-directory=%s %s", device_mountpoint, device)
600 proc = subprocess.Popen(["grub-install", "--recheck", "--no-floppy",
601 "--root-directory=%s" % device_mountpoint, device], stdout=file(os.devnull, "r+"))
603 if proc.returncode != 0:
604 raise Exception("error executing grub-install")
605 except CriticalException, error:
606 logging.critical("Fatal: %s" % error)
611 unmount(device_mountpoint, "")
612 os.rmdir(device_mountpoint)
613 unregister_tmpfile(device_mountpoint)
616 def install_syslinux(device):
617 """Install syslinux on specified device.
619 @device: partition where syslinux should be installed to"""
622 logging.info("Would install syslinux as bootloader on %s", device)
625 # syslinux -d boot/isolinux /dev/sdb1
626 logging.info("Installing syslinux as bootloader")
627 logging.debug("syslinux -d boot/syslinux %s" % device)
628 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
630 if proc.returncode != 0:
631 raise CriticalException("Error executing syslinux (either try --fat16 or --grub?)")
634 def install_bootloader(device):
635 """Install bootloader on specified device.
637 @device: partition where bootloader should be installed to"""
639 # by default we use grub, so install syslinux only on request
642 install_syslinux(device)
643 except CriticalException, error:
644 logging.critical("Fatal: %s" % error)
650 except CriticalException, error:
651 logging.critical("Fatal: %s" % error)
656 def execute_lilo(lilo, device):
657 """execute lilo for activating the partitions in the MBR
659 @lilo: path of lilo executable
660 @device: device where lilo should be executed on"""
662 # to support -A for extended partitions:
663 logging.info("Activating partitions in MBR via lilo")
664 logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
665 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
667 if proc.returncode != 0:
668 raise Exception("error executing lilo")
670 # activate partition:
671 logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
672 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
674 if proc.returncode != 0:
675 raise Exception("error executing lilo")
678 def install_syslinux_mbr(device):
679 """install syslinux's master boot record (MBR) on the specified device
681 @device: device where MBR of syslinux should be installed to"""
683 # lilo's mbr is broken, use the one from syslinux instead:
684 if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
685 raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
687 logging.info("Installing syslinux MBR")
688 logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
690 # TODO -> use Popen instead?
691 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
693 logging.critical("Error copying MBR to device (%s)" % retcode)
694 except OSError, error:
695 logging.critical("Execution failed:", error)
698 def install_mir_mbr(mbrtemplate, device, partition, ismirbsdmbr=True):
699 """install 'mbr' master boot record (MBR) on a device
701 Retrieve the partition table from "device", install an MBR from
702 the "mbrtemplate" file, set the "partition" (0..3) active, and
703 install the result back to "device".
705 @mbrtemplate: default MBR file
707 @device: name of a file assumed to be a hard disc (or USB stick) image,
708 or something like "/dev/sdb"
709 @partition: must be a number between 0 and 3, inclusive
711 @mbrtemplate: must be a valid MBR file of at least 440 (or 439
712 if ismirbsdmbr) bytes.
714 @ismirbsdmbr: if set the partitions' active flags are not changed.
715 Instead, the MBR's default value is set accordingly."""
717 logging.info("Installing default MBR")
719 if not os.path.isfile(mbrtemplate):
720 logging.critical("Error: %s can not be read." % mbrtemplate)
721 raise CriticalException("Error installing MBR (either try --syslinux-mbr or install missing file?)")
723 if (partition < 0) or (partition > 3):
724 raise ValueError("partition must be between 0 and 3")
731 tmpf = tempfile.NamedTemporaryFile()
733 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1" % (device, tmpf.name))
734 proc = subprocess.Popen(["dd", "if=%s" % device, "of=%s" % tmpf.name, "bs=512", "count=1"], stderr=file(os.devnull, "r+"))
736 if proc.returncode != 0:
737 raise Exception("error executing dd (first run)")
739 logging.debug("executing: dd if=%s of=%s bs=%s count=1 conv=notrunc" % (mbrtemplate,
740 tmpf.name, nmbrbytes))
741 proc = subprocess.Popen(["dd", "if=%s" % mbrtemplate, "of=%s" % tmpf.name, "bs=%s" % nmbrbytes,
742 "count=1", "conv=notrunc"], stderr=file(os.devnull, "r+"))
744 if proc.returncode != 0:
745 raise Exception("error executing dd (second run)")
747 mbrcode = tmpf.file.read(512)
748 if len(mbrcode) < 512:
749 raise EOFError("MBR size (%d) < 512" % len(mbrcode))
752 mbrcode = mbrcode[0:439] + chr(partition) + \
753 mbrcode[440:510] + "\x55\xAA"
755 actives = ["\x00", "\x00", "\x00", "\x00"]
756 actives[partition] = "\x80"
757 mbrcode = mbrcode[0:446] + actives[0] + \
758 mbrcode[447:462] + actives[1] + \
759 mbrcode[463:478] + actives[2] + \
760 mbrcode[479:494] + actives[3] + \
761 mbrcode[495:510] + "\x55\xAA"
765 tmpf.file.write(mbrcode)
768 logging.debug("executing: dd if='%s' of='%s' bs=512 count=1 conv=notrunc" % (tmpf.name, device))
769 proc = subprocess.Popen(["dd", "if=%s" % tmpf.name, "of=%s" % device, "bs=512", "count=1",
770 "conv=notrunc"], stderr=file(os.devnull, "r+"))
772 if proc.returncode != 0:
773 raise Exception("error executing dd (third run)")
777 def handle_syslinux_mbr(device):
778 """Install syslinux master boot record on given device
780 @device: device where MBR should be installed to"""
782 if not is_writeable(device):
783 raise IOError("device not writeable for user")
785 # try to use system's lilo
789 # otherwise fall back to our static version
790 from platform import architecture
791 if architecture()[0] == '64bit':
792 lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
794 lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
795 # finally prefer a specified lilo executable
797 lilo = options.lilobin
800 raise Exception("lilo executable can not be execute")
803 logging.info("Would install MBR running lilo and using syslinux.")
806 execute_lilo(lilo, device)
807 install_syslinux_mbr(device)
810 def is_writeable(device):
811 """Check if the device is writeable for the current user
813 @device: partition where bootloader should be installed to"""
817 #raise Exception("no device for checking write permissions")
819 if not os.path.exists(device):
822 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
825 def mount(source, target, mount_options):
826 """Mount specified source on given target
828 @source: name of device/ISO that should be mounted
829 @target: directory where the ISO should be mounted to
830 @options: mount specific options"""
832 # note: options.dryrun does not work here, as we have to
833 # locate files and identify the grml flavour
835 for x in file('/proc/mounts').readlines():
836 if x.startswith(source):
837 raise CriticalException("Error executing mount: %s already mounted - please unmount before invoking grml2usb" % source)
839 logging.debug("mount %s %s %s" % (mount_options, source, target))
840 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
842 if proc.returncode != 0:
843 raise CriticalException("Error executing mount")
845 logging.debug("register_mountpoint(%s)" % target)
846 register_mountpoint(target)
849 def unmount(target, unmount_options):
850 """Unmount specified target
852 @target: target where something is mounted on and which should be unmounted
853 @options: options for umount command"""
855 # make sure we unmount only already mounted targets
856 target_unmount = False
857 mounts = open('/proc/mounts').readlines()
858 mountstring = re.compile(".*%s.*" % re.escape(target))
860 if re.match(mountstring, line):
861 target_unmount = True
863 if not target_unmount:
864 logging.debug("%s not mounted anymore" % target)
866 logging.debug("umount %s %s" % (list(unmount_options), target))
867 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
869 if proc.returncode != 0:
870 raise Exception("Error executing umount")
872 logging.debug("unregister_mountpoint(%s)" % target)
873 unregister_mountpoint(target)
876 def check_for_usbdevice(device):
877 """Check whether the specified device is a removable USB device
879 @device: device name, like /dev/sda1 or /dev/sda
882 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
883 usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
884 if os.path.isfile(usbdevice):
885 is_usb = open(usbdevice).readline()
892 def check_for_fat(partition):
893 """Check whether specified partition is a valid VFAT/FAT16 filesystem
895 @partition: device name of partition"""
898 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition],
899 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
900 filesystem = udev_info.communicate()[0].rstrip()
902 if udev_info.returncode == 2:
903 raise CriticalException("Failed to read device %s"
904 " (wrong UID/permissions or device not present?)" % partition)
906 if options.syslinux and filesystem != "vfat":
907 raise CriticalException("Partition %s does not contain a FAT16 filesystem. (Use --fat16 or run mkfs.vfat %s)" % (partition, partition))
910 raise CriticalException("Sorry, /lib/udev/vol_id not available.")
913 def mkdir(directory):
914 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
916 # just silently pass as it's just fine it the directory exists
917 if not os.path.isdir(directory):
919 os.makedirs(directory)
920 # pylint: disable-msg=W0704
925 def copy_system_files(grml_flavour, iso_mount, target):
926 """copy grml's main files (like squashfs, kernel and initrd) to a given target
928 @grml_flavour: name of grml flavour the configuration should be generated for
929 @iso_mount: path where a grml ISO is mounted on
930 @target: path where grml's main files should be copied to"""
932 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
934 logging.critical("Fatal: squashfs file not found")
936 squashfs_target = target + '/live/'
937 execute(mkdir, squashfs_target)
938 # use install(1) for now to make sure we can write the files afterwards as normal user as well
939 logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
940 proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
943 filesystem_module = search_file('filesystem.module', iso_mount)
944 if filesystem_module is None:
945 logging.critical("Fatal: filesystem.module not found")
947 logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
948 proc = subprocess.Popen(["install", "--mode=664", filesystem_module,
949 squashfs_target + grml_flavour + '.module'])
952 release_target = target + '/boot/release/' + grml_flavour
953 execute(mkdir, release_target)
955 kernel = search_file('linux26', iso_mount)
957 logging.critical("Fatal kernel not found")
959 logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
960 proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
963 initrd = search_file('initrd.gz', iso_mount)
965 logging.critical("Fatal: initrd not found")
967 logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
968 proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
972 def copy_grml_files(iso_mount, target):
973 """copy some minor grml files to a given target
975 @iso_mount: path where a grml ISO is mounted on
976 @target: path where grml's main files should be copied to"""
978 grml_target = target + '/grml/'
979 execute(mkdir, grml_target)
981 for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
982 grml_file = search_file(myfile, iso_mount)
983 if grml_file is None:
984 logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
986 logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
987 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
990 grml_web_target = grml_target + '/web/'
991 execute(mkdir, grml_web_target)
993 for myfile in 'index.html', 'style.css':
994 grml_file = search_file(myfile, iso_mount)
995 if grml_file is None:
996 logging.warn("Warning: myfile %s could not be found - can not install it")
998 logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
999 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
1002 grml_webimg_target = grml_web_target + '/images/'
1003 execute(mkdir, grml_webimg_target)
1005 for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
1006 grml_file = search_file(myfile, iso_mount)
1007 if grml_file is None:
1008 logging.warn("Warning: myfile %s could not be found - can not install it")
1010 logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
1011 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
1015 def copy_addons(iso_mount, target):
1016 """copy grml's addons files (like allinoneimg, bsd4grml,..) to a given target
1018 @iso_mount: path where a grml ISO is mounted on
1019 @target: path where grml's main files should be copied to"""
1021 addons = target + '/boot/addons/'
1022 execute(mkdir, addons)
1024 # grub all-in-one image
1025 allinoneimg = search_file('allinone.img', iso_mount)
1026 if allinoneimg is None:
1027 logging.warn("Warning: allinone.img not found - can not install it")
1029 logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
1030 proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
1034 bsdimg = search_file('bsd4grml', iso_mount)
1036 logging.warn("Warning: bsd4grml not found - can not install it")
1038 logging.debug("cp -a %s %s" % (bsdimg, addons + '/'))
1039 proc = subprocess.Popen(["cp", "-a", bsdimg, addons + '/'])
1043 balderimg = search_file('balder10.imz', iso_mount)
1044 if balderimg is None:
1045 logging.warn("Warning: balder10.imz not found - can not install it")
1047 logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
1048 proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
1052 memdiskimg = search_file('memdisk', iso_mount)
1053 if memdiskimg is None:
1054 logging.warn("Warning: memdisk not found - can not install it")
1056 logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
1057 proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
1061 memtestimg = search_file('memtest', iso_mount)
1062 if memtestimg is None:
1063 logging.warn("Warning: memtest not found - can not install it")
1065 logging.debug("cp %s %s" % (memtestimg, addons + '/memtest'))
1066 proc = subprocess.Popen(["install", "--mode=664", memtestimg, addons + 'memtest'])
1070 def copy_bootloader_files(iso_mount, target):
1071 """copy grml's bootloader files to a given target
1073 @iso_mount: path where a grml ISO is mounted on
1074 @target: path where grml's main files should be copied to"""
1076 syslinux_target = target + '/boot/syslinux/'
1077 execute(mkdir, syslinux_target)
1079 logo = search_file('logo.16', iso_mount)
1080 logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
1081 proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
1084 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
1085 bootsplash = search_file(ffile, iso_mount)
1086 logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
1087 proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
1090 grub_target = target + '/boot/grub/'
1091 execute(mkdir, grub_target)
1093 if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
1094 logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
1097 logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
1098 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz',
1099 grub_target + 'splash.xpm.gz'])
1102 # grml splash in grub
1103 if os.path.isfile("/usr/share/grml2usb/grub/grml.png"):
1104 logging.debug("cp /usr/share/grml2usb/grub/grml.png to %s" % grub_target + 'grml.png')
1105 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/grml.png',
1106 grub_target + 'grml.png'])
1109 # font file for graphical bootsplash in grub
1110 if os.path.isfile("/usr/share/grub/ascii.pff"):
1111 logging.debug("cp /usr/share/grub/ascii.pff to %s" % grub_target + 'ascii.pff')
1112 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grub/ascii.pff',
1113 grub_target + 'ascii.pff'])
1117 def install_iso_files(grml_flavour, iso_mount, device, target):
1118 """Copy files from ISO to given target
1120 @grml_flavour: name of grml flavour the configuration should be generated for
1121 @iso_mount: path where a grml ISO is mounted on
1122 @target: path where grml's main files should be copied to"""
1124 # TODO => several improvements:
1125 # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
1126 # * provide alternative search_file() if file information is stored in a config.ini file?
1127 # * catch "install: .. No space left on device" & CO
1130 logging.info("Would copy files to %s", iso_mount)
1132 elif not options.bootloaderonly:
1133 logging.info("Copying files. This might take a while....")
1134 copy_system_files(grml_flavour, iso_mount, target)
1135 copy_grml_files(iso_mount, target)
1137 if not options.skipaddons:
1138 copy_addons(iso_mount, target)
1140 if not options.copyonly:
1141 copy_bootloader_files(iso_mount, target)
1143 if not options.dryrun:
1144 handle_bootloader_config(grml_flavour, device, target)
1146 # make sure we sync filesystems before returning
1147 proc = subprocess.Popen(["sync"])
1151 def uninstall_files(device):
1152 """Get rid of all grml files on specified device
1154 @device: partition where grml2usb files should be removed from"""
1156 # TODO - not implemented yet
1157 logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
1160 def identify_grml_flavour(mountpath):
1161 """Get name of grml flavour
1163 @mountpath: path where the grml ISO is mounted to
1164 @return: name of grml-flavour"""
1166 version_file = search_file('grml-version', mountpath)
1168 if version_file == "":
1169 logging.critical("Error: could not find grml-version file.")
1173 tmpfile = open(version_file, 'r')
1174 grml_info = tmpfile.readline()
1175 grml_flavour = re.match(r'[\w-]*', grml_info).group()
1179 logging.critical("Unexpected error:", sys.exc_info()[0])
1185 def handle_grub1_config(grml_flavour, install_partition, grub_target, bootopt):
1186 """Main handler for generating grub1 configuration
1188 @grml_flavour: name of grml flavour the configuration should be generated for
1189 @install_partition: partition number for use in (hd0,X)
1190 @grub_target: path of grub's configuration files
1191 @bootoptions: additional bootoptions that should be used by default"""
1194 grub1_cfg = grub_target + 'menu.lst'
1195 logging.debug("Creating grub1 configuration file (menu.lst)")
1197 # install main configuration only *once*, no matter how many ISOs we have:
1198 if os.path.isfile(grub1_cfg):
1199 string = open(grub1_cfg).readline()
1200 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1201 if not re.match(main_identifier, string):
1202 grub1_config_file = open(grub1_cfg, 'w')
1203 # logging.info("Note: grml flavour %s is being installed as the default booting system." % grml_flavour)
1204 grub1_config_file.write(generate_main_grub1_config(grml_flavour, install_partition, bootopt))
1205 grub1_config_file.close()
1207 grub1_config_file = open(grub1_cfg, 'w')
1208 grub1_config_file.write(generate_main_grub1_config(grml_flavour, install_partition, bootopt))
1209 grub1_config_file.close()
1211 grub_flavour_config = True
1212 if os.path.isfile(grub1_cfg):
1213 string = open(grub1_cfg).readlines()
1214 # logging.info("Note: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
1215 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1217 if flavour.match(line):
1218 grub_flavour_config = False
1220 if grub_flavour_config:
1221 grub1_config_file = open(grub1_cfg, 'a')
1222 grub1_config_file.write(generate_flavour_specific_grub1_config(grml_flavour, install_partition, bootopt))
1223 grub1_config_file.close( )
1226 def handle_grub2_config(grml_flavour, install_partition, grub_target, bootopt):
1227 """Main handler for generating grub2 configuration
1229 @grml_flavour: name of grml flavour the configuration should be generated for
1230 @install_partition: partition number for use in (hd0,X)
1231 @grub_target: path of grub's configuration files
1232 @bootoptions: additional bootoptions that should be used by default"""
1235 grub2_cfg = grub_target + 'grub.cfg'
1236 logging.debug("Creating grub2 configuration file (grub.lst)")
1238 # install main configuration only *once*, no matter how many ISOs we have:
1239 if os.path.isfile(grub2_cfg):
1240 string = open(grub2_cfg).readline()
1241 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1242 if not re.match(main_identifier, string):
1243 grub2_config_file = open(grub2_cfg, 'w')
1244 logging.info("Note: grml flavour %s is being installed as the default booting system." % grml_flavour)
1245 grub2_config_file.write(generate_main_grub2_config(grml_flavour, install_partition, bootopt))
1246 grub2_config_file.close()
1248 grub2_config_file = open(grub2_cfg, 'w')
1249 grub2_config_file.write(generate_main_grub2_config(grml_flavour, install_partition, bootopt))
1250 grub2_config_file.close()
1252 grub_flavour_config = True
1253 if os.path.isfile(grub2_cfg):
1254 string = open(grub2_cfg).readlines()
1255 logging.info("Note: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
1256 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1258 if flavour.match(line):
1259 grub_flavour_config = False
1261 if grub_flavour_config:
1262 grub2_config_file = open(grub2_cfg, 'a')
1263 grub2_config_file.write(generate_flavour_specific_grub2_config(grml_flavour, install_partition, bootopt))
1264 grub2_config_file.close( )
1267 def handle_grub_config(grml_flavour, device, target):
1268 """Main handler for generating grub (v1 and v2) configuration
1270 @grml_flavour: name of grml flavour the configuration should be generated for
1271 @device: device/partition where grub should be installed to
1272 @target: path of grub's configuration files"""
1274 logging.debug("Generating grub configuration")
1276 grub_target = target + '/boot/grub/'
1277 execute(mkdir, grub_target)
1279 # we have to adjust root() inside grub configuration
1280 if device[-1:].isdigit():
1281 install_grub1_partition = int(device[-1:]) - 1
1282 install_grub2_partition = device[-1:]
1284 # do NOT write "None" in kernel cmdline
1285 if options.bootoptions is None:
1288 bootopt = options.bootoptions
1291 handle_grub1_config(grml_flavour, install_grub1_partition, grub_target, bootopt)
1293 handle_grub2_config(grml_flavour, install_grub2_partition, grub_target, bootopt)
1296 def handle_syslinux_config(grml_flavour, target):
1297 """Main handler for generating syslinux configuration
1299 @grml_flavour: name of grml flavour the configuration should be generated for
1300 @target: path of syslinux's configuration files"""
1302 # do NOT write "None" in kernel cmdline
1303 if options.bootoptions is None:
1306 bootopt = options.bootoptions
1308 logging.info("Generating syslinux configuration")
1309 syslinux_target = target + '/boot/syslinux/'
1310 # should be present via copy_bootloader_files(), but make sure it exits:
1311 execute(mkdir, syslinux_target)
1312 syslinux_cfg = syslinux_target + 'syslinux.cfg'
1314 # install main configuration only *once*, no matter how many ISOs we have:
1315 if os.path.isfile(syslinux_cfg):
1316 string = open(syslinux_cfg).readline()
1317 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
1318 if not re.match(main_identifier, string):
1319 syslinux_config_file = open(syslinux_cfg, 'w')
1320 logging.info("Note: grml flavour %s is being installed as the default booting system." % grml_flavour)
1321 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, bootopt))
1322 syslinux_config_file.close()
1324 syslinux_config_file = open(syslinux_cfg, 'w')
1325 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, bootopt))
1326 syslinux_config_file.close()
1328 # install flavour specific configuration only *once* as well
1329 # kind of ugly - I'm pretty sure this could be smoother...
1330 syslinux_flavour_config = True
1331 if os.path.isfile(syslinux_cfg):
1332 string = open(syslinux_cfg).readlines()
1333 logging.info("Note: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
1334 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
1336 if flavour.match(line):
1337 syslinux_flavour_config = False
1339 if syslinux_flavour_config:
1340 syslinux_config_file = open(syslinux_cfg, 'a')
1341 syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, bootopt))
1342 syslinux_config_file.close( )
1344 logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
1345 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
1346 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
1347 isolinux_splash.close( )
1350 def handle_bootloader_config(grml_flavour, device, target):
1351 """Main handler for generating bootloader's configuration
1353 @grml_flavour: name of grml flavour the configuration should be generated for
1354 @device: device/partition where bootloader should be installed to
1355 @target: path of bootloader's configuration files"""
1357 if options.syslinux:
1358 handle_syslinux_config(grml_flavour, target)
1360 handle_grub_config(grml_flavour, device, target)
1363 def handle_iso(iso, device):
1364 """Main logic for mounting ISOs and copying files.
1366 @iso: full path to the ISO that should be installed to the specified device
1367 @device: partition where the specified ISO should be installed to"""
1369 logging.info("Using ISO %s" % iso)
1371 if os.path.isdir(iso):
1372 logging.critical("TODO: /live/image handling not yet implemented - sorry")
1375 iso_mountpoint = tempfile.mkdtemp()
1376 register_tmpfile(iso_mountpoint)
1377 remove_iso_mountpoint = True
1379 if not os.path.isfile(iso):
1380 logging.critical("Fatal: specified ISO %s could not be read" % iso)
1385 mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
1386 except CriticalException, error:
1387 logging.critical("Fatal: %s" % error)
1390 if os.path.isdir(device):
1391 logging.info("Specified target is a directory, not mounting therefor.")
1392 device_mountpoint = device
1393 remove_device_mountpoint = False
1396 device_mountpoint = tempfile.mkdtemp()
1397 register_tmpfile(device_mountpoint)
1398 remove_device_mountpoint = True
1400 mount(device, device_mountpoint, "")
1401 except CriticalException, error:
1402 logging.critical("Fatal: %s" % error)
1407 grml_flavour = identify_grml_flavour(iso_mountpoint)
1408 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
1409 install_iso_files(grml_flavour, iso_mountpoint, device, device_mountpoint)
1411 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
1414 if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
1415 unmount(iso_mountpoint, "")
1416 os.rmdir(iso_mountpoint)
1417 unregister_tmpfile(iso_mountpoint)
1418 if remove_device_mountpoint:
1419 unmount(device_mountpoint, "")
1420 if os.path.isdir(device_mountpoint):
1421 os.rmdir(device_mountpoint)
1422 unregister_tmpfile(device_mountpoint)
1425 def handle_mbr(device):
1426 """Main handler for installing master boot record (MBR)
1428 @device: device where the MBR should be installed to"""
1430 # make sure we have syslinux available
1431 if not options.skipmbr:
1432 if not which("syslinux") and not options.copyonly and not options.dryrun:
1433 logging.critical('Sorry, syslinux not available. Exiting.')
1434 logging.critical('Please install syslinux or consider using the --grub option.')
1437 if not options.skipmbr:
1438 if device[-1:].isdigit():
1439 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
1440 partition_number = int(device[-1:]) - 1
1443 if options.syslinuxmbr:
1444 handle_syslinux_mbr(mbr_device)
1447 install_mir_mbr('/usr/share/grml2usb/mbr/mbrmgr', mbr_device, partition_number, True)
1449 install_mir_mbr('/usr/share/grml2usb/mbr/mbrldr', mbr_device, partition_number, True)
1450 except IOError, error:
1451 logging.critical("Execution failed: %s", error)
1453 except Exception, error:
1454 logging.critical("Execution failed: %s", error)
1458 def handle_vfat(device):
1459 """Check for FAT specific settings and options
1461 @device: device that should checked / formated"""
1463 # make sure we have mkfs.vfat available
1464 if options.fat16 and not options.force:
1465 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
1466 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
1467 logging.critical('Please make sure to install dosfstools.')
1470 # make sure the user is aware of what he is doing
1471 f = raw_input("Are you sure you want to format the specified partition with fat16? y/N ")
1472 if f == "y" or f == "Y":
1473 logging.info("Note: you can skip this question using the option --force")
1476 except CriticalException, error:
1477 logging.critical("Execution failed: %s", error)
1482 # check for vfat filesystem
1483 if device is not None and not os.path.isdir(device):
1485 check_for_fat(device)
1486 except CriticalException, error:
1487 logging.critical("Execution failed: %s", error)
1490 if not check_for_usbdevice(device):
1491 print "Warning: the specified device %s does not look like a removable usb device." % device
1492 f = raw_input("Do you really want to continue? y/N ")
1493 if f == "y" or f == "Y":
1499 def handle_compat_warning(device):
1500 """Backwards compatible checks
1502 @device: device that should be checked"""
1504 # make sure we can replace old grml2usb script and warn user when using old way of life:
1505 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1506 print "Warning: the semantics of grml2usb has changed."
1507 print "Instead of using grml2usb /path/to/iso %s you might" % device
1508 print "want to use grml2usb /path/to/iso /dev/... instead."
1509 print "Please check out the grml2usb manpage for details."
1510 f = raw_input("Do you really want to continue? y/N ")
1511 if f == "y" or f == "Y":
1517 def handle_logging():
1518 """Log handling and configuration"""
1521 FORMAT = "%(asctime)-15s %(message)s"
1522 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1524 FORMAT = "Critical: %(message)s"
1525 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1527 FORMAT = "Info: %(message)s"
1528 logging.basicConfig(level=logging.INFO, format=FORMAT)
1531 def handle_bootloader(device):
1532 """wrapper for installing bootloader
1534 @device: device where bootloader should be installed to"""
1536 # Install bootloader only if not using the --copy-only option
1537 if options.copyonly:
1538 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1540 install_bootloader(device)
1544 """Main function [make pylint happy :)]"""
1547 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1551 parser.error("invalid usage")
1556 # make sure we have the appropriate permissions
1560 logging.info("Running in simulation mode as requested via option dry-run.")
1562 # specified arguments
1563 device = args[len(args) - 1]
1564 isos = args[0:len(args) - 1]
1566 if device[-1:].isdigit():
1567 if int(device[-1:]) > 4:
1568 logging.critical("Fatal: installation on partition number >4 not supported. (BIOS won't support it.)")
1571 logging.critical("Fatal: installation on raw device not supported. (BIOS won't support it.)")
1574 # provide upgrade path
1575 handle_compat_warning(device)
1577 # check for vfat partition
1580 # main operation (like installing files)
1582 handle_iso(iso, device)
1587 handle_bootloader(device)
1589 # finally be politely :)
1590 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1593 if __name__ == "__main__":
1596 except KeyboardInterrupt:
1597 logging.info("Received KeyboardInterrupt")
1600 ## END OF FILE #################################################################
1601 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8