繁体   English   中英

将python模块output写入toml文件的方法

[英]Method to write python module output to toml file

我正在 python 中编写一个扫描仪,它将收集有关目标的各种信息,例如开放端口、版本信息等。 还使用一个 toml 文件来保存单个扫描的配置设置。

我需要一种方法来存储扫描结果。 到目前为止,我使用的是包含所有目标数据的 class。 有没有办法将结果存储在文件中并让库函数按要求解析和打印它们?

在 toml 表示中,我正在考虑类似的东西

[target]
ip = xx.xx.xx.xx
  [target.os]
  os = 'win 10'
  Arch = 'x64'

  [target.ports]
  ports = ['1', '2']

    [target.ports.1]
    service = 'xxx'
    ver = '5.9'

有没有办法以这种方式将扫描结果转储到 toml 文件? 还是有另一种方法可以做得更好?

toml库可以为您做到这一点。 还有其他像jsonpyyaml等以几乎相同的方式工作。 在您的示例中,您首先需要将信息存储在字典中,格式如下:

data = {
  "target": {
    "ip": "xx.xx.xx.xx",
    "os": {
      "os": "win 10",
      "Arch": "x64"
    },
    "ports": {
      "ports": ["1", "2"],
      "1": {
        "service": "xxx",
        "ver": "5.9",
      }
    } 
  }
}

然后,你可以这样做:

import toml

toml_string = toml.dumps(data)  # Output to a string

output_file_name = "output.toml"
with open(output_file_name, "w") as toml_file:
    toml.dump(data, toml_file)

同样,您也可以使用以下方法将 toml 文件加载到字典格式中:

import toml

toml_dict = toml.loads(toml_string)  # Read from a string

input_file_name = "input.toml"
with open(input_file_name) as toml_file:
    toml_dict = toml.load(toml_file)

If instead of toml you want to use yaml or json , it is as simple as replacing toml with yaml or json in all the commands. 它们都使用相同的调用约定。

您可以使用此堆栈跟踪来实现您想要做的事情:

1.通过这种方法,您大概可以将class的数据提取为字典。

2.这个把它写到一个文件中

3.使用toml.dump将其加载到字典到 toml 转换器中,此处提供更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM