/
grml2usb
executable file
·1785 lines (1378 loc) · 59.8 KB
/
grml2usb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable-msg=C0302
"""
grml2usb
~~~~~~~~
This script installs a grml system (either a running system or ISO[s]) to a USB device
:copyright: (c) 2009, 2010, 2011 by Michael Prokop <mika@grml.org>
:license: GPL v2 or any later version
:bugreports: http://grml.org/bugs/
"""
from optparse import OptionParser
from inspect import isroutine, isclass
import datetime
import fileinput
import glob
import logging
import os
import os.path
import re
import struct
import subprocess
import sys
import tempfile
import time
import uuid
# The line following this line is patched by debian/rules and tarball.sh.
PROG_VERSION = '***UNRELEASED***'
# global variables
MOUNTED = set() # register mountpoints
TMPFILES = set() # register tmpfiles
DATESTAMP = time.mktime(datetime.datetime.now().timetuple()) # unique identifier for syslinux.cfg
GRML_FLAVOURS = set() # which flavours are being installed?
GRML_DEFAULT = None
UUID = None
SYSLINUX_LIBS = "/usr/lib/syslinux/"
def syslinux_warning(option, opt, value, opt_parser):
"""A helper function for printing a warning about deprecated option
"""
# pylint: disable-msg=W0613
sys.stderr.write("Note: the --syslinux option is deprecated as syslinux "
"is grml2usb's default. Continuing anyway.\n")
setattr(opt_parser.values, option.dest, True)
# if grub option is set, unset syslinux option
def grub_option(option, opt, value, opt_parser):
"""A helper function adjusting other option values
"""
# pylint: disable-msg=W0613
setattr(opt_parser.values, option.dest, True)
setattr(opt_parser.values, 'syslinux', False)
# cmdline parsing
USAGE = "Usage: %prog [options] <[ISO[s] | /lib/live/mount/medium]> </dev/sdX#>\n\
\n\
%prog installs Grml ISO[s] to an USB device to be able to boot from it.\n\
Make sure you have at least one Grml ISO or a running Grml system (/lib/live/mount/medium),\n\
grub or syslinux and root access.\n\
\n\
Run %prog --help for usage hints, further information via: man grml2usb"
# pylint: disable-msg=C0103
# pylint: disable-msg=W0603
parser = OptionParser(usage=USAGE)
parser.add_option("--bootoptions", dest="bootoptions",
action="append", type="string",
help="use specified bootoptions as default")
parser.add_option("--bootloader-only", dest="bootloaderonly", action="store_true",
help="do not copy files but just install a bootloader")
parser.add_option("--copy-only", dest="copyonly", action="store_true",
help="copy files only but do not install bootloader")
parser.add_option("--dry-run", dest="dryrun", action="store_true",
help="avoid executing commands")
parser.add_option("--fat16", dest="fat16", action="store_true",
help="format specified partition with FAT16")
parser.add_option("--force", dest="force", action="store_true",
help="force any actions requiring manual interaction")
parser.add_option("--grub", dest="grub", action="callback",
callback=grub_option,
help="install grub bootloader instead of (default) syslinux")
parser.add_option("--grub-mbr", dest="grubmbr", action="store_true",
help="install grub into MBR instead of (default) PBR")
parser.add_option("--mbr-menu", dest="mbrmenu", action="store_true",
help="enable interactive boot menu in MBR")
parser.add_option("--quiet", dest="quiet", action="store_true",
help="do not output anything but just errors on console")
parser.add_option("--remove-bootoption", dest="removeoption", action="append",
help="regex for removing existing bootoptions")
parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
help="do not install /boot/addons/ files")
parser.add_option("--skip-grub-config", dest="skipgrubconfig", action="store_true",
help="skip generation of grub configuration files")
parser.add_option("--skip-mbr", dest="skipmbr", action="store_true",
help="do not install a master boot record (MBR) on the device")
parser.add_option("--skip-syslinux-config", dest="skipsyslinuxconfig", action="store_true",
help="skip generation of syslinux configuration files")
parser.add_option("--syslinux", dest="syslinux", action="callback", default=True,
callback=syslinux_warning,
help="install syslinux bootloader (deprecated as it's the default)")
parser.add_option("--syslinux-mbr", dest="syslinuxmbr", action="store_true",
help="install syslinux master boot record (MBR) instead of default")
parser.add_option("--tmpdir", dest="tmpdir", default="/tmp",
help="directory to be used for temporary files")
parser.add_option("--verbose", dest="verbose", action="store_true",
help="enable verbose mode")
parser.add_option("-v", "--version", dest="version", action="store_true",
help="display version and exit")
(options, args) = parser.parse_args()
GRML2USB_BASE = '/usr/share/grml2usb'
if not os.path.isdir(GRML2USB_BASE):
GRML2USB_BASE = os.path.dirname(os.path.realpath(__file__))
class CriticalException(Exception):
"""Throw critical exception if the exact error is not known but fatal.
@Exception: message"""
pass
class VerifyException(Exception):
"""Throw critical exception if there is an fatal error when verifying something.
@Exception: message"""
pass
# The following two functions help to operate on strings as
# array (list) of bytes (octets). In Python 3000, the bytes
# datatype will need to be used. This is intended for using
# with manipulation of files on the octet level, like shell
# arrays, e.g. in MBR creation.
def array2string(*a):
"""Convert a list of integers [0;255] to a string."""
return struct.pack("%sB" % len(a), *a)
def string2array(s):
"""Convert a (bytes) string into a list of integers."""
return struct.unpack("%sB" % len(s), s)
def cleanup():
"""Cleanup function to make sure there aren't any mounted devices left behind.
"""
logging.info("Cleaning up before exiting...")
proc = subprocess.Popen(["sync"])
proc.wait()
try:
for device in MOUNTED:
unmount(device, "")
for tmpfile in TMPFILES:
os.unlink(tmpfile)
# ignore: RuntimeError: Set changed size during iteration
except RuntimeError:
logging.debug('caught expection RuntimeError, ignoring')
def register_tmpfile(path):
"""
register tmpfile
"""
TMPFILES.add(path)
def unregister_tmpfile(path):
"""
remove registered tmpfile
"""
try:
TMPFILES.remove(path)
except KeyError:
pass
def register_mountpoint(target):
"""register specified target in a set() for handling clean exiting
@target: destination target of mountpoint
"""
MOUNTED.add(target)
def unregister_mountpoint(target):
"""unregister specified target in a set() for handling clean exiting
@target: destination target of mountpoint
"""
if target in MOUNTED:
MOUNTED.remove(target)
def get_function_name(obj):
"""Helper function for use in execute() to retrive name of a function
@obj: the function object
"""
if not (isroutine(obj) or isclass(obj)):
obj = type(obj)
return obj.__module__ + '.' + obj.__name__
def execute(f, *exec_arguments):
"""Wrapper for executing a command. Either really executes
the command (default) or when using --dry-run commandline option
just displays what would be executed."""
# usage: execute(subprocess.Popen, (["ls", "-la"]))
if options.dryrun:
# pylint: disable-msg=W0141
logging.debug('dry-run only: %s(%s)', get_function_name(f), ', '.join(map(repr, exec_arguments)))
else:
# pylint: disable-msg=W0142
return f(*exec_arguments)
def is_exe(fpath):
"""Check whether a given file can be executed
@fpath: full path to file
@return:"""
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
def which(program):
"""Check whether a given program is available in PATH
@program: name of executable"""
fpath = os.path.split(program)[0]
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def get_defaults_file(iso_mount, flavour, name):
"""get the default file for syslinux
"""
bootloader_dirs = ['/boot/isolinux/', '/boot/syslinux/']
for directory in bootloader_dirs:
for name in name, \
"%s_%s" % (get_flavour_filename(flavour), name):
if os.path.isfile(iso_mount + directory + name):
return (directory, name)
return ('', '')
def search_file(filename, search_path='/bin' + os.pathsep + '/usr/bin', lst_return=False):
"""Given a search path, find file
@filename: name of file to search for
@search_path: path where searching for the specified filename
@lst_return: return list of matching files instead one file"""
paths = search_path.split(os.pathsep)
current_dir = '' # make pylint happy :)
retval = []
def match_file(cwd):
"""Helper function ffor testing if specified file exists in cwd
@cwd: current working directory
"""
return os.path.exists(os.path.join(cwd, filename))
for path in paths:
current_dir = path
if match_file(current_dir):
retval.append(os.path.abspath(os.path.join(current_dir, filename)))
if not lst_return:
break
# pylint: disable-msg=W0612
for current_dir, directories, files in os.walk(path):
if match_file(current_dir):
retval.append(os.path.abspath(os.path.join(current_dir, filename)))
if not lst_return:
break
if lst_return:
return retval
elif retval:
return retval[0]
else:
return None
def check_uid_root():
"""Check for root permissions"""
if not os.geteuid() == 0:
sys.exit("Error: please run this script with uid 0 (root).")
def check_boot_flag(device):
if device[-1:].isdigit():
boot_dev = re.match(r'(.*?)\d*$', device).group(1)
else:
boot_dev = device
with open(boot_dev, 'r') as image:
data = image.read(512)
bootcode = data[440:]
if bootcode[6] == '\x80':
logging.debug("bootflag is enabled")
else:
logging.debug("bootflag is NOT enabled")
raise VerifyException("Device %s does not have the bootflag set. "
"Please enable it to be able to boot." % boot_dev)
def mkfs_fat16(device):
"""Format specified device with VFAT/FAT16 filesystem.
@device: partition that should be formated"""
if options.dryrun:
logging.info("Would execute mkfs.vfat -F 16 %s now.", device)
return 0
logging.info("Formating partition with fat16 filesystem")
logging.debug("mkfs.vfat -F 16 %s", device)
proc = subprocess.Popen(["mkfs.vfat", "-F", "16", device])
proc.wait()
if proc.returncode != 0:
raise CriticalException("error executing mkfs.vfat")
def generate_isolinux_splash(grml_flavour):
"""Generate bootsplash for isolinux/syslinux
@grml_flavour: name of grml flavour the configuration should be generated for"""
grml_name = grml_flavour
return("""\
17/boot/syslinux/logo.16
Some information and boot options available via keys F2 - F10. http://grml.org/
%(grml_name)s
""" % {'grml_name': grml_name})
def generate_main_syslinux_config(*arg):
"""Generate main configuration for use in syslinux.cfg
@*arg: just for backward compatibility"""
# pylint: disable-msg=W0613
# remove warning about unused arg
return("""\
label -
menu label Default boot modes:
menu disable
include defaults.cfg
menu end
menu separator
# flavours:
label -
menu label Additional boot entries for:
menu disable
include additional.cfg
menu separator
include options.cfg
include addons.cfg
label help
include promptname.cfg
config prompt.cfg
text help
Jump to old style isolinux prompt
featuring further information
regarding available boot options.
endtext
include hiddens.cfg
""")
def generate_flavour_specific_syslinux_config(grml_flavour):
"""Generate flavour specific configuration for use in syslinux.cfg
@grml_flavour: name of grml flavour the configuration should be generated for"""
return("""\
menu begin grml %(grml_flavour)s
menu title %(display_name)s
label mainmenu
menu label ^Back to main menu...
menu exit
menu separator
# include config for boot parameters from disk
include %(grml_flavour)s_grml.cfg
menu hide
menu end
""" % {'grml_flavour': grml_flavour, 'display_name': get_flavour_filename(grml_flavour)})
def install_grub(device):
"""Install grub on specified device.
@mntpoint: mountpoint of device where grub should install its files to
@device: partition where grub should be installed to"""
if options.dryrun:
logging.info("Would execute grub-install [--root-directory=mount_point] %s now.", device)
else:
device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
register_tmpfile(device_mountpoint)
try:
try:
mount(device, device_mountpoint, "")
# If using --grub-mbr then make sure we install grub in MBR instead of PBR
if options.grubmbr:
logging.debug("Using option --grub-mbr ...")
if device[-1:].isdigit():
grub_device = re.match(r'(.*?)\d*$', device).group(1)
else:
grub_device = device
else:
grub_device = device
logging.info("Installing grub as bootloader")
for opt in ["", "--force"]:
logging.debug("grub-install --recheck %s --no-floppy --root-directory=%s %s",
opt, device_mountpoint, grub_device)
proc = subprocess.Popen(["grub-install", "--recheck", opt, "--no-floppy",
"--root-directory=%s" % device_mountpoint, grub_device],
stdout=file(os.devnull, "r+"))
proc.wait()
if proc.returncode == 0:
break
if proc.returncode != 0:
# raise Exception("error executing grub-install")
logging.critical("Fatal: error executing grub-install "
+ "(please check the grml2usb FAQ or drop the --grub option)")
logging.critical("Note: if using grub2 consider using "
+ "the --grub-mbr option as grub considers PBR problematic.")
cleanup()
sys.exit(1)
except CriticalException, error:
logging.critical("Fatal: %s", error)
cleanup()
sys.exit(1)
finally:
unmount(device_mountpoint, "")
os.rmdir(device_mountpoint)
unregister_tmpfile(device_mountpoint)
def install_syslinux(device):
"""Install syslinux on specified device.
@device: partition where syslinux should be installed to"""
if options.dryrun:
logging.info("Would install syslinux as bootloader on %s", device)
return 0
# syslinux -d boot/isolinux /dev/sdb1
logging.info("Installing syslinux as bootloader")
logging.debug("syslinux -d boot/syslinux %s", device)
proc = subprocess.Popen(["syslinux", "-d", "boot/syslinux", device])
proc.wait()
if proc.returncode != 0:
raise CriticalException("Error executing syslinux (either try --fat16 or use grub?)")
def install_bootloader(device):
"""Install bootloader on specified device.
@device: partition where bootloader should be installed to"""
# by default we use grub, so install syslinux only on request
if options.grub:
try:
install_grub(device)
except CriticalException, error:
logging.critical("Fatal: %s", error)
cleanup()
sys.exit(1)
else:
try:
install_syslinux(device)
except CriticalException, error:
logging.critical("Fatal: %s", error)
cleanup()
sys.exit(1)
def install_mbr(mbrtemplate, device, partition, ismirbsdmbr=True):
"""install 'mbr' master boot record (MBR) on a device
Retrieve the partition table from "device", install an MBR from the
"mbrtemplate" file, set the "partition" (0..3) active, and install the
result back to "device".
@mbrtemplate: default MBR file
@device: name of a file assumed to be a hard disc (or USB stick) image, or
something like "/dev/sdb"
@partition: must be a number between 0 and 3, inclusive
@mbrtemplate: must be a valid MBR file of at least 440 (or 439 if
ismirbsdmbr) bytes.
@ismirbsdmbr: if true then ignore the active flag, set the mirbsdmbr
specific flag to 0/1/2/3 and set the MBR's default value accordingly. If
false then leave the mirbsdmbr specific flag set to FFh, set all
active flags to 0 and set the active flag of the partition to 80h. Note:
behaviour of mirbsdmbr: if flag = 0/1/2/3 then use it, otherwise search for
the active flag."""
logging.info("Installing default MBR")
if not os.path.isfile(mbrtemplate):
logging.critical("Error: %s can not be read.", mbrtemplate)
raise CriticalException("Error installing MBR (either try --syslinux-mbr or install missing file \"%s\"?)" % mbrtemplate)
if partition is not None and ((partition < 0) or (partition > 3)):
logging.warn("Cannot activate partition %d" % partition)
partition = None
if ismirbsdmbr:
nmbrbytes = 439
else:
nmbrbytes = 440
tmpf = tempfile.NamedTemporaryFile()
logging.debug("executing: dd if='%s' of='%s' bs=512 count=1", device, tmpf.name)
proc = subprocess.Popen(["dd", "if=%s" % device, "of=%s" % tmpf.name, "bs=512", "count=1"],
stderr=file(os.devnull, "r+"))
proc.wait()
if proc.returncode != 0:
raise Exception("error executing dd (first run)")
logging.debug("executing: dd if=%s of=%s bs=%s count=1 conv=notrunc", mbrtemplate,
tmpf.name, nmbrbytes)
proc = subprocess.Popen(["dd", "if=%s" % mbrtemplate, "of=%s" % tmpf.name, "bs=%s" % nmbrbytes,
"count=1", "conv=notrunc"], stderr=file(os.devnull, "r+"))
proc.wait()
if proc.returncode != 0:
raise Exception("error executing dd (second run)")
mbrcode = tmpf.file.read(512)
if len(mbrcode) < 512:
raise EOFError("MBR size (%d) < 512" % len(mbrcode))
if partition is not None:
if ismirbsdmbr:
mbrcode = mbrcode[0:439] + chr(partition) + \
mbrcode[440:510] + "\x55\xAA"
else:
actives = ["\x00", "\x00", "\x00", "\x00"]
actives[partition] = "\x80"
mbrcode = mbrcode[0:446] + actives[0] + \
mbrcode[447:462] + actives[1] + \
mbrcode[463:478] + actives[2] + \
mbrcode[479:494] + actives[3] + \
mbrcode[495:510] + "\x55\xAA"
tmpf.file.seek(0)
tmpf.file.truncate()
tmpf.file.write(mbrcode)
tmpf.file.close()
logging.debug("executing: dd if='%s' of='%s' bs=512 count=1 conv=notrunc", tmpf.name, device)
proc = subprocess.Popen(["dd", "if=%s" % tmpf.name, "of=%s" % device, "bs=512", "count=1",
"conv=notrunc"], stderr=file(os.devnull, "r+"))
proc.wait()
if proc.returncode != 0:
raise Exception("error executing dd (third run)")
del tmpf
def is_writeable(device):
"""Check if the device is writeable for the current user
@device: partition where bootloader should be installed to"""
if not device:
return False
#raise Exception("no device for checking write permissions")
if not os.path.exists(device):
return False
return os.access(device, os.W_OK) and os.access(device, os.R_OK)
def mount(source, target, mount_options):
"""Mount specified source on given target
@source: name of device/ISO that should be mounted
@target: directory where the ISO should be mounted to
@options: mount specific options"""
# note: options.dryrun does not work here, as we have to
# locate files and identify the grml flavour
for x in file('/proc/mounts').readlines():
if x.startswith(source):
raise CriticalException("Error executing mount: %s already mounted - " % source
+ "please unmount before invoking grml2usb")
if os.path.isdir(source):
logging.debug("Source %s is not a device, therefore not mounting.", source)
return 0
logging.debug("mount %s %s %s", mount_options, source, target)
proc = subprocess.Popen(["mount"] + list(mount_options) + [source, target])
proc.wait()
if proc.returncode != 0:
raise CriticalException("Error executing mount (no filesystem on the partition?)")
else:
logging.debug("register_mountpoint(%s)", target)
register_mountpoint(target)
def unmount(target, unmount_options):
"""Unmount specified target
@target: target where something is mounted on and which should be unmounted
@options: options for umount command"""
# make sure we unmount only already mounted targets
target_unmount = False
mounts = open('/proc/mounts').readlines()
mountstring = re.compile(".*%s.*" % re.escape(os.path.realpath(target)))
for line in mounts:
if re.match(mountstring, line):
target_unmount = True
if not target_unmount:
logging.debug("%s not mounted anymore", target)
else:
logging.debug("umount %s %s", list(unmount_options), target)
proc = subprocess.Popen(["umount"] + list(unmount_options) + [target])
proc.wait()
if proc.returncode != 0:
raise Exception("Error executing umount")
else:
logging.debug("unregister_mountpoint(%s)", target)
unregister_mountpoint(target)
def check_for_usbdevice(device):
"""Check whether the specified device is a removable USB device
@device: device name, like /dev/sda1 or /dev/sda
"""
usbdevice = re.match(r'/dev/(.*?)\d*$', device).group(1)
# newer systems:
usbdev = os.path.realpath('/sys/class/block/' + usbdevice + '/removable')
if not os.path.isfile(usbdev):
# Ubuntu with kernel 2.6.24 for example:
usbdev = os.path.realpath('/sys/block/' + usbdevice + '/removable')
if os.path.isfile(usbdev):
is_usb = open(usbdev).readline()
if is_usb.find("1"):
return 0
return 1
def check_for_fat(partition):
"""Check whether specified partition is a valid VFAT/FAT16 filesystem
@partition: device name of partition"""
if not os.access(partition, os.R_OK):
raise CriticalException("Failed to read device %s"
" (wrong UID/permissions or device/directory not present?)" % partition)
try:
udev_info = subprocess.Popen(["/sbin/blkid", "-s", "TYPE", "-o", "value", partition],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
filesystem = udev_info.communicate()[0].rstrip()
if filesystem != "vfat":
raise CriticalException(
"Partition %s does not contain a FAT16 filesystem. "
"(Use --fat16 or run mkfs.vfat %s)" % (partition, partition))
except OSError:
raise CriticalException("Sorry, /sbin/blkid not available (install e2fsprogs?)")
def mkdir(directory):
"""Simple wrapper around os.makedirs to get shell mkdir -p behaviour"""
# just silently pass as it's just fine it the directory exists
if not os.path.isdir(directory):
try:
os.makedirs(directory)
# pylint: disable-msg=W0704
except OSError:
pass
def exec_rsync(source, target):
"""Simple wrapper around rsync to install files
@source: source file/directory
@target: target file/directory"""
logging.debug("Source: %s / Target: %s", source, target)
proc = subprocess.Popen(["rsync", "-rlptDH", "--inplace", source, target])
proc.wait()
if proc.returncode == 12:
logging.critical("Fatal: No space left on device")
cleanup()
sys.exit(1)
if proc.returncode != 0:
logging.critical("Fatal: could not install %s", source)
cleanup()
sys.exit(1)
def write_uuid(target_file):
"""Generates an returns uuid and write it to the specified file
@target_file: filename to write the uuid to
"""
fileh = open(target_file, 'w')
uid = str(uuid.uuid4())
fileh.write(uid)
fileh.close()
return uid
def get_uuid(target):
"""Get the uuid of the specified target. Will generate an uuid if none exist.
@target: directory/mountpoint containing the grml layout
"""
conf_target = target + "/conf/"
uuid_file_name = conf_target + "/bootid.txt"
if os.path.isdir(conf_target):
if os.path.isfile(uuid_file_name):
uuid_file = open(uuid_file_name, 'r')
uid = uuid_file.readline().strip()
uuid_file.close()
return uid
else:
return write_uuid(uuid_file_name)
else:
execute(mkdir, conf_target)
return write_uuid(uuid_file_name)
def get_shortname(grml_flavour):
"""Get shortname based from grml_flavour name. The rules applied are the same as in grml-live
@grml_flavour: flavour name which shold be translated to shortname"""
return re.sub(r'[,._-]', '', grml_flavour)
def copy_system_files(grml_flavour, iso_mount, target):
"""copy grml's main files (like squashfs, kernel and initrd) to a given target
@grml_flavour: name of grml flavour the configuration should be generated for
@iso_mount: path where a grml ISO is mounted on
@target: path where grml's main files should be copied to"""
squashfs = search_file(grml_flavour + '.squashfs', iso_mount)
if squashfs is None:
logging.critical("Fatal: squashfs file not found"
", please check that your iso is not corrupt")
raise CriticalException("error locating squashfs file")
else:
squashfs_target = target + '/live/' + grml_flavour + '/'
execute(mkdir, squashfs_target)
exec_rsync(squashfs, squashfs_target + grml_flavour + '.squashfs')
for prefix in grml_flavour + "/", "":
filesystem_module = search_file(prefix + 'filesystem.module', iso_mount)
if filesystem_module:
break
if filesystem_module is None:
logging.critical("Fatal: filesystem.module not found")
raise CriticalException("error locating filesystem.module file")
else:
exec_rsync(filesystem_module, squashfs_target + 'filesystem.module')
shortname = get_shortname(grml_flavour)
if os.path.isdir(iso_mount + '/boot/' + shortname):
exec_rsync(iso_mount + '/boot/' + shortname, target + '/boot')
else:
kernel = search_file('vmlinuz', iso_mount)
if kernel is None:
# compat for releases < 2011.12
kernel = search_file('linux26', iso_mount)
if kernel is None:
logging.critical("Fatal: kernel not found")
raise CriticalException("error locating kernel file")
source = os.path.dirname(kernel) + '/'
dest = target + '/' + os.path.dirname(kernel).replace(iso_mount, '') + '/'
execute(mkdir, dest)
exec_rsync(source, dest)
def update_grml_versions(iso_mount, target):
"""Update the grml version file on a cd
Returns true if version was updated successfully,
False if grml-version does not exist yet on the mountpoint
@iso_mount: string of the iso mount point
@target: path of the target mount point
"""
grml_target = target + '/grml/'
target_grml_version_file = search_file('grml-version', grml_target)
if target_grml_version_file:
iso_grml_version_file = search_file('grml-version', iso_mount)
if not iso_grml_version_file:
logging.warn("Warning: %s could not be found - can not install it", iso_grml_version_file)
return False
try:
# read the flavours from the iso image
iso_versions = {}
iso_file = open(iso_grml_version_file, 'r')
for line in iso_file:
iso_versions[get_flavour(line)] = line.strip()
# update the existing flavours on the target
for line in fileinput.input([target_grml_version_file], inplace=1):
flavour = get_flavour(line)
if flavour in iso_versions.keys():
print iso_versions.pop(flavour)
else:
print line.strip()
fileinput.close()
target_file = open(target_grml_version_file, 'a')
# add the new flavours from the current iso
for flavour in iso_versions:
target_file.write("%s\n" % iso_versions[flavour])
except IOError:
logging.warn("Warning: Could not write file")
finally:
iso_file.close()
target_file.close()
return True
else:
return False
def copy_grml_files(grml_flavour, iso_mount, target):
"""copy some minor grml files to a given target
@grml_flavour: the current grml_flavour
@iso_mount: path where a grml ISO is mounted on
@target: path where grml's main files should be copied to"""
grml_target = target + '/grml/'
execute(mkdir, grml_target)
grml_prefixe = ["GRML", "grml"]
for prefix in grml_prefixe:
filename = "{0}/{1}/{2}".format(iso_mount, prefix, grml_flavour)
if os.path.exists(filename):
exec_rsync(filename, grml_target)
break
else:
logging.warn("Warning: could not find flavour directory for %s ", grml_flavour)
def handle_addon_copy(filename, dst, iso_mount, ignore_errors=False):
"""handle copy of optional addons
@filename: filename of the addon
@dst: destination directory
@iso_mount: location of the iso mount
@ignore_errors: don't report missing files
"""
file_location = search_file(filename, iso_mount)
if file_location is None:
if not ignore_errors:
logging.warn("Warning: %s not found (that's fine if you don't need it)", filename)
else:
exec_rsync(file_location, dst)
def copy_addons(iso_mount, target):
"""copy grml's addons files (like allinoneimg, bsd4grml,..) to a given target
@iso_mount: path where a grml ISO is mounted on
@target: path where grml's main files should be copied to"""
addons = target + '/boot/addons/'
execute(mkdir, addons)
# grub all-in-one image
handle_addon_copy('allinone.img', addons, iso_mount)
# bsd image
handle_addon_copy('bsd4grml', addons, iso_mount)
# DOS image
handle_addon_copy('balder10.imz', addons, iso_mount)
# syslinux + pci.ids for hdt
for expr in '*.c32', 'pci.ids':
glob_and_copy(iso_mount + '/boot/addons/' + expr, addons)
# memdisk image
handle_addon_copy('memdisk', addons, iso_mount)
# memtest86+ image
handle_addon_copy('memtest', addons, iso_mount)
# gpxe.lkrn: got replaced by ipxe
handle_addon_copy('gpxe.lkrn', addons, iso_mount, ignore_errors=True)
# ipxe.lkrn
handle_addon_copy('ipxe.lkrn', addons, iso_mount)
def build_loopbackcfg(target):
"""Generate GRUB's loopback.cfg based on existing config files.
@target: target directory
"""
grub_dir = '/boot/grub/'
mkdir(os.path.join(target, grub_dir))
f = open(target + grub_dir + 'loopback.cfg', 'w')
f.write("# grml2usb generated grub2 configuration file\n")
f.write("source /boot/grub/header.cfg\n")
for defaults in glob.glob(target + os.path.sep + grub_dir + os.path.sep + "*_default.cfg"):
sourcefile = defaults.split(target + os.path.sep)[1]
logging.debug("Found source file" + sourcefile)
os.path.isfile(defaults) and f.write("source " + sourcefile + "\n")
for ops in glob.glob(target + os.path.sep + grub_dir + os.path.sep + "*_options.cfg"):
sourcefile = ops.split(target + os.path.sep)[1]
logging.debug("Found source file" + sourcefile)
os.path.isfile(ops) and f.write("source " + sourcefile + "\n")
f.write("source /boot/grub/adddons.cfg\n")
f.write("source /boot/grub/footer.cfg\n")
f.close()
def glob_and_copy(filepattern, dst):
"""Glob on specified filepattern and copy the result to dst
@filepattern: globbing pattern
@dst: target directory
"""
for name in glob.glob(filepattern):
copy_if_exist(name, dst)
def search_and_copy(filename, search_path, dst):
"""Search for the specified filename at searchpath and copy it to dst
@filename: filename to look for
@search_path: base search file
@dst: destionation to copy the file to
"""
file_location = search_file(filename, search_path)
copy_if_exist(file_location, dst)