2 # -*- coding: utf-8 -*-
7 This script installs a grml system (either a running system or ISO[s]) to a USB device
9 :copyright: (c) 2009 by Michael Prokop <mika@grml.org>
10 :license: GPL v2 or any later version
11 :bugreports: http://grml.org/bugs/
15 from __future__ import with_statement
16 from optparse import OptionParser
17 from inspect import isroutine, isclass
18 import datetime, logging, os, re, subprocess, sys, tempfile, time
21 PROG_VERSION = "0.9.2(pre1)"
22 MOUNTED = set() # register mountpoints
23 TMPFILES = set() # register tmpfiles
24 DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
27 USAGE = "Usage: %prog [options] <[ISO[s] | /live/image]> </dev/sdX#>\n\
29 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
30 Make sure you have at least one grml ISO or a running grml system (/live/image),\n\
31 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
32 and root access. Further information can be found in: man grml2usb"
34 # pylint: disable-msg=C0103
35 parser = OptionParser(usage=USAGE)
36 parser.add_option("--bootoptions", dest="bootoptions",
37 action="store", type="string",
38 help="use specified bootoptions as default")
39 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
40 help="do not copy files but just install a bootloader")
41 parser.add_option("--copy-only", dest="copyonly", action="store_true",
42 help="copy files only but do not install bootloader")
43 parser.add_option("--dry-run", dest="dryrun", action="store_true",
44 help="avoid executing commands")
45 parser.add_option("--fat16", dest="fat16", action="store_true",
46 help="format specified partition with FAT16")
47 parser.add_option("--force", dest="force", action="store_true",
48 help="force any actions requiring manual interaction")
49 parser.add_option("--grub", dest="grub", action="store_true",
50 help="install grub bootloader instead of syslinux [TODO]")
51 parser.add_option("--initrd", dest="initrd", action="store", type="string",
52 help="install specified initrd instead of the default [TODO]")
53 parser.add_option("--kernel", dest="kernel", action="store", type="string",
54 help="install specified kernel instead of the default [TODO]")
55 parser.add_option("--lilo", dest="lilo", action="store", type="string",
56 help="lilo executable to be used for installing MBR")
57 parser.add_option("--quiet", dest="quiet", action="store_true",
58 help="do not output anything but just errors on console")
59 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
60 help="do not install /boot/addons/ files")
61 parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
62 help="do not install a master boot record (MBR) on the device")
63 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
64 help="install specified squashfs file instead of the default [TODO]")
65 parser.add_option("--uninstall", dest="uninstall", action="store_true",
66 help="remove grml ISO files from specified device [TODO]")
67 parser.add_option("--verbose", dest="verbose", action="store_true",
68 help="enable verbose mode")
69 parser.add_option("-v", "--version", dest="version", action="store_true",
70 help="display version and exit")
71 (options, args) = parser.parse_args()
74 class CriticalException(Exception):
75 """Throw critical exception if the exact error is not known but fatal."
77 @Exception: message"""
82 """Cleanup function to make sure there aren't any mounted devices left behind.
85 logging.info("Cleaning up before exiting...")
86 proc = subprocess.Popen(["sync"])
90 for device in MOUNTED:
92 # ignore: RuntimeError: Set changed size during iteration
94 logging.debug('caught expection RuntimeError, ignoring')
97 def register_tmpfile(path):
104 def unregister_tmpfile(path):
109 TMPFILES.remove(path)
112 def register_mountpoint(target):
119 def unregister_mountpoint(target):
123 if target in MOUNTED:
124 MOUNTED.remove(target)
127 def get_function_name(obj):
128 """Helper function for use in execute() to retrive name of a function
130 @obj: the function object
132 if not (isroutine(obj) or isclass(obj)):
134 return obj.__module__ + '.' + obj.__name__
137 def execute(f, *exec_arguments):
138 """Wrapper for executing a command. Either really executes
139 the command (default) or when using --dry-run commandline option
140 just displays what would be executed."""
141 # usage: execute(subprocess.Popen, (["ls", "-la"]))
142 # TODO: doesn't work for proc = execute(subprocess.Popen...() -> any ideas?
144 # pylint: disable-msg=W0141
145 logging.debug('dry-run only: %s(%s)' % (get_function_name(f), ', '.join(map(repr, exec_arguments))))
147 # pylint: disable-msg=W0142
148 return f(*exec_arguments)
152 """Check whether a given file can be executed
154 @fpath: full path to file
156 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
160 """Check whether a given program is available in PATH
162 @program: name of executable"""
163 fpath = os.path.split(program)[0]
168 for path in os.environ["PATH"].split(os.pathsep):
169 exe_file = os.path.join(path, program)
176 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
177 """Given a search path, find file
179 @filename: name of file to search for
180 @search_path: path where searching for the specified filename"""
182 paths = search_path.split(os.pathsep)
183 current_dir = '' # make pylint happy :)
185 # pylint: disable-msg=W0612
186 for current_dir, directories, files in os.walk(path):
187 if os.path.exists(os.path.join(current_dir, filename)):
191 return os.path.abspath(os.path.join(current_dir, filename))
196 def check_uid_root():
197 """Check for root permissions"""
198 if not os.geteuid()==0:
199 sys.exit("Error: please run this script with uid 0 (root).")
202 def mkfs_fat16(device):
203 """Format specified device with VFAT/FAT16 filesystem.
205 @device: partition that should be formated"""
207 # syslinux -d boot/isolinux /dev/sdb1
208 logging.info("Formating partition with fat16 filesystem")
209 logging.debug("mkfs.vfat -F 16 %s" % device)
210 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
212 if proc.returncode != 0:
213 raise Exception("error executing mkfs.vfat")
216 def generate_grub_config(grml_flavour):
217 """Generate grub configuration for use via menu.lst
219 @grml_flavour: name of grml flavour the configuration should be generated for"""
221 # * what about systems using grub2 without having grub1 available?
227 # color red/blue green/black
228 splashimage=/boot/grub/splash.xpm.gz
233 title %(grml_flavour)s - Default boot (using 1024x768 framebuffer)
234 kernel /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s
235 initrd /boot/release/%(grml_flavour)s/initrd.gz
237 # TODO: extend configuration :)
238 """ % {'grml_flavour': grml_flavour} )
241 def generate_isolinux_splash(grml_flavour):
242 """Generate bootsplash for isolinux/syslinux
244 @grml_flavour: name of grml flavour the configuration should be generated for"""
246 # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
248 grml_name = grml_flavour
251 \ f17
\f\18/boot/syslinux/logo.16
253 Some information and boot options available via keys F2 - F10. http://grml.org/
255 """ % {'grml_name': grml_name} )
258 def generate_main_syslinux_config(grml_flavour, bootoptions):
259 """Generate main configuration for use in syslinux.cfg
261 @grml_flavour: name of grml flavour the configuration should be generated for
262 @bootoptions: bootoptions that should be used as a default"""
264 local_datestamp = DATESTAMP
267 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
268 # use this to control the bootup via a serial port
273 DISPLAY /boot/syslinux/boot.msg
274 F1 /boot/syslinux/boot.msg
283 F10 /boot/syslinux/f10
284 ## end of main configuration
286 ## global configuration
287 # the default option (using %(grml_flavour)s)
289 KERNEL /boot/release/%(grml_flavour)s/linux26
290 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
294 KERNEL /boot/addons/memtest
299 KERNEL /boot/addons/memdisk
300 APPEND initrd=/boot/addons/allinone.img
305 KERNEL /boot/addons/memdisk
306 APPEND initrd=/boot/addons/balder10.imz
308 ## end of global configuration
309 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
312 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
313 """Generate flavour specific configuration for use in syslinux.cfg
315 @grml_flavour: name of grml flavour the configuration should be generated for
316 @bootoptions: bootoptions that should be used as a default"""
318 local_datestamp = DATESTAMP
322 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
323 LABEL %(grml_flavour)s
324 KERNEL /boot/release/%(grml_flavour)s/linux26
325 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce vga=791 quiet module=%(grml_flavour)s %(bootoptions)s
327 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
328 LABEL %(grml_flavour)s2ram
329 KERNEL /boot/release/%(grml_flavour)s/linux26
330 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
332 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
333 LABEL %(grml_flavour)s-debug
334 KERNEL /boot/release/%(grml_flavour)s/linux26
335 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
337 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
338 LABEL %(grml_flavour)s-x
339 KERNEL /boot/release/%(grml_flavour)s/linux26
340 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
342 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
343 LABEL %(grml_flavour)s-nofb
344 KERNEL /boot/release/%(grml_flavour)s/linux26
345 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
347 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
348 LABEL %(grml_flavour)s-failsafe
349 KERNEL /boot/release/%(grml_flavour)s/linux26
350 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
352 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
353 LABEL %(grml_flavour)s-forensic
354 KERNEL /boot/release/%(grml_flavour)s/linux26
355 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
357 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
358 LABEL %(grml_flavour)s-serial
359 KERNEL /boot/release/%(grml_flavour)s/linux26
360 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
361 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
364 def install_grub(device):
365 """Install grub on specified device.
367 @device: partition where grub should be installed to"""
370 logging.info("Would execute grub-install %s now.", device)
372 logging.critical("TODO: sorry - grub-install %s not implemented yet" % device)
375 def install_syslinux(device):
376 """Install syslinux on specified device.
378 @device: partition where syslinux should be installed to"""
381 logging.info("Would install syslinux as bootloader on %s", device)
384 # syslinux -d boot/isolinux /dev/sdb1
385 logging.info("Installing syslinux as bootloader")
386 logging.debug("syslinux -d boot/syslinux %s" % device)
387 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
389 if proc.returncode != 0:
390 raise Exception("error executing syslinux")
393 def install_bootloader(device):
394 """Install bootloader on specified device.
396 @device: partition where bootloader should be installed to"""
398 # Install bootloader on the device (/dev/sda),
399 # not on the partition itself (/dev/sda1)?
400 #if partition[-1:].isdigit():
401 # device = re.match(r'(.*?)\d*$', partition).group(1)
408 install_syslinux(device)
411 def install_lilo_mbr(lilo, device):
414 # TODO: check out the *real* difference between:
415 # * mbr-install /dev/ice
416 # * lilo -S /dev/null -M /dev/ice ext && lilo -S /dev/null -A /dev/ice 1
417 # * cat /usr/lib/syslinux/mbr.bin > /dev/ice
418 # * syslinux -sf /dev/iceX
421 # to support -A for extended partitions:
422 logging.info("Installing MBR")
423 logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
424 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
426 if proc.returncode != 0:
427 raise Exception("error executing lilo")
429 # activate partition:
430 logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
431 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
433 if proc.returncode != 0:
434 raise Exception("error executing lilo")
437 def install_syslinux_mbr(device):
440 # lilo's mbr is broken, use the one from syslinux instead:
441 if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
442 raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
444 logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
446 # TODO -> use Popen instead?
447 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
449 logging.critical("Error copying MBR to device (%s)" % retcode)
450 except OSError, error:
451 logging.critical("Execution failed:", error)
454 def install_mbr(device):
455 """Install a default master boot record on given device
457 @device: device where MBR should be installed to"""
459 if not is_writeable(device):
460 raise IOError("device not writeable for user")
462 # try to use system's lilo
466 # otherwise fall back to our static version
467 from platform import architecture
468 if architecture()[0] == '64bit':
469 lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
471 lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
472 # finally prefer a specified lilo executable
477 raise Exception("lilo executable can not be execute")
480 logging.info("Would install MBR running lilo and using syslinux.")
483 install_lilo_mbr(lilo, device)
484 install_syslinux_mbr(device)
487 def is_writeable(device):
488 """Check if the device is writeable for the current user
490 @device: partition where bootloader should be installed to"""
494 #raise Exception("no device for checking write permissions")
496 if not os.path.exists(device):
499 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
502 def mount(source, target, mount_options):
503 """Mount specified source on given target
505 @source: name of device/ISO that should be mounted
506 @target: directory where the ISO should be mounted to
507 @options: mount specific options"""
509 # notice: options.dryrun does not work here, as we have to
510 # locate files and identify the grml flavour
511 logging.debug("mount %s %s %s" % (mount_options, source, target))
512 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
514 if proc.returncode != 0:
515 raise CriticalException("Error executing mount")
517 logging.debug("register_mountpoint(%s)" % target)
518 register_mountpoint(target)
521 def unmount(target, unmount_options):
522 """Unmount specified target
524 @target: target where something is mounted on and which should be unmounted
525 @options: options for umount command"""
527 # make sure we unmount only already mounted targets
528 target_unmount = False
529 mounts = open('/proc/mounts').readlines()
530 mountstring = re.compile(".*%s.*" % re.escape(target))
532 if re.match(mountstring, line):
533 target_unmount = True
535 if not target_unmount:
536 logging.debug("%s not mounted anymore" % target)
538 logging.debug("umount %s %s" % (list(unmount_options), target))
539 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
541 if proc.returncode != 0:
542 raise Exception("Error executing umount")
544 logging.debug("unregister_mountpoint(%s)" % target)
545 unregister_mountpoint(target)
548 def check_for_usbdevice(device):
549 """Check whether the specified device is a removable USB device
551 @device: device name, like /dev/sda1 or /dev/sda
554 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
555 usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
556 if os.path.isfile(usbdevice):
557 is_usb = open(usbdevice).readline()
564 def check_for_fat(partition):
565 """Check whether specified partition is a valid VFAT/FAT16 filesystem
567 @partition: device name of partition"""
570 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition],
571 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
572 filesystem = udev_info.communicate()[0].rstrip()
574 if udev_info.returncode == 2:
575 raise CriticalException("Failed to read device %s"
576 "(wrong UID/permissions or device not present?)" % partition)
578 if filesystem != "vfat":
579 raise CriticalException("Device %s does not contain a FAT16 partition." % partition)
582 raise CriticalException("Sorry, /lib/udev/vol_id not available.")
585 def mkdir(directory):
586 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
588 # just silently pass as it's just fine it the directory exists
589 if not os.path.isdir(directory):
591 os.makedirs(directory)
592 # pylint: disable-msg=W0704
597 def copy_system_files(grml_flavour, iso_mount, target):
600 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
602 logging.critical("Fatal: squashfs file not found")
604 squashfs_target = target + '/live/'
605 execute(mkdir, squashfs_target)
606 # use install(1) for now to make sure we can write the files afterwards as normal user as well
607 logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
608 proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
611 filesystem_module = search_file('filesystem.module', iso_mount)
612 if filesystem_module is None:
613 logging.critical("Fatal: filesystem.module not found")
615 logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
616 proc = subprocess.Popen(["install", "--mode=664", filesystem_module,
617 squashfs_target + grml_flavour + '.module'])
620 release_target = target + '/boot/release/' + grml_flavour
621 execute(mkdir, release_target)
623 kernel = search_file('linux26', iso_mount)
625 logging.critical("Fatal kernel not found")
627 logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
628 proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
631 initrd = search_file('initrd.gz', iso_mount)
633 logging.critical("Fatal: initrd not found")
635 logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
636 proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
640 def copy_grml_files(iso_mount, target):
643 grml_target = target + '/grml/'
644 execute(mkdir, grml_target)
646 for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
647 grml_file = search_file(myfile, iso_mount)
648 if grml_file is None:
649 logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
651 logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
652 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
655 grml_web_target = grml_target + '/web/'
656 execute(mkdir, grml_web_target)
658 for myfile in 'index.html', 'style.css':
659 grml_file = search_file(myfile, iso_mount)
660 if grml_file is None:
661 logging.warn("Warning: myfile %s could not be found - can not install it")
663 logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
664 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
667 grml_webimg_target = grml_web_target + '/images/'
668 execute(mkdir, grml_webimg_target)
670 for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
671 grml_file = search_file(myfile, iso_mount)
672 if grml_file is None:
673 logging.warn("Warning: myfile %s could not be found - can not install it")
675 logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
676 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
680 def copy_addons(iso_mount, target):
682 addons = target + '/boot/addons/'
683 execute(mkdir, addons)
685 # grub all-in-one image
686 allinoneimg = search_file('allinone.img', iso_mount)
687 if allinoneimg is None:
688 logging.warn("Warning: allinone.img not found - can not install it")
690 logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
691 proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
695 balderimg = search_file('balder10.imz', iso_mount)
696 if balderimg is None:
697 logging.warn("Warning: balder10.imz not found - can not install it")
699 logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
700 proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
704 memdiskimg = search_file('memdisk', iso_mount)
705 if memdiskimg is None:
706 logging.warn("Warning: memdisk not found - can not install it")
708 logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
709 proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
713 memtestimg = search_file('memtest', iso_mount)
714 if memtestimg is None:
715 logging.warn("Warning: memtest not found - can not install it")
717 logging.debug("cp %s %s" % (memtestimg, addons + '/memtest'))
718 proc = subprocess.Popen(["install", "--mode=664", memtestimg, addons + 'memtest'])
722 def copy_bootloader_files(iso_mount, target):
725 syslinux_target = target + '/boot/syslinux/'
726 execute(mkdir, syslinux_target)
728 logo = search_file('logo.16', iso_mount)
729 logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
730 proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
733 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
734 bootsplash = search_file(ffile, iso_mount)
735 logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
736 proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
739 grub_target = target + '/boot/grub/'
740 execute(mkdir, grub_target)
742 if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
743 logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
746 logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
747 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz',
748 grub_target + 'splash.xpm.gz'])
751 if not os.path.isfile("/usr/share/grml2usb/grub/stage2_eltorito"):
752 logging.critical("Error: /usr/share/grml2usb/grub/stage2_eltorito can not be read.")
755 logging.debug("cp /usr/share/grml2usb/grub/stage2_eltorito to %s" % grub_target + 'stage2_eltorito')
756 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/stage2_eltorito',
757 grub_target + 'stage2_eltorito'])
761 def install_iso_files(grml_flavour, iso_mount, target):
762 """Copy files from ISO on given target"""
765 # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
766 # * provide alternative search_file() if file information is stored in a config.ini file?
767 # * catch "install: .. No space left on device" & CO
768 # * abstract copy logic to make the code shorter and get rid of spaghettis ;)
771 logging.info("Would copy files to %s", iso_mount)
773 elif not options.bootloaderonly:
774 logging.info("Copying files. This might take a while....")
775 copy_system_files(grml_flavour, iso_mount, target)
776 copy_grml_files(iso_mount, target)
778 if not options.skipaddons:
779 copy_addons(iso_mount, target)
781 if not options.copyonly:
782 copy_bootloader_files(iso_mount, target)
784 if not options.dryrun:
785 handle_bootloader_config(grml_flavour, target) # FIXME
787 # make sure we sync filesystems before returning
788 proc = subprocess.Popen(["sync"])
792 def uninstall_files(device):
793 """Get rid of all grml files on specified device
795 @device: partition where grml2usb files should be removed from"""
798 logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
801 def identify_grml_flavour(mountpath):
802 """Get name of grml flavour
804 @mountpath: path where the grml ISO is mounted to
805 @return: name of grml-flavour"""
807 version_file = search_file('grml-version', mountpath)
809 if version_file == "":
810 logging.critical("Error: could not find grml-version file.")
814 tmpfile = open(version_file, 'r')
815 grml_info = tmpfile.readline()
816 grml_flavour = re.match(r'[\w-]*', grml_info).group()
820 logging.critical("Unexpected error:", sys.exc_info()[0])
826 def handle_bootloader_config(grml_flavour, target):
829 logging.debug("Generating grub configuration")
830 #with open("...", "w") as f:
831 #f.write("bla bla bal")
833 grub_target = target + '/boot/grub/'
834 # should be present via copy_bootloader_files(), but make sure it exists:
835 execute(mkdir, grub_target)
836 grub_config_file = open(grub_target + 'menu.lst', 'w')
837 grub_config_file.write(generate_grub_config(grml_flavour))
838 grub_config_file.close()
840 logging.info("Generating syslinux configuration")
841 syslinux_target = target + '/boot/syslinux/'
842 # should be present via copy_bootloader_files(), but make sure it exits:
843 execute(mkdir, syslinux_target)
844 syslinux_cfg = syslinux_target + 'syslinux.cfg'
846 # install main configuration only *once*, no matter how many ISOs we have:
847 if os.path.isfile(syslinux_cfg):
848 string = open(syslinux_cfg).readline()
849 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
850 if not re.match(main_identifier, string):
851 syslinux_config_file = open(syslinux_cfg, 'w')
852 logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
853 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
854 syslinux_config_file.close()
856 syslinux_config_file = open(syslinux_cfg, 'w')
857 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
858 syslinux_config_file.close()
860 # install flavour specific configuration only *once* as well
861 # kind of ugly - I'm pretty sure this could be smoother...
862 flavour_config = True
863 if os.path.isfile(syslinux_cfg):
864 string = open(syslinux_cfg).readlines()
865 logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
866 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
868 if flavour.match(line):
869 flavour_config = False
872 syslinux_config_file = open(syslinux_cfg, 'a')
873 syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, options.bootoptions))
874 syslinux_config_file.close( )
876 logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
877 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
878 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
879 isolinux_splash.close( )
882 def handle_iso(iso, device):
883 """Main logic for mounting ISOs and copying files.
885 @iso: full path to the ISO that should be installed to the specified device
886 @device: partition where the specified ISO should be installed to"""
888 logging.info("Using ISO %s" % iso)
890 if os.path.isdir(iso):
891 logging.critical("TODO: /live/image handling not yet implemented - sorry") # TODO
894 iso_mountpoint = tempfile.mkdtemp()
895 register_tmpfile(iso_mountpoint)
896 remove_iso_mountpoint = True
898 if not os.path.isfile(iso):
899 logging.critical("Fatal: specified ISO %s could not be read" % iso)
904 mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
905 except CriticalException, error:
906 logging.critical("Fatal: %s" % error)
909 if os.path.isdir(device):
910 logging.info("Specified target is a directory, not mounting therefor.")
911 device_mountpoint = device
912 remove_device_mountpoint = False
915 device_mountpoint = tempfile.mkdtemp()
916 register_tmpfile(device_mountpoint)
917 remove_device_mountpoint = True
919 mount(device, device_mountpoint, "")
920 except CriticalException, error:
921 logging.critical("Fatal: %s" % error)
925 grml_flavour = identify_grml_flavour(iso_mountpoint)
926 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
927 install_iso_files(grml_flavour, iso_mountpoint, device_mountpoint)
929 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
932 if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
933 unmount(iso_mountpoint, "")
934 os.rmdir(iso_mountpoint)
935 unregister_tmpfile(iso_mountpoint)
936 if remove_device_mountpoint:
937 unmount(device_mountpoint, "")
938 if os.path.isdir(device_mountpoint):
939 os.rmdir(device_mountpoint)
940 unregister_tmpfile(device_mountpoint)
943 def handle_mbr(device):
947 # if not options.mbr:
948 # logging.info("You are NOT using the --mbr option. Consider using it if your device does not boot.")
950 # make sure we install MBR on /dev/sdX and not /dev/sdX#
952 # make sure we have syslinux available
954 if not options.skipmbr:
955 if not which("syslinux") and not options.copyonly and not options.dryrun:
956 logging.critical('Sorry, syslinux not available. Exiting.')
957 logging.critical('Please install syslinux or consider using the --grub option.')
960 if not options.skipmbr:
961 if device[-1:].isdigit():
962 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
965 install_mbr(mbr_device)
966 except IOError, error:
967 logging.critical("Execution failed: %s", error)
969 except Exception, error:
970 logging.critical("Execution failed: %s", error)
974 def handle_vfat(device):
977 # make sure we have mkfs.vfat available
978 if options.fat16 and not options.force:
979 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
980 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
981 logging.critical('Please make sure to install dosfstools.')
984 # make sure the user is aware of what he is doing
985 f = raw_input("Are you sure you want to format the device with a fat16 filesystem? y/N ")
986 if f == "y" or f == "Y":
987 logging.info("Note: you can skip this question using the option --force")
992 # check for vfat filesystem
993 if device is not None and not os.path.isdir(device):
995 check_for_fat(device)
996 except CriticalException, error:
997 logging.critical("Execution failed: %s", error)
1000 if not check_for_usbdevice(device):
1001 print "Warning: the specified device %s does not look like a removable usb device." % device
1002 f = raw_input("Do you really want to continue? y/N ")
1003 if f == "y" or f == "Y":
1009 def handle_compat_warning(device):
1012 # make sure we can replace old grml2usb script and warn user when using old way of life:
1013 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
1014 print "Warning: the semantics of grml2usb has changed."
1015 print "Instead of using grml2usb /path/to/iso %s you might" % device
1016 print "want to use grml2usb /path/to/iso /dev/... instead."
1017 print "Please check out the grml2usb manpage for details."
1018 f = raw_input("Do you really want to continue? y/N ")
1019 if f == "y" or f == "Y":
1025 def handle_logging():
1029 FORMAT = "%(asctime)-15s %(message)s"
1030 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1032 FORMAT = "Critial: %(message)s"
1033 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1035 FORMAT = "Info: %(message)s"
1036 logging.basicConfig(level=logging.INFO, format=FORMAT)
1039 def handle_bootloader(device):
1041 # Install bootloader only if not using the --copy-only option
1042 if options.copyonly:
1043 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1045 install_bootloader(device)
1049 """Main function [make pylint happy :)]"""
1052 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1056 parser.error("invalid usage")
1061 # make sure we have the appropriate permissions
1065 logging.info("Running in simulate mode as requested via option dry-run.")
1067 # specified arguments
1068 device = args[len(args) - 1]
1069 isos = args[0:len(args) - 1]
1071 # provide upgrade path
1072 handle_compat_warning(device)
1074 # check for vfat partition
1077 # main operation (like installing files)
1079 handle_iso(iso, device)
1084 handle_bootloader(device)
1086 # finally be politely :)
1087 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1090 if __name__ == "__main__":
1093 except KeyboardInterrupt:
1094 logging.info("Received KeyboardInterrupt")
1097 ## END OF FILE #################################################################
1098 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8