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 * improve error handling :)
17 * implement mount handling
18 * log wrapper (-> logging module)
19 * implement logic for storing information about copied files
20 -> register every single file?
21 * trap handling (like unmount devices when interrupting?)
22 * get rid of all TODOs in code :)
26 import os, re, subprocess, sys, tempfile
27 from optparse import OptionParser
28 from os.path import exists, join, abspath
29 from os import pathsep
30 # TODO string.split() is deprecated - replace?
31 # -> http://docs.python.org/library/string.html#deprecated-string-functions
32 from string import split
34 PROG_VERSION = "0.0.1"
39 # * --bootloader-only?
40 usage = "Usage: %prog [options] <ISO[s]> <partition>\n\
42 %prog installs a grml ISO to an USB device to be able to boot from it.\n\
43 Make sure you have at least a grml ISO or a running grml system,\n\
44 syslinux (just run 'aptitude install syslinux' on Debian-based systems)\n\
47 parser = OptionParser(usage=usage)
48 parser.add_option("--bootoptions", dest="bootoptions",
49 action="store", type="string",
50 help="use specified bootoptions as defaut")
51 parser.add_option("--dry-run", dest="dryrun", action="store_true",
52 help="do not actually execute any commands")
53 parser.add_option("--fat16", dest="fat16", action="store_true",
54 help="format specified partition with FAT16")
55 parser.add_option("--force", dest="force", action="store_true",
56 help="force any actions requiring manual interaction")
57 parser.add_option("--grub", dest="grub", action="store_true",
58 help="install grub bootloader instead of syslinux")
59 parser.add_option("--initrd", dest="initrd", action="store", type="string",
60 help="install specified initrd instead of the default")
61 parser.add_option("--kernel", dest="kernel", action="store", type="string",
62 help="install specified kernel instead of the default")
63 parser.add_option("--mbr", dest="mbr", action="store_true",
64 help="install master boot record (MBR) on the device")
65 parser.add_option("--squashfs", dest="squashfs", action="store", type="string",
66 help="install specified squashfs file instead of the default")
67 parser.add_option("--uninstall", dest="uninstall", action="store_true",
68 help="remove grml ISO files")
69 parser.add_option("--verbose", dest="verbose", action="store_true",
70 help="enable verbose mode")
71 parser.add_option("-v", "--version", dest="version", action="store_true",
72 help="display version and exit")
73 (options, args) = parser.parse_args()
76 def execute(f, *args):
77 """Wrapper for executing a command. Either really executes
78 the command (default) or when using --dry-run commandline option
79 just displays what would be executed."""
80 # demo: execute(subprocess.Popen, (["ls", "-la"]))
82 print "would execute %s(%s) now" % (f, args)
88 """Check whether a given file can be executed
90 @fpath: full path to file
92 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
96 """Check whether a given program is available in PATH
98 @program: name of executable"""
99 fpath, fname = os.path.split(program)
104 for path in os.environ["PATH"].split(os.pathsep):
105 exe_file = os.path.join(path, program)
112 def search_file(filename, search_path='/bin' + pathsep + '/usr/bin'):
113 """Given a search path, find file"""
115 paths = split(search_path, pathsep)
117 for current_dir, directories, files in os.walk(path):
118 if exists(join(current_dir, filename)):
122 return abspath(join(current_dir, filename))
127 def check_uid_root():
128 """Check for root permissions"""
129 if not os.geteuid()==0:
130 sys.exit("Error: please run this script with uid 0 (root).")
133 def install_syslinux(device):
135 """Install syslinux on specified device."""
136 print("debug: syslinux %s [TODO]") % device
138 # syslinux -d boot/isolinux /dev/usb-sdb1
141 def generate_grub_config(grml_flavour):
142 """Generate grub configuration for use via menu,lst"""
145 # * what about system using grub2 without having grub available?
148 grml_name = grml_flavour
153 # color red/blue green/black
154 splashimage=/boot/grub/splash.xpm.gz
159 title %(grml_name)s - Default boot (using 1024x768 framebuffer)
160 kernel /boot/release/%(grml_name)s/linux26 apm=power-off lang=us vga=791 quiet boot=live nomce module=%(grml_name)s
161 initrd /boot/release/%(grml_name)s/initrd.gz
163 # TODO: extend configuration :)
167 def generate_isolinux_splash(grml_flavour):
168 """Generate bootsplash for isolinux/syslinux"""
171 # * adjust last bootsplash line
173 grml_name = grml_flavour
176 \ f17
\f\18/boot/isolinux/logo.16
178 Some information and boot options available via keys F2 - F10. http://grml.org/
182 def generate_syslinux_config(grml_flavour):
183 """Generate configuration for use in syslinux.cfg"""
186 # * unify isolinux and syslinux setup ("INCLUDE /boot/...")
188 grml_name = grml_flavour
191 # use this to control the bootup via a serial port
196 DISPLAY /boot/isolinux/boot.msg
197 F1 /boot/isolinux/boot.msg
206 F10 /boot/isolinux/f10
209 KERNEL /boot/release/%(grml_name)s/linux26
210 APPEND initrd=/boot/release/%(grml_name)s/initrd.gz apm=power-off lang=us boot=live nomce module=%(grml_name)s
212 # TODO: extend configuration :)
216 def install_grub(device):
217 """Install grub on specified device."""
218 print("grub-install %s") % device
221 def install_bootloader(partition):
222 """Install bootloader on device."""
223 # Install bootloader on the device (/dev/sda),
224 # not on the partition itself (/dev/sda1)
225 if partition[-1:].isdigit():
226 device = re.match(r'(.*?)\d*$', partition).group(1)
233 install_syslinux(device)
236 def is_writeable(device):
237 """Check if the device is writeable for the current user"""
241 #raise Exception, "no device for checking write permissions"
243 if not os.path.exists(device):
246 return os.access(device, os.W_OK) and os.access(device, os.R_OK)
248 def install_mbr(device):
249 """Install a default master boot record on given device
251 @device: device where MBR should be installed to"""
253 if not is_writeable(device):
254 raise IOError, "device not writeable for user"
256 lilo = './lilo/lilo.static' # FIXME
259 raise Exception, "lilo executable not available."
261 # to support -A for extended partitions:
262 print("debug: ./lilo/lilo.static -S /dev/null -M %s ext") % device
263 proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-M", device, "ext"])
265 if proc.returncode != 0:
266 raise Exception, "error executing lilo"
268 # activate partition:
269 print("debug: ./lilo/lilo.static -S /dev/null -A %s 1") % device
270 proc = subprocess.Popen(["./lilo/lilo.static", "-S", "/dev/null", "-A", device, "1"])
272 if proc.returncode != 0:
273 raise Exception, "error executing lilo"
275 # lilo's mbr is broken, use the one from syslinux instead:
276 print("debug: cat /usr/lib/syslinux/mbr.bin > %s") % device
278 # TODO use Popen instead?
279 retcode = subprocess.call("cat /usr/lib/syslinux/mbr.bin > "+ device, shell=True)
281 print >> sys.stderr, "Error copying MBR to device", -retcode
282 except OSError, error:
283 print >> sys.stderr, "Execution failed:", error
286 def loopback_mount(iso, target):
287 """Loopback mount specified ISO on given target
289 @iso: name of ISO that should be mounted
290 @target: directory where the ISO should be mounted to"""
292 print("mount -o loop %s %s") % (iso, target)
295 def check_for_vat(partition):
296 """Check whether specified partition is a valid VFAT/FAT16 filesystem
298 @partition: device name of partition"""
301 udev_info = subprocess.Popen(["/lib/udev/vol_id", "-t",
302 partition],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
303 filesystem = udev_info.communicate()[0].rstrip()
305 if udev_info.returncode == 2:
306 print("failed to read device %s - wrong UID / permissions?") % partition
309 if filesystem != "vfat":
313 # * check for ID_FS_VERSION=FAT16 as well?
316 print("Sorry, /lib/udev/vol_id not available.")
319 def mkdir(directory):
320 """Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
322 if not os.path.isdir(directory):
324 os.makedirs(directory)
326 # just silently pass as it's just fine it the directory exists
330 def copy_grml_files(grml_flavour, iso_mount, target):
331 """Copy files from ISO on given target"""
334 # * provide alternative search_file() if file information is stored in a config.ini file?
335 # * catch "install: .. No space left on device" & CO
336 # * abstract copy logic to make the code shorter?
338 squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
339 squashfs_target = target + '/live/'
340 mkdir(squashfs_target)
342 # use install(1) for now to make sure we can write the files afterwards as normal user as well
343 print("debug: copy squashfs to %s") % target + '/live/' + grml_flavour + '.squashfs'
344 subprocess.Popen(["install", "--mode=664", squashfs, squashfs_target + grml_flavour + ".squashfs"])
346 filesystem_module = search_file('filesystem.module', iso_mount)
347 print("debug: copy filesystem.module to %s") % squashfs_target + grml_flavour + '.module'
348 subprocess.Popen(["install", "--mode=664", filesystem_module, squashfs_target + grml_flavour + '.module'])
350 release_target = target + '/boot/release/' + grml_flavour
351 mkdir(release_target)
353 kernel = search_file('linux26', iso_mount)
354 print("debug: copy kernel to %s") % release_target + '/linux26'
355 subprocess.Popen(["install", "--mode=664", kernel, release_target + '/linux26'])
357 initrd = search_file('initrd.gz', iso_mount)
358 print("debug: copy initrd to %s") % release_target + '/initrd.gz'
359 subprocess.Popen(["install", "--mode=664", initrd, release_target + '/initrd.gz'])
361 isolinux_target = target + '/boot/isolinux/'
362 mkdir(isolinux_target)
364 logo = search_file('logo.16', iso_mount)
365 print("debug: copy logo.16 to %s") % isolinux_target + 'logo.16'
366 subprocess.Popen(["install", "--mode=664", logo, isolinux_target + 'logo.16'])
368 for ffile in 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10':
369 bootsplash = search_file(ffile, iso_mount)
370 print("debug: copy %s to %s") % (bootsplash, isolinux_target + ffile)
371 subprocess.Popen(["install", "--mode=664", bootsplash, isolinux_target + ffile])
373 grub_target = target + '/boot/grub/'
376 print("debug: copy grub/splash.xpm.gz to %s") % grub_target + 'splash.xpm.gz'
377 subprocess.Popen(["install", "--mode=664", 'grub/splash.xpm.gz', grub_target + 'splash.xpm.gz'])
379 print("debug: copy grub/stage2_eltorito to %s") % grub_target + 'stage2_eltorito'
380 subprocess.Popen(["install", "--mode=664", 'grub/stage2_eltorito', grub_target + 'stage2_eltorito'])
382 print("debug: generating grub configuration %s") % grub_target + 'menu.lst'
383 grub_config_file = open(grub_target + 'menu.lst', 'w')
384 grub_config_file.write(generate_grub_config(grml_flavour))
385 grub_config_file.close( )
387 syslinux_target = target + '/boot/isolinux/'
388 mkdir(syslinux_target)
390 print("debug: generating syslinux configuration %s") % syslinux_target + 'syslinux.cfg'
391 syslinux_config_file = open(syslinux_target + 'syslinux.cfg', 'w')
392 syslinux_config_file.write(generate_syslinux_config(grml_flavour))
393 syslinux_config_file.close( )
395 print("debug: generating isolinux/syslinux splash %s") % syslinux_target + 'boot.msg'
396 isolinux_splash = open(syslinux_target + 'boot.msg', 'w')
397 isolinux_splash.write(generate_isolinux_splash(grml_flavour))
398 isolinux_splash.close( )
401 def uninstall_files(device):
402 """Get rid of all grml files on specified device"""
405 print("TODO: %s") % device
408 def identify_grml_flavour(mountpath):
409 """Get name of grml flavour
411 @mountpath: path where the grml ISO is mounted to
412 @return: name of grml-flavour"""
414 version_file = search_file('grml-version', mountpath)
416 tmpfile = open(version_file, 'r')
417 grml_info = tmpfile.readline()
418 #tmpfile.close # pylint: Statement seems to have no effect
420 grml_flavour = re.match(r'[\w-]*', grml_info).group()
425 """Main function [make pylint happy :)]"""
428 print("%s %s")% (os.path.basename(sys.argv[0]), PROG_VERSION)
432 parser.error("invalid usage")
436 device = args[len(args) - 1]
437 isos = args[0:len(args) - 1]
439 if not which("syslinux"):
440 print >> sys.stderr, 'Sorry, syslinux not available. Exiting.'
441 print >> sys.stderr, 'Please install syslinux or consider using the --grub option.'
445 # * check for valid blockdevice, vfat and mount functions
446 # if device is not None:
447 # check_for_vat(device)
448 # mount_target(partition)
451 # target = '/mnt/usb-sdb1'
452 target = tempfile.mkdtemp()
453 print("debug: target = %s") % target
456 # * it doesn't need to be a ISO, could be /live/image as well
458 print("debug: iso = %s") % iso
459 # loopback_mount(iso)
460 iso_mount = '/mnt/test' # FIXME
461 loopback_mount(iso, target) # FIXME s/target/iso_mount/
462 # copy_grml_files(iso, target)
463 # loopback_unmount(iso)
465 grml_flavour = identify_grml_flavour(iso_mount)
466 print("debug: grml_flavour = %s") % grml_flavour
468 grml_flavour_short = grml_flavour.replace('-','')
469 print("debug: grml_flavour_short = %s") % grml_flavour_short
471 # TODO - re-enable :)
472 # copy_grml_files(grml_flavour, iso_mount, target)
475 # make sure we install MBR on /dev/sdX and not /dev/sdX#
476 if device[-1:].isdigit():
477 device = re.match(r'(.*?)\d*$', device).group(1)
481 except IOError, error:
482 print >> sys.stderr, "Execution failed:", error
484 except Exception, error:
485 print >> sys.stderr, "Execution failed:", error
488 install_bootloader(device)
490 if os.path.isdir(target):
493 if __name__ == "__main__":
496 ## END OF FILE #################################################################
497 # vim:foldmethod=marker expandtab ai ft=python tw=120 fileencoding=utf-8