Method to write python module output to toml file
Asked Answered
A

2

10

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?

Americano answered 2/7, 2020 at 6:52 Comment(0)
I
10

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.

Implicate answered 2/7, 2020 at 7:25 Comment(0)
Z
0

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

Zerlina answered 2/7, 2020 at 7:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.