pythonparsinggrub

Is there a python grub.cfg parser?


Does anyone know of a python parser for grub2's grub.cfg file?

I'm trying to get the "menuentry" by device partition (root), e.g.

hd0,msdos1: ['Ubuntu, with Linux 3.0.0-15-generic',
            'Ubuntu, with Linux 3.0.0-15-generic (recovery mode)',
            'Ubuntu, with Linux 3.0.0-14-generic']
hd2,msdos1: ["Windows 7 (on /dev/sdc1)"]

etc.

Solution:

re.findall("menuentry ['\"](.*?)['\"].*?set root='(.*?)'", x, re.S)

[('Ubuntu, with Linux 3.0.0-15-generic', '(hd0,msdos1)'), ('Ubuntu, with Linux 3.0.0-15-generic (recovery mode)', '(hd0,msdos1)'), ('Ubuntu, with Linux 3.0.0-14-generic', '(hd0,msdos1)'), ('Ubuntu, with Linux 3.0.0-14-generic (recovery mode)', '(hd0,msdos1)'), ('Ubuntu, with Linux 3.0.0-13-generic', '(hd0,msdos1)'), ('Ubuntu, with Linux 3.0.0-13-generic (recovery mode)', '(hd0,msdos1)'), ('Ubuntu, with Linux 3.0.0-12-generic', '(hd0,msdos1)'), ('Ubuntu, with Linux 3.0.0-12-generic (recovery mode)', '(hd0,msdos1)'), ('Memory test (memtest86+)', '(hd0,msdos1)'), ('Memory test (memtest86+, serial console 115200)', '(hd0,msdos1)'), ('Windows 7 (on /dev/sdc1)', '(hd2,msdos1)')]


Solution

  • I'm not aware of a Python parser for grub.cfg, but you don't need to parse the whole file for that information. This is the format for the data you're looking for:

    menuentry "<name>" [options] {
      ...
      set root='<root>'
      ...
    }
    

    So look for lines starting with menuentry, parse the name from that line, and scan until the next line with a } for set root=.