【问题标题】:How to convert sudoers file into JSON data using Python?如何使用 Python 将 sudoers 文件转换为 JSON 数据?
【发布时间】:2018-11-26 00:25:23
【问题描述】:

我正在将 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

【问题讨论】:

  • 您的示例文件是什么样的?您可以添加它吗?
  • @SufiyanGhori,将其添加到主帖中。

标签: python json parsing sudoers


【解决方案1】:

你不需要在这里使用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"
}

【讨论】:

  • 感谢您的快速回复以及所有回复的人。我喜欢你所做的重构。老实说,我认为我完全偏离了我的方法。又是 Tyvm!
【解决方案2】:

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

#!/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)

【讨论】:

  • 感谢您的快速回复以及所有回复的人。直到现在我才考虑到cmets。好主意哈哈,再次感谢!
【解决方案3】:

您应该将其添加为字典列表。您修改后的代码是这样的:

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

【讨论】:

  • 感谢您的快速回复以及所有回复的人。我之前尝试过做类似的事情,但我需要一个 dict 来分配键和值。我尝试在字典上使用 append ,但这有效。感谢您的指导。 Tyvm 的帮助!
  • 祝你的项目好运!
猜你喜欢
  • 2019-04-18
  • 2017-05-01
  • 2019-12-03
  • 2021-11-25
  • 2011-09-21
  • 1970-01-01
  • 2017-02-20
  • 2021-12-04
  • 1970-01-01
相关资源
最近更新 更多