简体   繁体   中英

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. Also using a toml file that holds configuration settings for individual scans.

I need a method to store the scan results. So far I'm using a class that holds all target data. 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

[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? Or is there another method that could do a better job?

The toml library can do this for you. There are others like json , pyyaml etc that work in pretty much the same way. 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:

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. 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.

2. Write that to a file with this

3. From there load it into dictionary to toml converter with toml.dump with more info here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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