如何使用 Python 将 sudoers 文件转换为 JSON 数据?

How to convert sudoers file into JSON data using Python?

我正在为 sudoers 文件开发一个解析器,使之成为我正在处理的程序更容易阅读的格式。我是 Python 的初学者,没有足够的经验来完成我需要的工作。

到目前为止我有以下代码:

#!/usr/bin/env python

import operator
import os
import sys
import re
import json

example_file = "./Sudoers_example.txt"
try:
    column1 = []
    column2 = []
    column3 = []

    with open(example_file) as f:
        for line in f:
            #result.append(re.split(r'\s+', line)[0:3])
            column1.append(re.split(r'\s+', line)[0])
            column2.append(re.split(r'\s+', line)[1])
            column3.append(re.split(r'\s+', line)[2])

        mergedDict = {'op':column1, 'runas':column2, 'cmds':column3}

        print(json.dumps(mergedDict, indent=4, sort_keys=False))

except Exception as ee:
    print(ee)
    sys.exit(-1)

这不是我想要的。这是一项正在进行的工作。

尽管如此,我想看到的是:

{
    "hostname": "host.moo.com",
    "sudoers": [
        {
            "op": "operator1",
            "runas": "ALL=(ALL)",
            "cmds": "ALL"
        },
        {
            "op": "operator2",
            "runas": "ALL=(ALL)",
            "cmds": "ALL"
        }

    ]
}

我不确定下一步是什么。我该如何进行?

编辑,示例文件如下所示(根据要求):

root          ALL=(ALL) ALL
%group1 ALL=(ALL) ALL
operator1 ALL=(ALL) ALL
operator2 ALL=(ALL) ALL
%systems ALL=(ALL) ALL

你不需要在这里使用re,只需从文件中读取每一行并split它。

import json


js = {"hostname": "test", "sudoers":[]} # create json structure first
with open("/home/sufiyan/a") as f:
    for line in f:
        line = line.split() # split on every space character
        js["sudoers"].append({"op": line[0], "runas": line[1], "cmds": line[2]})


print(json.dumps(js))

# output,

{
  "sudoers": [
    {
      "runas": "ALL=(ALL)",
      "cmds": "ALL",
      "op": "root"
    },
    {
      "runas": "ALL=(ALL)",
      "cmds": "ALL",
      "op": "%group1"
    },
    {
      "runas": "ALL=(ALL)",
      "cmds": "ALL",
      "op": "operator1"
    },
    {
      "runas": "ALL=(ALL)",
      "cmds": "ALL",
      "op": "operator2"
    },
    {
      "runas": "ALL=(ALL)",
      "cmds": "ALL",
      "op": "%systems"
    }
  ],
  "hostname": "test"
}

我的两分钱(我添加了一些避免评论的检查):

#!/usr/bin/env python

import sys
import re
import json

example_file = "sudoers.txt"

try:
    sudoers = []

    with open(example_file) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#"):
                lst = re.split(r'\s+', line)
                if len(lst) > 2:
                    sudoers.append({
                        "op": lst[0],
                        "runas": lst[1],
                        "cmds": lst[2]
                    })

         ret = {"hostname": "host.moo.com",
               "sudoers": sudoers}

         print(json.dumps(ret, indent=4, sort_keys=False))

except Exception as ee:
    print(ee)
    sys.exit(-1)

您应该将其添加为词典列表。你改编的代码是这样的:

import operator
import os
import sys
import re
import json

example_file = "./Sudoers_example.txt"
sudoer_list = []
try:
    column1 = []

    with open(example_file) as f:
        for line in f:
            splits = re.split(r'\s+', line)
            sudoer_list.append({'op':splits[0], 'runas':splits[1], 'cmds':splits[2]})

        print(json.dumps(sudoer_list, indent=4, sort_keys=False))

except Exception as ee:
    print(ee)
    sys.exit(-1)

输出:

[
    {
        "op": "root",
        "runas": "ALL=(ALL)",
        "cmds": "ALL"
    },
    {
        "op": "%group1",
        "runas": "ALL=(ALL)",
        "cmds": "ALL"
    },
    {
        "op": "operator1",
        "runas": "ALL=(ALL)",
        "cmds": "ALL"
    },
    {
        "op": "operator2",
        "runas": "ALL=(ALL)",
        "cmds": "ALL"
    },
    {
        "op": "%systems",
        "runas": "ALL=(ALL)",
        "cmds": "ALL"
    }
]