有没有Python的grub.cfg解析器?

7 投票
2 回答
1939 浏览
提问于 2025-04-17 12:53

有没有人知道有没有适合解析grub2的grub.cfg文件的Python工具?

我想通过设备分区(根目录)来获取“menuentry”,比如说:

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)"]

等等。

解决方案:

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)')]

2 个回答

0

我觉得你可以试试这些解析器:augeaslibconfuseDevicetree

3

我不知道有没有专门用Python来解析grub.cfg文件的工具,但其实你不需要解析整个文件就能找到你需要的信息。你要找的数据格式是这样的:

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

所以你可以找那些以menuentry开头的行,从中提取出名字,然后继续扫描,直到遇到下一个包含}的行,看看有没有set root=

撰写回答