2 # -*- coding: utf-8 -*-
7 This script installs a grml system 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 (--kernel, --initrd, --uninstall,...)
17 * improve error handling :)
18 * get rid of "if not dry_run" inside code/functions
19 * implement mount handling
20 * log wrapper (-> logging module)
21 * implement logic for storing information about copied files
22 -> register every single file?
23 * trap handling (like unmount devices when interrupting?)
24 * get rid of all TODOs in code :)
28 import os, re, subprocess, sys, tempfile
29 from optparse import OptionParser
30 from os.path import exists, join, abspath
31 from os import pathsep
32 # TODO string.split() is deprecated - replace?
33 # -> http://docs.python.org/library/string.html#deprecated-string-functions
34 from string import split
36 PROG_VERSION = "0.0.1"
40 # * --bootloader-only?
41 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
43 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
44 Make sure you have at least a grml ISO or a running grml system,\n\
45 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
48 parser = OptionParser(usage=usage)
49 parser.add_option("--bootoptions", dest="bootoptions",
50 action="store", type="string",
51 help="use specified bootoptions as defaut")
52 parser.add_option("--copy-only", dest="copyonly", action="store_true",
53 help="copy files only and do not install bootloader")
54 parser.add_option("--dry-run", dest="dryrun", action="store_true",
55 help="do not actually execute any commands")
56 parser.add_option("--fat16", dest="fat16", action="store_true",
57 help="format specified partition with FAT16")
58 parser.add_option("--force", dest="force", action="store_true",
59 help="force any actions requiring manual interaction")
60 parser.add_option("--grub", dest="grub", action="store_true",
61 help="install grub bootloader instead of syslinux")
62 parser.add_option("--initrd", dest="initrd", action="store", type="string",
63 help="install specified initrd instead of the default")
64 parser.add_option("--kernel", dest="kernel", action="store", type="string",
65 help="install specified kernel instead of the default")
66 parser.add_option("--mbr", dest="mbr", action="store_true",
67 help="install master boot record (MBR) on the device")
68 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
69 help="install specified squashfs file instead of the default")
70 parser.add_option("--uninstall", dest="uninstall", action="store_true",
71 help="remove grml ISO files")
72 parser.add_option("--verbose", dest="verbose", action="store_true",
73 help="enable verbose mode")
74 parser.add_option("-v", "--version", dest="version", action="store_true",
75 help="display version and exit")
76 (options, args) = parser.parse_args()
79 def execute(f, *args):
80 """Wrapper for executing a command. Either really executes
81 the command (default) or when using --dry-run commandline option
82 just displays what would be executed."""
83 # demo: execute(subprocess.Popen, (["ls", "-la"]))
85 print "would execute %s(%s) now" % (f, args)
91 """Check whether a given file can be executed
93 @fpath: full path to file
95 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
99 """Check whether a given program is available in PATH
101 @program: name of executable"""
102 fpath, fname = os.path.split(program)
107 for path in os.environ["PATH"].split(os.pathsep):
108 exe_file = os.path.join(path, program)
115 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
116 """Given a search path, find file"""
118 paths = split(search_path, pathsep)
120 for current_dir, directories, files in os.walk(path):
121 if exists(join(current_dir, filename)):
125 return abspath(join(current_dir, filename))
130 def check_uid_root():
131 """Check for root permissions"""
132 if not os.geteuid()==0:
133 sys.exit("Error: please run this script with uid 0 (root).")
136 def install_syslinux(device, dry_run=False):
138 """Install syslinux on specified device."""
139 print("debug: syslinux %s [TODO]") % device
141 # syslinux -d boot/isolinux /dev/usb-sdb1
144 def generate_grub_config(grml_flavour):
145 """Generate grub configuration for use via menu,lst"""
148 # * install main part of configuration just *once* and append
149 # flavour specific configuration only
150 # * what about systems using grub2 without having grub1 available?
153 grml_name = grml_flavour
158 # color red/blue green/black
159 splashimage=/boot/grub/splash.xpm.gz
164 title %(grml_name)s - Default boot (using 1024x768 framebuffer)
165 kernel /boot/release/%(grml_name)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_name)s
166 initrd /boot/release/%(grml_name)s/initrd.gz
168 # TODO: extend configuration :)
172 def generate_isolinux_splash(grml_flavour):
173 """Generate bootsplash for isolinux/syslinux"""
176 # * adjust last bootsplash line
178 grml_name = grml_flavour
181 \ f17
\f\18/boot/isolinux/logo.16
183 Some information and boot options available via keys F2 - F10. http://grml.org/
187 def generate_syslinux_config(grml_flavour):
188 """Generate configuration for use in syslinux.cfg"""
191 # * install main part of configuration just *once* and append
192 # flavour specific configuration only
193 # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
196 grml_name = grml_flavour
199 # use this to control the bootup via a serial port
204 DISPLAY /boot/isolinux/boot.msg
205 F1 /boot/isolinux/boot.msg
214 F10 /boot/isolinux/f10
217 KERNEL /boot/release/%(grml_name)s/linux26
218 APPEND initrd=/boot/release/%(grml_name)s/initrd.gz apm=power-off lang=us boot=live nomce module=%(grml_name)s
220 # TODO: extend configuration :)
224 def install_grub(device, dry_run=False):
225 """Install grub on specified device."""
226 print("grub-install %s") % device
229 def install_bootloader(partition, dry_run=False):
230 """Install bootloader on device."""
231 # Install bootloader on the device (/dev/sda),
232 # not on the partition itself (/dev/sda1)
233 if partition[-1:].isdigit():
234 device = re.match(r'(.*?)\d*$', partition).group(1)
239 install_grub(device, dry_run)
241 install_syslinux(device, dry_run)
244 def is_writeable(device):
245 """Check if the device is writeable for the current user"""
249 #raise Exception, "no device for checking write permissions"
251 if not os.path.exists(device):
254 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
256 def install_mbr(device, dry_run=False):
257 """Install a default master boot record on given device
259 @device: device where MBR should be installed to"""
261 if not is_writeable(device):
262 raise IOError, "device not writeable for user"
264 lilo = './lilo/lilo.static' # FIXME
267 raise Exception, "lilo executable not available."
269 # to support -A for extended partitions:
270 print("debug: ./lilo/lilo.static -S /dev/null -M %s ext") % device
271 proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-M", device, "ext"])
273 if proc.returncode != 0:
274 raise Exception, "error executing lilo"
276 # activate partition:
277 print("debug: ./lilo/lilo.static -S /dev/null -A %s 1") % device
279 proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-A", device, "1"])
281 if proc.returncode != 0:
282 raise Exception, "error executing lilo"
284 # lilo's mbr is broken, use the one from syslinux instead:
285 print("debug: cat /usr/lib/syslinux/mbr.bin > %s") % device
288 # TODO use Popen instead?
289 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
291 print >> sys.stderr, "Error copying MBR to device", -retcode
292 except OSError, error:
293 print >> sys.stderr, "Execution failed:", error
296 def mount(source, target, options):
297 """Mount specified source on given target
299 @source: name of device/ISO that should be mounted
300 @target: directory where the ISO should be mounted to
301 @options: mount specific options"""
303 print("debug: mount %s %s %s [TODO]") % (options, source, target)
306 def unmount(directory):
307 """Unmount specified directory
309 @directory: directory where something is mounted on and which should be unmounted"""
311 print("debug: umount %s [TODO]") % directory
314 def check_for_vat(partition):
315 """Check whether specified partition is a valid VFAT/FAT16 filesystem
317 @partition: device name of partition"""
320 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
321 partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
322 filesystem = udev_info.communicate()[0].rstrip()
324 if udev_info.returncode == 2:
325 print("failed to read device %s - wrong UID / permissions?") % partition
328 if filesystem != "vfat":
332 # * check for ID_FS_VERSION=FAT16 as well?
335 print("Sorry, /lib/udev/vol_id not available.")
339 def mkdir(directory):
340 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
342 if not os.path.isdir(directory):
344 os.makedirs(directory)
346 # just silently pass as it's just fine it the directory exists
350 def copy_grml_files(grml_flavour, iso_mount, target, dry_run=False):
351 """Copy files from ISO on given target"""
354 # * provide alternative search_file() if file information is stored in a config.ini file?
355 # * catch "install: .. No space left on device" & CO
356 # * abstract copy logic to make the code shorter and get rid of spaghetti ;)
358 print("Copying files. This might take a while....")
360 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
361 squashfs_target = target + '/live/'
362 execute(mkdir, squashfs_target)
364 # use install(1) for now to make sure we can write the files afterwards as normal user as well
365 print("cp %s %s") % (squashfs, target + '/live/' + grml_flavour + '.squashfs')
366 execute(subprocess.Popen, ["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
368 filesystem_module = search_file('filesystem.module', iso_mount)
369 print("cp %s %s") % (filesystem_module, squashfs_target + grml_flavour + '.module')
370 execute(subprocess.Popen, ["install", "--mode=664", filesystem_module, squashfs_target + grml_flavour + '.module'])
372 release_target = target + '/boot/release/' + grml_flavour
373 execute(mkdir, release_target)
375 kernel = search_file('linux26', iso_mount)
376 print("cp linux26 %s") % release_target + '/linux26'
377 execute(subprocess.Popen, ["install", "--mode=664", kernel, release_target + '/linux26'])
379 initrd = search_file('initrd.gz', iso_mount)
380 print("debug: copy initrd to %s") % release_target + '/initrd.gz'
381 execute(subprocess.Popen, ["install", "--mode=664", initrd, release_target + '/initrd.gz'])
383 if not options.copyonly:
384 isolinux_target = target + '/boot/isolinux/'
385 execute(mkdir, isolinux_target)
387 logo = search_file('logo.16', iso_mount)
388 print("debug: copy logo.16 to %s") % isolinux_target + 'logo.16'
389 execute(subprocess.Popen, ["install", "--mode=664", logo, isolinux_target + 'logo.16'])
391 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
392 bootsplash = search_file(ffile, iso_mount)
393 print("debug: copy %s to %s") % (bootsplash, isolinux_target + ffile)
394 execute(subprocess.Popen, ["install", "--mode=664", bootsplash, isolinux_target + ffile])
396 grub_target = target + '/boot/grub/'
397 execute(mkdir, grub_target)
399 print("debug: copy grub/splash.xpm.gz to %s") % grub_target + 'splash.xpm.gz'
400 execute(subprocess.Popen, ["install", "--mode=664", 'grub/splash.xpm.gz', grub_target + 'splash.xpm.gz'])
402 print("debug: copy grub/stage2_eltorito to %s") % grub_target + 'stage2_eltorito'
403 execute(subprocess.Popen, ["install", "--mode=664", 'grub/stage2_eltorito', grub_target + 'stage2_eltorito'])
405 print("debug: generating grub configuration %s") % grub_target + 'menu.lst'
407 grub_config_file = open(grub_target + 'menu.lst', 'w')
408 grub_config_file.write(generate_grub_config(grml_flavour))
409 grub_config_file.close( )
411 syslinux_target = target + '/boot/isolinux/'
412 execute(mkdir, syslinux_target)
414 print("debug: generating syslinux configuration %s") % syslinux_target + 'syslinux.cfg'
416 syslinux_config_file = open(syslinux_target + 'syslinux.cfg', 'w')
417 syslinux_config_file.write(generate_syslinux_config(grml_flavour))
418 syslinux_config_file.close( )
420 print("debug: generating isolinux/syslinux splash %s") % syslinux_target + 'boot.msg'
422 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
423 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
424 isolinux_splash.close( )
427 def uninstall_files(device):
428 """Get rid of all grml files on specified device"""
431 print("TODO: %s") % device
434 def identify_grml_flavour(mountpath):
435 """Get name of grml flavour
437 @mountpath: path where the grml ISO is mounted to
438 @return: name of grml-flavour"""
440 version_file = search_file('grml-version', mountpath)
442 if version_file == "":
446 tmpfile = open(version_file, 'r')
447 grml_info = tmpfile.readline()
448 grml_flavour = re.match(r'[\w-]*', grml_info).group()
452 print "Unexpected error:", sys.exc_info()[0]
459 """Main function [make pylint happy :)]"""
462 print("%s %s")% (os.path.basename(sys.argv[0]), PROG_VERSION)
466 parser.error("invalid usage")
469 print("Running in simulate mode as requested via option dry-run.")
473 device = args[len(args) - 1]
474 isos = args[0:len(args) - 1]
476 if not which("syslinux"):
477 print >> sys.stderr, 'Sorry, syslinux not available. Exiting.'
478 print >> sys.stderr, 'Please install syslinux or consider using the --grub option.'
482 # * check for valid blockdevice, vfat and mount functions
483 # if device is not None:
484 # check_for_vat(device)
485 # mount_target(partition)
488 # * it doesn't need to be a ISO, could be /live/image as well
490 print("debug: iso = %s") % iso
492 if os.path.isdir(iso):
493 print("TODO: /live/image handling not yet implemented") # TODO
495 iso_mountpoint = '/mnt/test' # FIXME
496 # iso_mount = tempfile.mkdtemp()
497 mount(iso, iso_mountpoint, "-o loop -t iso9660")
498 # device_mountpoint = '/mnt/usb-sdb1'
499 # device_mountpoint = tempfile.mkdtemp()
500 device_mountpoint = '/dev/shm/grml2usb' # FIXME
501 mount(device, device_mountpoint, "")
504 grml_flavour = identify_grml_flavour(iso_mountpoint)
505 print("Identified grml flavour \"%s\".") % grml_flavour
507 print("Fatal: could not identify grml flavour, sorry.")
510 # grml_flavour_short = grml_flavour.replace('-','')
511 #p rint("debug: grml_flavour_short = %s") % grml_flavour_short
513 copy_grml_files(grml_flavour, iso_mountpoint, device_mountpoint, dry_run=options.dryrun)
515 unmount(device_mountpoint) # TODO
516 unmount(iso_mountpoint) # TODO
518 #if os.path.isdir(target):
520 #if os.path.isdir(iso_mount):
521 # os.rmdir(iso_mount)
525 # make sure we install MBR on /dev/sdX and not /dev/sdX#
526 if device[-1:].isdigit():
527 device = re.match(r'(.*?)\d*$', device).group(1)
530 install_mbr(device, dry_run=options.dryrun)
531 except IOError, error:
532 print >> sys.stderr, "Execution failed:", error
534 except Exception, error:
535 print >> sys.stderr, "Execution failed:", error
539 print("Not installing bootloader and its files as requested via option copyonly.")
541 install_bootloader(device, dry_run=options.dryrun)
543 print("Finished execution of grml2usb (%s). Have fun with your grml system.") % PROG_VERSION
545 if __name__ == "__main__":
548 ## END OF FILE #################################################################
549 # vim:foldmethod=marker expandtab ai ft=python tw=120 fileencoding=utf-8