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 quiet module=%(grml_flavour)s %(bootoptions)s
294 KERNEL /boot/addons/memtest
295 #APPEND BOOT_IMAGE=memtest
300 KERNEL /boot/addons/memdisk
301 APPEND initrd=/boot/addons/allinone.img
306 KERNEL /boot/addons/memdisk
307 APPEND initrd=/boot/addons/balder10.imz
309 ## end of global configuration
310 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
313 def generate_flavour_specific_syslinux_config(grml_flavour, bootoptions):
314 """Generate flavour specific configuration for use in syslinux.cfg
316 @grml_flavour: name of grml flavour the configuration should be generated for
317 @bootoptions: bootoptions that should be used as a default"""
319 local_datestamp = DATESTAMP
323 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
324 LABEL %(grml_flavour)s
325 KERNEL /boot/release/%(grml_flavour)s/linux26
326 APPEND initrd=/boot/release/%(grml_flavour)s/initrd.gz apm=power-off boot=live nomce quiet module=%(grml_flavour)s %(bootoptions)s
328 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
329 LABEL %(grml_flavour)s2ram
330 KERNEL /boot/release/%(grml_flavour)s/linux26
331 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
333 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
334 LABEL %(grml_flavour)s-debug
335 KERNEL /boot/release/%(grml_flavour)s/linux26
336 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
338 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
339 LABEL %(grml_flavour)s-x
340 KERNEL /boot/release/%(grml_flavour)s/linux26
341 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
343 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
344 LABEL %(grml_flavour)s-nofb
345 KERNEL /boot/release/%(grml_flavour)s/linux26
346 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
348 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
349 LABEL %(grml_flavour)s-failsafe
350 KERNEL /boot/release/%(grml_flavour)s/linux26
351 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
353 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
354 LABEL %(grml_flavour)s-forensic
355 KERNEL /boot/release/%(grml_flavour)s/linux26
356 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
358 # flavour specific configuration for %(grml_flavour)s [grml2usb for %(grml_flavour)s: %(local_datestamp)s]
359 LABEL %(grml_flavour)s-serial
360 KERNEL /boot/release/%(grml_flavour)s/linux26
361 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
362 """ % {'grml_flavour': grml_flavour, 'local_datestamp': local_datestamp, 'bootoptions': bootoptions} )
365 def install_grub(device):
366 """Install grub on specified device.
368 @device: partition where grub should be installed to"""
371 logging.info("Would execute grub-install %s now.", device)
373 logging.critical("TODO: sorry - grub-install %s not implemented yet" % device)
376 def install_syslinux(device):
377 """Install syslinux on specified device.
379 @device: partition where syslinux should be installed to"""
382 logging.info("Would install syslinux as bootloader on %s", device)
385 # syslinux -d boot/isolinux /dev/sdb1
386 logging.info("Installing syslinux as bootloader")
387 logging.debug("syslinux -d boot/syslinux %s" % device)
388 proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
390 if proc.returncode != 0:
391 raise Exception("error executing syslinux")
394 def install_bootloader(device):
395 """Install bootloader on specified device.
397 @device: partition where bootloader should be installed to"""
399 # Install bootloader on the device (/dev/sda),
400 # not on the partition itself (/dev/sda1)?
401 #if partition[-1:].isdigit():
402 # device = re.match(r'(.*?)\d*$', partition).group(1)
409 install_syslinux(device)
412 def install_lilo_mbr(lilo, device):
415 # to support -A for extended partitions:
416 logging.info("Installing MBR")
417 logging.debug("%s -S /dev/null -M %s ext" % (lilo, device))
418 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-M", device, "ext"])
420 if proc.returncode != 0:
421 raise Exception("error executing lilo")
423 # activate partition:
424 logging.debug("%s -S /dev/null -A %s 1" % (lilo, device))
425 proc = subprocess.Popen([lilo, "-S", "/dev/null", "-A", device, "1"])
427 if proc.returncode != 0:
428 raise Exception("error executing lilo")
431 def install_syslinux_mbr(device):
434 # lilo's mbr is broken, use the one from syslinux instead:
435 if not os.path.isfile("/usr/lib/syslinux/mbr.bin"):
436 raise Exception("/usr/lib/syslinux/mbr.bin can not be read")
438 logging.debug("cat /usr/lib/syslinux/mbr.bin > %s" % device)
440 # TODO -> use Popen instead?
441 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
443 logging.critical("Error copying MBR to device (%s)" % retcode)
444 except OSError, error:
445 logging.critical("Execution failed:", error)
448 def install_mbr(device):
449 """Install a default master boot record on given device
451 @device: device where MBR should be installed to"""
453 if not is_writeable(device):
454 raise IOError("device not writeable for user")
456 # try to use system's lilo
460 # otherwise fall back to our static version
461 from platform import architecture
462 if architecture()[0] == '64bit':
463 lilo = '/usr/share/grml2usb/lilo/lilo.static.amd64'
465 lilo = '/usr/share/grml2usb/lilo/lilo.static.i386'
466 # finally prefer a specified lilo executable
471 raise Exception("lilo executable can not be execute")
474 logging.info("Would install MBR running lilo and using syslinux.")
477 install_lilo_mbr(lilo, device)
478 install_syslinux_mbr(device)
481 def is_writeable(device):
482 """Check if the device is writeable for the current user
484 @device: partition where bootloader should be installed to"""
488 #raise Exception("no device for checking write permissions")
490 if not os.path.exists(device):
493 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
496 def mount(source, target, mount_options):
497 """Mount specified source on given target
499 @source: name of device/ISO that should be mounted
500 @target: directory where the ISO should be mounted to
501 @options: mount specific options"""
503 # notice: options.dryrun does not work here, as we have to
504 # locate files and identify the grml flavour
505 logging.debug("mount %s %s %s" % (mount_options, source, target))
506 proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
508 if proc.returncode != 0:
509 raise CriticalException("Error executing mount")
511 logging.debug("register_mountpoint(%s)" % target)
512 register_mountpoint(target)
515 def unmount(target, unmount_options):
516 """Unmount specified target
518 @target: target where something is mounted on and which should be unmounted
519 @options: options for umount command"""
521 # make sure we unmount only already mounted targets
522 target_unmount = False
523 mounts = open('/proc/mounts').readlines()
524 mountstring = re.compile(".*%s.*" % re.escape(target))
526 if re.match(mountstring, line):
527 target_unmount = True
529 if not target_unmount:
530 logging.debug("%s not mounted anymore" % target)
532 logging.debug("umount %s %s" % (list(unmount_options), target))
533 proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
535 if proc.returncode != 0:
536 raise Exception("Error executing umount")
538 logging.debug("unregister_mountpoint(%s)" % target)
539 unregister_mountpoint(target)
542 def check_for_usbdevice(device):
543 """Check whether the specified device is a removable USB device
545 @device: device name, like /dev/sda1 or /dev/sda
548 usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
549 usbdevice = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
550 if os.path.isfile(usbdevice):
551 is_usb = open(usbdevice).readline()
558 def check_for_fat(partition):
559 """Check whether specified partition is a valid VFAT/FAT16 filesystem
561 @partition: device name of partition"""
564 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t", partition],
565 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
566 filesystem = udev_info.communicate()[0].rstrip()
568 if udev_info.returncode == 2:
569 raise CriticalException("Failed to read device %s"
570 "(wrong UID/permissions or device not present?)" % partition)
572 if filesystem != "vfat":
573 raise CriticalException("Device %s does not contain a FAT16 partition." % partition)
576 raise CriticalException("Sorry, /lib/udev/vol_id not available.")
579 def mkdir(directory):
580 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
582 # just silently pass as it's just fine it the directory exists
583 if not os.path.isdir(directory):
585 os.makedirs(directory)
586 # pylint: disable-msg=W0704
591 def copy_system_files(grml_flavour, iso_mount, target):
594 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
596 logging.critical("Fatal: squashfs file not found")
598 squashfs_target = target + '/live/'
599 execute(mkdir, squashfs_target)
600 # use install(1) for now to make sure we can write the files afterwards as normal user as well
601 logging.debug("cp %s %s" % (squashfs, target + '/live/' + grml_flavour + '.squashfs'))
602 proc = subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
605 filesystem_module = search_file('filesystem.module', iso_mount)
606 if filesystem_module is None:
607 logging.critical("Fatal: filesystem.module not found")
609 logging.debug("cp %s %s" % (filesystem_module, squashfs_target + grml_flavour + '.module'))
610 proc = subprocess.Popen(["install", "--mode=664", filesystem_module,
611 squashfs_target + grml_flavour + '.module'])
614 release_target = target + '/boot/release/' + grml_flavour
615 execute(mkdir, release_target)
617 kernel = search_file('linux26', iso_mount)
619 logging.critical("Fatal kernel not found")
621 logging.debug("cp %s %s" % (kernel, release_target + '/linux26'))
622 proc = subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
625 initrd = search_file('initrd.gz', iso_mount)
627 logging.critical("Fatal: initrd not found")
629 logging.debug("cp %s %s" % (initrd, release_target + '/initrd.gz'))
630 proc = subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
634 def copy_grml_files(iso_mount, target):
637 grml_target = target + '/grml/'
638 execute(mkdir, grml_target)
640 for myfile in 'grml-cheatcodes.txt', 'grml-version', 'LICENSE.txt', 'md5sums', 'README.txt':
641 grml_file = search_file(myfile, iso_mount)
642 if grml_file is None:
643 logging.warn("Warning: myfile %s could not be found - can not install it", myfile)
645 logging.debug("cp %s %s" % (grml_file, grml_target + grml_file))
646 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_target + myfile])
649 grml_web_target = grml_target + '/web/'
650 execute(mkdir, grml_web_target)
652 for myfile in 'index.html', 'style.css':
653 grml_file = search_file(myfile, iso_mount)
654 if grml_file is None:
655 logging.warn("Warning: myfile %s could not be found - can not install it")
657 logging.debug("cp %s %s" % (grml_file, grml_web_target + grml_file))
658 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_web_target + myfile])
661 grml_webimg_target = grml_web_target + '/images/'
662 execute(mkdir, grml_webimg_target)
664 for myfile in 'button.png', 'favicon.png', 'linux.jpg', 'logo.png':
665 grml_file = search_file(myfile, iso_mount)
666 if grml_file is None:
667 logging.warn("Warning: myfile %s could not be found - can not install it")
669 logging.debug("cp %s %s" % (grml_file, grml_webimg_target + grml_file))
670 proc = subprocess.Popen(["install", "--mode=664", grml_file, grml_webimg_target + myfile])
674 def copy_addons(iso_mount, target):
676 addons = target + '/boot/addons/'
677 execute(mkdir, addons)
679 # grub all-in-one image
680 allinoneimg = search_file('allinone.img', iso_mount)
681 if allinoneimg is None:
682 logging.warn("Warning: allinone.img not found - can not install it")
684 logging.debug("cp %s %s" % (allinoneimg, addons + '/allinone.img'))
685 proc = subprocess.Popen(["install", "--mode=664", allinoneimg, addons + 'allinone.img'])
689 balderimg = search_file('balder10.imz', iso_mount)
690 if balderimg is None:
691 logging.warn("Warning: balder10.imz not found - can not install it")
693 logging.debug("cp %s %s" % (balderimg, addons + '/balder10.imz'))
694 proc = subprocess.Popen(["install", "--mode=664", balderimg, addons + 'balder10.imz'])
698 memdiskimg = search_file('memdisk', iso_mount)
699 if memdiskimg is None:
700 logging.warn("Warning: memdisk not found - can not install it")
702 logging.debug("cp %s %s" % (memdiskimg, addons + '/memdisk'))
703 proc = subprocess.Popen(["install", "--mode=664", memdiskimg, addons + 'memdisk'])
707 def copy_bootloader_files(iso_mount, target):
710 syslinux_target = target + '/boot/syslinux/'
711 execute(mkdir, syslinux_target)
713 logo = search_file('logo.16', iso_mount)
714 logging.debug("cp %s %s" % (logo, syslinux_target + 'logo.16'))
715 proc = subprocess.Popen(["install", "--mode=664", logo, syslinux_target + 'logo.16'])
718 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
719 bootsplash = search_file(ffile, iso_mount)
720 logging.debug("cp %s %s" % (bootsplash, syslinux_target + ffile))
721 proc = subprocess.Popen(["install", "--mode=664", bootsplash, syslinux_target + ffile])
724 grub_target = target + '/boot/grub/'
725 execute(mkdir, grub_target)
727 if not os.path.isfile("/usr/share/grml2usb/grub/splash.xpm.gz"):
728 logging.critical("Error: /usr/share/grml2usb/grub/splash.xpm.gz can not be read.")
731 logging.debug("cp /usr/share/grml2usb/grub/splash.xpm.gz %s" % grub_target + 'splash.xpm.gz')
732 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/splash.xpm.gz',
733 grub_target + 'splash.xpm.gz'])
736 if not os.path.isfile("/usr/share/grml2usb/grub/stage2_eltorito"):
737 logging.critical("Error: /usr/share/grml2usb/grub/stage2_eltorito can not be read.")
740 logging.debug("cp /usr/share/grml2usb/grub/stage2_eltorito to %s" % grub_target + 'stage2_eltorito')
741 proc = subprocess.Popen(["install", "--mode=664", '/usr/share/grml2usb/grub/stage2_eltorito',
742 grub_target + 'stage2_eltorito'])
746 def install_iso_files(grml_flavour, iso_mount, target):
747 """Copy files from ISO on given target"""
750 # * make sure grml_flavour, iso_mount, target are set when the function is called, otherwise raise exception
751 # * provide alternative search_file() if file information is stored in a config.ini file?
752 # * catch "install: .. No space left on device" & CO
753 # * abstract copy logic to make the code shorter and get rid of spaghettis ;)
756 logging.info("Would copy files to %s", iso_mount)
758 elif not options.bootloaderonly:
759 logging.info("Copying files. This might take a while....")
760 copy_system_files(grml_flavour, iso_mount, target)
761 copy_grml_files(iso_mount, target)
763 if not options.skipaddons:
764 copy_addons(iso_mount, target)
766 if not options.copyonly:
767 copy_bootloader_files(iso_mount, target)
769 if not options.dryrun:
770 handle_bootloader_config(grml_flavour, target) # FIXME
772 # make sure we sync filesystems before returning
773 proc = subprocess.Popen(["sync"])
777 def uninstall_files(device):
778 """Get rid of all grml files on specified device
780 @device: partition where grml2usb files should be removed from"""
783 logging.critical("TODO: uninstalling files from %s not yet implement, sorry." % device)
786 def identify_grml_flavour(mountpath):
787 """Get name of grml flavour
789 @mountpath: path where the grml ISO is mounted to
790 @return: name of grml-flavour"""
792 version_file = search_file('grml-version', mountpath)
794 if version_file == "":
795 logging.critical("Error: could not find grml-version file.")
799 tmpfile = open(version_file, 'r')
800 grml_info = tmpfile.readline()
801 grml_flavour = re.match(r'[\w-]*', grml_info).group()
805 logging.critical("Unexpected error:", sys.exc_info()[0])
811 def handle_bootloader_config(grml_flavour, target):
814 logging.debug("Generating grub configuration")
815 #with open("...", "w") as f:
816 #f.write("bla bla bal")
818 grub_target = target + '/boot/grub/'
819 # should be present via copy_bootloader_files(), but make sure it exists:
820 execute(mkdir, grub_target)
821 grub_config_file = open(grub_target + 'menu.lst', 'w')
822 grub_config_file.write(generate_grub_config(grml_flavour))
823 grub_config_file.close()
825 logging.info("Generating syslinux configuration")
826 syslinux_target = target + '/boot/syslinux/'
827 # should be present via copy_bootloader_files(), but make sure it exits:
828 execute(mkdir, syslinux_target)
829 syslinux_cfg = syslinux_target + 'syslinux.cfg'
831 # install main configuration only *once*, no matter how many ISOs we have:
832 if os.path.isfile(syslinux_cfg):
833 string = open(syslinux_cfg).readline()
834 main_identifier = re.compile(".*main config generated at: %s.*" % re.escape(str(DATESTAMP)))
835 if not re.match(main_identifier, string):
836 syslinux_config_file = open(syslinux_cfg, 'w')
837 logging.info("Notice: grml flavour %s is being installed as the default booting system." % grml_flavour)
838 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
839 syslinux_config_file.close()
841 syslinux_config_file = open(syslinux_cfg, 'w')
842 syslinux_config_file.write(generate_main_syslinux_config(grml_flavour, options.bootoptions))
843 syslinux_config_file.close()
845 # install flavour specific configuration only *once* as well
846 # kind of ugly - I'm pretty sure this could be smoother...
847 flavour_config = True
848 if os.path.isfile(syslinux_cfg):
849 string = open(syslinux_cfg).readlines()
850 logging.info("Notice: you can boot flavour %s using '%s' on the commandline." % (grml_flavour, grml_flavour))
851 flavour = re.compile("grml2usb for %s: %s" % (re.escape(grml_flavour), re.escape(str(DATESTAMP))))
853 if flavour.match(line):
854 flavour_config = False
857 syslinux_config_file = open(syslinux_cfg, 'a')
858 syslinux_config_file.write(generate_flavour_specific_syslinux_config(grml_flavour, options.bootoptions))
859 syslinux_config_file.close( )
861 logging.debug("Generating isolinux/syslinux splash %s" % syslinux_target + 'boot.msg')
862 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
863 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
864 isolinux_splash.close( )
867 def handle_iso(iso, device):
868 """Main logic for mounting ISOs and copying files.
870 @iso: full path to the ISO that should be installed to the specified device
871 @device: partition where the specified ISO should be installed to"""
873 logging.info("Using ISO %s" % iso)
875 if os.path.isdir(iso):
876 logging.critical("TODO: /live/image handling not yet implemented - sorry") # TODO
879 iso_mountpoint = tempfile.mkdtemp()
880 register_tmpfile(iso_mountpoint)
881 remove_iso_mountpoint = True
883 if not os.path.isfile(iso):
884 logging.critical("Fatal: specified ISO %s could not be read" % iso)
889 mount(iso, iso_mountpoint, ["-o", "loop", "-t", "iso9660"])
890 except CriticalException, error:
891 logging.critical("Fatal: %s" % error)
894 if os.path.isdir(device):
895 logging.info("Specified target is a directory, not mounting therefor.")
896 device_mountpoint = device
897 remove_device_mountpoint = False
900 device_mountpoint = tempfile.mkdtemp()
901 register_tmpfile(device_mountpoint)
902 remove_device_mountpoint = True
904 mount(device, device_mountpoint, "")
905 except CriticalException, error:
906 logging.critical("Fatal: %s" % error)
910 grml_flavour = identify_grml_flavour(iso_mountpoint)
911 logging.info("Identified grml flavour \"%s\"." % grml_flavour)
912 install_iso_files(grml_flavour, iso_mountpoint, device_mountpoint)
914 logging.critical("Fatal: a critical error happend during execution (not a grml ISO?), giving up")
917 if os.path.isdir(iso_mountpoint) and remove_iso_mountpoint:
918 unmount(iso_mountpoint, "")
919 os.rmdir(iso_mountpoint)
920 unregister_tmpfile(iso_mountpoint)
921 if remove_device_mountpoint:
922 unmount(device_mountpoint, "")
923 if os.path.isdir(device_mountpoint):
924 os.rmdir(device_mountpoint)
925 unregister_tmpfile(device_mountpoint)
928 def handle_mbr(device):
932 # if not options.mbr:
933 # logging.info("You are NOT using the --mbr option. Consider using it if your device does not boot.")
935 # make sure we install MBR on /dev/sdX and not /dev/sdX#
937 # make sure we have syslinux available
939 if not options.skipmbr:
940 if not which("syslinux") and not options.copyonly and not options.dryrun:
941 logging.critical('Sorry, syslinux not available. Exiting.')
942 logging.critical('Please install syslinux or consider using the --grub option.')
945 if not options.skipmbr:
946 if device[-1:].isdigit():
947 mbr_device = re.match(r'(.*?)\d*$', device).group(1)
950 install_mbr(mbr_device)
951 except IOError, error:
952 logging.critical("Execution failed: %s", error)
954 except Exception, error:
955 logging.critical("Execution failed: %s", error)
959 def handle_vfat(device):
962 # make sure we have mkfs.vfat available
963 if options.fat16 and not options.force:
964 if not which("mkfs.vfat") and not options.copyonly and not options.dryrun:
965 logging.critical('Sorry, mkfs.vfat not available. Exiting.')
966 logging.critical('Please make sure to install dosfstools.')
969 # make sure the user is aware of what he is doing
970 f = raw_input("Are you sure you want to format the device with a fat16 filesystem? y/N ")
971 if f == "y" or f == "Y":
972 logging.info("Note: you can skip this question using the option --force")
977 # check for vfat filesystem
978 if device is not None and not os.path.isdir(device):
980 check_for_fat(device)
981 except CriticalException, error:
982 logging.critical("Execution failed: %s", error)
985 if not check_for_usbdevice(device):
986 print "Warning: the specified device %s does not look like a removable usb device." % device
987 f = raw_input("Do you really want to continue? y/N ")
988 if f == "y" or f == "Y":
994 def handle_compat_warning(device):
997 # make sure we can replace old grml2usb script and warn user when using old way of life:
998 if device.startswith("/mnt/external") or device.startswith("/mnt/usb") and not options.force:
999 print "Warning: the semantics of grml2usb has changed."
1000 print "Instead of using grml2usb /path/to/iso %s you might" % device
1001 print "want to use grml2usb /path/to/iso /dev/... instead."
1002 print "Please check out the grml2usb manpage for details."
1003 f = raw_input("Do you really want to continue? y/N ")
1004 if f == "y" or f == "Y":
1010 def handle_logging():
1014 FORMAT = "%(asctime)-15s %(message)s"
1015 logging.basicConfig(level=logging.DEBUG, format=FORMAT)
1017 FORMAT = "Critial: %(message)s"
1018 logging.basicConfig(level=logging.CRITICAL, format=FORMAT)
1020 FORMAT = "Info: %(message)s"
1021 logging.basicConfig(level=logging.INFO, format=FORMAT)
1024 def handle_bootloader(device):
1026 # Install bootloader only if not using the --copy-only option
1027 if options.copyonly:
1028 logging.info("Not installing bootloader and its files as requested via option copyonly.")
1030 install_bootloader(device)
1034 """Main function [make pylint happy :)]"""
1037 print os.path.basename(sys.argv[0]) + " " + PROG_VERSION
1041 parser.error("invalid usage")
1046 # make sure we have the appropriate permissions
1050 logging.info("Running in simulate mode as requested via option dry-run.")
1052 # specified arguments
1053 device = args[len(args) - 1]
1054 isos = args[0:len(args) - 1]
1056 # provide upgrade path
1057 handle_compat_warning(device)
1059 # check for vfat partition
1062 # main operation (like installing files)
1064 handle_iso(iso, device)
1069 handle_bootloader(device)
1071 # finally be politely :)
1072 logging.info("Finished execution of grml2usb (%s). Have fun with your grml system." % PROG_VERSION)
1075 if __name__ == "__main__":
1078 except KeyboardInterrupt:
1079 logging.info("Received KeyboardInterrupt")
1082 ## END OF FILE #################################################################
1083 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8