简体   繁体   English

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

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

I'm writing a scanner in python that will gather various information about a target such as open ports, version info and so on.我正在 python 中编写一个扫描仪,它将收集有关目标的各种信息,例如开放端口、版本信息等。 Also using a toml file that holds configuration settings for individual scans.还使用一个 toml 文件来保存单个扫描的配置设置。

I need a method to store the scan results.我需要一种方法来存储扫描结果。 So far I'm using a class that holds all target data.到目前为止,我使用的是包含所有目标数据的 class。 Is there a way to store the results in a file and have library functions parse and print them as requested?有没有办法将结果存储在文件中并让库函数按要求解析和打印它们?

In toml representation I'm thinking of something like在 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'

Is there a way to dump scan results to toml file in this manner?有没有办法以这种方式将扫描结果转储到 toml 文件? Or is there another method that could do a better job?还是有另一种方法可以做得更好?

The toml library can do this for you. toml库可以为您做到这一点。 There are others like json , pyyaml etc that work in pretty much the same way.还有其他像jsonpyyaml等以几乎相同的方式工作。 In your example, you would first need to store the information in a dictionary, in the following format:在您的示例中,您首先需要将信息存储在字典中,格式如下:

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

Then, you can do:然后,你可以这样做:

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)

Similarly, you can also load toml files into the dictionary format using:同样,您也可以使用以下方法将 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. 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. They all use the same calling convention.它们都使用相同的调用约定。

You can use this stacktrace to achieve what you want to do:您可以使用此堆栈跟踪来实现您想要做的事情:

1. You could probably extract the data of the class as a dictionary through this method. 1.通过这种方法,您大概可以将class的数据提取为字典。

2. Write that to a file with this 2.这个把它写到一个文件中

3. From there load it into dictionary to toml converter with toml.dump with more info here 3.使用toml.dump将其加载到字典到 toml 转换器中,此处提供更多信息

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

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