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/
16 * implement missing options (--grub, --kernel, --initrd, --squashfs, --uninstall)
17 * validate partition schema/layout: is the partition schema ok and the bootable flag set? (--validate?)
18 * provide --create-partition option?
19 * implement logic for storing information about copied files -> register every file in a set()
20 * the last line in bootsplash (boot.msg) should mention all installed grml flavours
22 - improve error handling wherever possible :)
23 - use 'with open("...", "w") as f: ... f.write("...")'
24 - simplify functions/code as much as possible, especially:
25 Too many local variables
28 * graphical version? any volunteers? :)
31 from __future__ import with_statement
32 from optparse import OptionParser
33 from inspect import isroutine, isclass
34 import datetime, logging, os, re, subprocess, sys, tempfile, time
37 PROG_VERSION = "0.9.2(pre1)"
38 mounted = set() # register mountpoints
39 tmpfiles = set() # register tmpfiles
40 datestamp = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
43 usage = "Usage: %prog [options] <[ISO[s] | /live/image]> </dev/sdX#>\n\
45 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
46 Make sure you have at least one grml ISO or a running grml system (/live/image),\n\
47 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
48 and root access. Further information can be found in: man grml2usb"
50 parser = OptionParser(usage=usage)
51 parser.add_option("--bootoptions", dest="bootoptions",
52 action="store", type="string",
53 help="use specified bootoptions as default")
54 parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
55 help="do not copy files but just install a bootloader")
56 parser.add_option("--copy-only", dest="copyonly", action="store_true",
57 help="copy files only but do not install bootloader")
58 parser.add_option("--dry-run", dest="dryrun", action="store_true",
59 help="avoid executing commands")
60 parser.add_option("--fat16", dest="fat16", action="store_true",
61 help="format specified partition with FAT16")
62 parser.add_option("--force", dest="force", action="store_true",
63 help="force any actions requiring manual interaction")
64 parser.add_option("--grub", dest="grub", action="store_true",
65 help="install grub bootloader instead of syslinux [TODO]")
66 parser.add_option("--initrd", dest="initrd", action="store", type="string",
67 help="install specified initrd instead of the default [TODO]")
68 parser.add_option("--kernel", dest="kernel", action="store", type="string",
69 help="install specified kernel instead of the default [TODO]")
70 parser.add_option("--lilo", dest="lilo", action="store", type="string",
71 help="lilo executable to be used for installing MBR")
72 parser.add_option("--mbr", dest="mbr", action="store_true",
73 help="install master boot record (MBR) on the device")
74 parser.add_option("--quiet", dest="quiet", action="store_true",
75 help="do not output anything but just errors on console")
76 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
77 help="do not install /boot/addons/ files")
78 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
79 help="install specified squashfs file instead of the default [TODO]")
80 parser.add_option("--uninstall", dest="uninstall", action="store_true",
81 help="remove grml ISO files from specified device [TODO]")
82 parser.add_option("--verbose", dest="verbose", action="store_true",
83 help="enable verbose mode")
84 parser.add_option("-v", "--version", dest="version", action="store_true",
85 help="display version and exit")
86 (options, args) = parser.parse_args()
90 """Cleanup function to make sure there aren't any mounted devices left behind.
93 logging.info("Cleaning up before exiting...")
94 proc = subprocess.Popen(["sync"])
98 for device in mounted:
100 # ignore: RuntimeError: Set changed size during iteration
105 def get_function_name(obj):
106 """Helper function for use in execute() to retrive name of a function
108 @obj: the function object
110 if not (isroutine(obj) or isclass(obj)):
112 return obj.__module__ + '.' + obj.__name__
115 def execute(f, *args):
116 """Wrapper for executing a command. Either really executes
117 the command (default) or when using --dry-run commandline option
118 just displays what would be executed."""
119 # usage: execute(subprocess.Popen, (["ls", "-la"]))
120 # TODO: doesn't work for proc = execute(subprocess.Popen...() -> any ideas?
122 logging.debug('dry-run only: %s(%s)' % (get_function_name(f), ', '.join(map(repr, args))))
128 """Check whether a given file can be executed
130 @fpath: full path to file
132 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
136 """Check whether a given program is available in PATH
138 @program: name of executable"""
139 fpath, fname = os.path.split(program)
144 for path in os.environ["PATH"].split(os.pathsep):
145 exe_file = os.path.join(path, program)
152 def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin'):
153 """Given a search path, find file
155 @filename: name of file to search for
156 @search_path: path where searching for the specified filename"""
158 paths = search_path.split(os.pathsep)
160 for current_dir, directories, files in os.walk(path):
161 if os.path.exists(os.path.join(current_dir, filename)):
165 return os.path.abspath(os.path.join(current_dir, filename))
170 def check_uid_root():
171 """Check for root permissions"""
172 if not os.geteuid()==0:
173 sys.exit("Error: please run this script with uid 0 (root).")
176 def mkfs_fat16(device):
177 """Format specified device with VFAT/FAT16 filesystem.
179 @device: partition that should be formated"""
181 # syslinux -d boot/isolinux /dev/sdb1
182 logging.info("Formating partition with fat16 filesystem")
183 logging.debug("mkfs.vfat -F 16 %s" % device)
184 proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
186 if proc.returncode != 0:
187 raise Exception, "error executing mkfs.vfat"
190 def install_syslinux(device):
191 """Install syslinux on specified device.
193 @device: partition where syslinux should be installed to"""
196 logging.info("Would install syslinux as bootloader on %s", device)
199 # syslinux -d boot/isolinux /dev/sdb1
200 logging.info("Installing syslinux as bootloader")
201 logging.debug("syslinux -d boot/syslinux %s" % device)
202 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
204 if proc.returncode != 0:
205 raise Exception, "error executing syslinux"
208 def generate_grub_config(grml_flavour):
209 """Generate grub configuration for use via menu.lst
211 @grml_flavour: name of grml flavour the configuration should be generated for"""
213 # * what about systems using grub2 without having grub1 available?
219 # color red/blue green/black
220 splashimage=/boot/grub/splash.xpm.gz
225 title %(grml_flavour)s - Default boot (using 1024x768 framebuffer)
226 kernel /boot/release/%(grml_flavour)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_flavour)s
227 initrd /boot/release/%(grml_flavour)s/initrd.gz
229 # TODO: extend configuration :)
233 def generate_isolinux_splash(grml_flavour):
234 """Generate bootsplash for isolinux/syslinux
236 @grml_flavour: name of grml flavour the configuration should be generated for"""
238 # TODO: adjust last bootsplash line (the one following the "Some information and boot ...")
240 grml_name = grml_flavour
243 \ f17
\f\18/boot/syslinux/logo.16
245 Some information and boot options available via keys F2 - F10. http://grml.org/
250 def generate_main_syslinux_config(grml_flavour, bootoptions):
251 """Generate main configuration for use in syslinux.cfg
253 @grml_flavour: name of grml flavour the configuration should be generated for
254 @bootoptions: bootoptions that should be used as a default"""
256 local_datestamp = datestamp
259 ## main syslinux configuration - generated by grml2usb [main config generated at: %(local_datestamp)s]
260 # use this to control the bootup via a serial port
265 DISPLAY /boot/syslinux/boot.msg
266 F1 /boot/syslinux/boot.msg
275 F10 /boot/syslinux/f10
276 ## end of main configuration
278 ## global configuration
279 # the default option (using %(grml_flavour)s)
281 KERNEL /boot/release/%(grml_flavour)s/linux26
282 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s %(bootoptions)s
286 KERNEL /boot/addons/memtest
287 #APPEND BOOT_IMAGE=memtest
292 KERNEL /boot/addons/memdisk
293 APPEND initrd=/boot/addons/allinone.img
298 KERNEL /boot/addons/memdisk
299 APPEND initrd=/boot/addons/balder10.imz
301 ## end of global configuration
305 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
306 """Generate flavour specific configuration for use in syslinux.cfg
308 @grml_flavour: name of grml flavour the configuration should be generated for
309 @bootoptions: bootoptions that should be used as a default"""
311 local_datestamp = datestamp
315 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
316 LABEL %(grml_flavour)s
317 KERNEL /boot/release/%(grml_flavour)s/linux26
318 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s %(bootoptions)s
320 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
321 LABEL %(grml_flavour)s2ram
322 KERNEL /boot/release/%(grml_flavour)s/linux26
323 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s toram=%(grml_flavour)s %(bootoptions)s
325 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
326 LABEL %(grml_flavour)s-debug
327 KERNEL /boot/release/%(grml_flavour)s/linux26
328 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s debug boot=live initcall_debug%(bootoptions)s
330 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
331 LABEL %(grml_flavour)s-x
332 KERNEL /boot/release/%(grml_flavour)s/linux26
333 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s startx=wm-ng %(bootoptions)s
335 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
336 LABEL %(grml_flavour)s-nofb
337 KERNEL /boot/release/%(grml_flavour)s/linux26
338 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
340 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
341 LABEL %(grml_flavour)s-failsafe
342 KERNEL /boot/release/%(grml_flavour)s/linux26
343 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
345 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
346 LABEL %(grml_flavour)s-forensic
347 KERNEL /boot/release/%(grml_flavour)s/linux26
348 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s nofstab noraid nolvm noautoconfig noswap raid=noautodetect %(bootoptions)s
350 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
351 LABEL %(grml_flavour)s-serial
352 KERNEL /boot/release/%(grml_flavour)s/linux26
353 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
357 def install_grub(device):
358 """Install grub on specified device.
360 @device: partition where grub should be installed to"""
363 logging.info("Would execute grub-install %s now.", device)
365 logging.critical("TODO: sorry - grub-install %s not implemented yet" % device)
368 def install_bootloader(device):
369 """Install bootloader on specified device.
371 @device: partition where bootloader should be installed to"""
373 # Install bootloader on the device (/dev/sda),
374 # not on the partition itself (/dev/sda1)?
375 #if partition[-1:].isdigit():
376 # device = re.match(r'(.*?)\d*$', partition).group(1)
383 install_syslinux(device)
386 def is_writeable(device):
387 """Check if the device is writeable for the current user
389 @device: partition where bootloader should be installed to"""
393 #raise Exception, "no device for checking write permissions"
395 if not os.path.exists(device):
398 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
401 def install_mbr(device):
402 """Install a default master boot record on given device
404 @device: device where MBR should be installed to"""
406 if not is_writeable(device):
407 raise IOError, "device not writeable for user"
413 # otherwise try to use system's lilo
416 print "debug: lilo = %s" % lilo
418 # finally fall back to our static version
419 from platform import architecture
420 if architecture()[0] == '64bit':
421 lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
423 lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
426 raise Exception, "lilo executable can not be execute"
429 logging.info("Would install MBR running lilo and using syslinux.")
432 # to support -A for extended partitions:
433 logging.info("Installing MBR")
434 logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
435 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
437 if proc.returncode != 0:
438 raise Exception, "error executing lilo"
440 # activate partition:
441 logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
442 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
444 if proc.returncode != 0:
445 raise Exception, "error executing lilo"
447 # lilo's mbr is broken, use the one from syslinux instead:
448 if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
449 raise Exception, "/usr/lib/syslinux/mbr.bin can not be read"
451 logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
453 # TODO -> use Popen instead?
454 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
456 logging.critical("Error copying MBR to device (%s)" % retcode)
457 except OSError, error:
458 logging.critical("Execution failed:", error)
461 def register_tmpfile(path):
468 def unregister_tmpfile(path):
473 tmpfiles.remove(path)
476 def register_mountpoint(target):
483 def unregister_mountpoint(target):
487 if target in mounted:
488 mounted.remove(target)
491 def mount(source, target, mount_options):
492 """Mount specified source on given target
494 @source: name of device/ISO that should be mounted
495 @target: directory where the ISO should be mounted to
496 @options: mount specific options"""
498 # notice: options.dryrun does not work here, as we have to
499 # locate files and identify the grml flavour
500 logging.debug("mount %s %s %s" % (mount_options, source, target))
501 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
503 if proc.returncode != 0:
504 raise Exception, "Error executing mount"
506 logging.debug("register_mountpoint(%s)" % target)
507 register_mountpoint(target)
510 def unmount(target, unmount_options):
511 """Unmount specified target
513 @target: target where something is mounted on and which should be unmounted
514 @options: options for umount command"""
516 # make sure we unmount only already mounted targets
517 target_unmount = False
518 mounts = open('/proc/mounts').readlines()
519 mountstring = re.compile(".*%s.*" % re.escape(target))
521 if re.match(mountstring, line):
522 target_unmount = True
524 if not target_unmount:
525 logging.debug("%s not mounted anymore" % target)
527 logging.debug("umount %s %s" % (list(unmount_options), target))
528 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
530 if proc.returncode != 0:
531 raise Exception, "Error executing umount"
533 logging.debug("unregister_mountpoint(%s)" % target)
534 unregister_mountpoint(target)
537 def check_for_usbdevice(device):
538 """Check whether the specified device is a removable USB device
540 @device: device name, like /dev/sda1 or /dev/sda
543 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
544 usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
545 if os.path.isfile(usbdevice):
546 is_usb = open(usbdevice).readline()
553 def check_for_fat(partition):
554 """Check whether specified partition is a valid VFAT/FAT16 filesystem
556 @partition: device name of partition"""
559 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
560 filesystem = udev_info.communicate()[0].rstrip()
562 if udev_info.returncode == 2:
563 raise Exception, "Failed to read device %s - wrong UID / permissions?" % partition
565 if filesystem != "vfat":
566 raise Exception, "Device %s does not contain a FAT16 partition." % partition
569 raise Exception, "Sorry, /lib/udev/vol_id not available."
572 def mkdir(directory):
573 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
575 if not os.path.isdir(directory):
577 os.makedirs(directory)
579 # just silently pass as it's just fine it the directory exists
583 def copy_grml_files(grml_flavour, iso_mount, target):
584 """Copy files from ISO on given target"""
587 # * provide alternative search_file() if file information is stored in a config.ini file?
588 # * catch "install: .. No space left on device" & CO
589 # * abstract copy logic to make the code shorter and get rid of spaghettis ;)
592 logging.info("Would copy files to %s", iso_mount)
594 elif not options.bootloaderonly:
595 logging.info("Copying files. This might take a while....")
597 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
599 logging.critical("Fatal: squashfs file not found")
601 squashfs_target = target + '/live/'
602 execute(mkdir, squashfs_target)
603 # use install(1) for now to make sure we can write the files afterwards as normal user as well
604 logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
605 proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
608 filesystem_module = search_file('filesystem.module', iso_mount)
609 if filesystem_module is None:
610 logging.critical("Fatal: filesystem.module not found")
612 logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
613 proc = subprocess.Popen(["install", "--mode=664", filesystem_module, squashfs_target + grml_flavour + '.module'])
616 release_target = target + '/boot/release/' + grml_flavour
617 execute(mkdir, release_target)
619 kernel = search_file('linux26', iso_mount)
621 logging.critical("Fatal kernel not found")
623 logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
624 proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
627 initrd = search_file('initrd.gz', iso_mount)
629 logging.critical("Fatal: initrd not found")
631 logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
632 proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
635 grml_target = target + '/grml/'
636 execute(mkdir, grml_target)
638 for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
639 grml_file = search_file(myfile, iso_mount)
640 if grml_file is None:
641 logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
643 logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
644 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
647 grml_web_target = grml_target + '/web/'
648 execute(mkdir, grml_web_target)
650 for myfile in 'index.html', 'style.css':
651 grml_file = search_file(myfile, iso_mount)
652 if grml_file is None:
653 logging.warn("Warning: myfile %s could not be found - can not install it")
655 logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
656 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
659 grml_webimg_target = grml_web_target + '/images/'
660 execute(mkdir, grml_webimg_target)
662 for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
663 grml_file = search_file(myfile, iso_mount)
664 if grml_file is None:
665 logging.warn("Warning: myfile %s could not be found - can not install it")
667 logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
668 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
671 if not options.skipaddons:
672 addons = target + '/boot/addons/'
673 execute(mkdir, addons)
675 # grub all-in-one image
676 allinoneimg = search_file('allinone.img', iso_mount)
677 if allinoneimg is None:
678 logging.warn("Warning: allinone.img not found - can not install it")
680 logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
681 proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
685 balderimg = search_file('balder10.imz', iso_mount)
686 if balderimg is None:
687 logging.warn("Warning: balder10.imz not found - can not install it")
689 logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
690 proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
694 memdiskimg = search_file('memdisk', iso_mount)
695 if memdiskimg is None:
696 logging.warn("Warning: memdisk not found - can not install it")
698 logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
699 proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
702 if not options.copyonly:
703 syslinux_target = target + '/boot/syslinux/'
704 execute(mkdir, syslinux_target)
706 logo = search_file('logo.16', iso_mount)
707 logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
708 proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
711 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
712 bootsplash = search_file(ffile, iso_mount)
713 logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
714 proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
717 grub_target = target + '/boot/grub/'
718 execute(mkdir, grub_target)
720 if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
721 logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
724 logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
725 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz', grub_target + 'splash.xpm.gz'])
728 if not os.path.isfile("/usr/share/grml2usb/grub/stage2_eltorito"):
729 logging.critical("Error: /usr/share/grml2usb/grub/stage2_eltorito can not be read.")
732 logging.debug("cp /usr/share/grml2usb/grub/stage2_eltorito to %s" % grub_target + 'stage2_eltorito')
733 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/stage2_eltorito', grub_target + 'stage2_eltorito'])
736 if not options.dryrun:
737 logging.debug("Generating grub configuration")
738 #with open("...", "w") as f:
739 #f.write("bla bla bal")
740 grub_config_file = open(grub_target + 'menu.lst', 'w')
741 grub_config_file.write(generate_grub_config(grml_flavour))
742 grub_config_file.close()
744 logging.info("Generating syslinux configuration")
745 syslinux_cfg = syslinux_target + 'syslinux.cfg'
747 # install main configuration only *once*, no matter how many ISOs we have:
748 if os.path.isfile(syslinux_cfg):
749 string = open(syslinux_cfg).readline()
750 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(datestamp)))
751 if not re.match(main_identifier, string):
752 syslinux_config_file = open(syslinux_cfg, 'w')
753 logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
754 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
755 syslinux_config_file.close()
757 syslinux_config_file = open(syslinux_cfg, 'w')
758 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
759 syslinux_config_file.close()
761 # install flavour specific configuration only *once* as well
762 # kind of ugly - I'm pretty sure this could be smoother...
763 flavour_config = True
764 if os.path.isfile(syslinux_cfg):
765 string = open(syslinux_cfg).readlines()
766 logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
767 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(datestamp))))
769 if flavour.match(line):
770 flavour_config = False
774 syslinux_config_file = open(syslinux_cfg, 'a')
775 syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, options.bootoptions))
776 syslinux_config_file.close( )
778 logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
779 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
780 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
781 isolinux_splash.close( )
784 # make sure we sync filesystems before returning
785 proc = subprocess.Popen(["sync"])
789 def uninstall_files(device):
790 """Get rid of all grml files on specified device
792 @device: partition where grml2usb files should be removed from"""
795 logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
798 def identify_grml_flavour(mountpath):
799 """Get name of grml flavour
801 @mountpath: path where the grml ISO is mounted to
802 @return: name of grml-flavour"""
804 version_file = search_file('grml-version', mountpath)
806 if version_file == "":
807 logging.critical("Error: could not find grml-version file.")
811 tmpfile = open(version_file, 'r')
812 grml_info = tmpfile.readline()
813 grml_flavour = re.match(r'[\w-]*', grml_info).group()
817 logging.critical("Unexpected error:", sys.exc_info()[0])
823 def handle_iso(iso, device):
824 """Main logic for mounting ISOs and copying files.
826 @iso: full path to the ISO that should be installed to the specified device
827 @device: partition where the specified ISO should be installed to"""
829 logging.info("Using ISO %s" % iso)
831 if os.path.isdir(iso):
832 logging.critical("TODO: /live/image handling not yet implemented - sorry") # TODO
835 iso_mountpoint = tempfile.mkdtemp()
836 register_tmpfile(iso_mountpoint)
837 remove_iso_mountpoint = True
839 if not os.path.isfile(iso):
840 logging.critical("Fatal: specified ISO %s could not be read" % iso)
845 mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
846 except Exception, error:
847 logging.critical("Fatal: %s" % error)
850 if os.path.isdir(device):
851 logging.info("Specified target is a directory, not mounting therefor.")
852 device_mountpoint = device
853 remove_device_mountpoint = False
857 device_mountpoint = tempfile.mkdtemp()
858 register_tmpfile(device_mountpoint)
859 remove_device_mountpoint = True
861 mount(device, device_mountpoint, "")
862 except Exception, error:
863 logging.critical("Fatal: %s" % error)
867 grml_flavour = identify_grml_flavour(iso_mountpoint)
868 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
869 copy_grml_files(grml_flavour, iso_mountpoint, device_mountpoint)
871 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
874 if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
875 unmount(iso_mountpoint, "")
877 os.rmdir(iso_mountpoint)
878 unregister_tmpfile(iso_mountpoint)
880 if remove_device_mountpoint:
881 unmount(device_mountpoint, "")
883 if os.path.isdir(device_mountpoint):
884 os.rmdir(device_mountpoint)
885 unregister_tmpfile(device_mountpoint)
887 # grml_flavour_short = grml_flavour.replace('-','')
888 # logging.debug("grml_flavour_short = %s" % grml_flavour_short)
892 """Main function [make pylint happy :)]"""
895 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
899 parser.error("invalid usage")
903 FORMAT = "%(asctime)-15s %(message)s"
904 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
906 FORMAT = "Critial: %(message)s"
907 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
909 FORMAT = "Info: %(message)s"
910 logging.basicConfig(level=logging.INFO, format=FORMAT)
915 logging.info("Running in simulate mode as requested via option dry-run.")
917 # specified arguments
918 device = args[len(args) - 1]
919 isos = args[0:len(args) - 1]
921 # make sure we can replace old grml2usb script and warn user when using old way of life:
922 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
923 print "Warning: the semantics of grml2usb has changed."
924 print "Instead of using grml2usb /path/to/iso %s you might" % device
925 print "want to use grml2usb /path/to/iso /dev/... instead."
926 print "Please check out the grml2usb manpage for details."
927 f = raw_input("Do you really want to continue? y/N ")
928 if f == "y" or f == "Y":
933 # make sure we have syslinux available
935 if not which("syslinux") and not options.copyonly and not options.dryrun:
936 logging.critical('Sorry, syslinux not available. Exiting.')
937 logging.critical('Please install syslinux or consider using the --grub option.')
940 # make sure we have mkfs.vfat available
941 if options.fat16 and not options.force:
942 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
943 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
944 logging.critical('Please make sure to install dosfstools.')
947 # make sure the user is aware of what he is doing
948 f = raw_input("Are you sure you want to format the device with a fat16 filesystem? y/N ")
949 if f == "y" or f == "Y":
950 logging.info("Note: you can skip this question using the option --force")
955 # check for vfat filesystem
956 if device is not None and not os.path.isdir(device):
958 check_for_fat(device)
959 except Exception, error:
960 logging.critical("Execution failed: %s", error)
963 if not check_for_usbdevice(device):
964 print "Warning: the specified device %s does not look like a removable usb device." % device
965 f = raw_input("Do you really want to continue? y/N ")
966 if f == "y" or f == "Y":
975 # main operation (like installing files)
977 handle_iso(iso, device)
981 logging.info("You are NOT using the --mbr option. Consider using it if your device does not boot.")
983 # make sure we install MBR on /dev/sdX and not /dev/sdX#
984 if device[-1:].isdigit():
985 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
988 install_mbr(mbr_device)
989 except IOError, error:
990 logging.critical("Execution failed: %s", error)
992 except Exception, error:
993 logging.critical("Execution failed: %s", error)
996 # Install bootloader only if not using the --copy-only option
998 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1000 install_bootloader(device)
1002 # finally be politely :)
1003 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1006 if __name__ == "__main__":
1009 except KeyboardInterrupt:
1010 logging.info("Received KeyboardInterrupt")
1013 ## END OF FILE #################################################################
1014 # vim:foldmethod=marker expandtab ai ft=python tw=120 fileencoding=utf-8