summaryrefslogtreecommitdiffstats
path: root/scripts/python/libvirt-xml2netbox-csv_interfaces.py
blob: 6ad2a24cea6b7c9ddfcdc0e758d554ca0d7bfc67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/python3
"""
Takes a directory with libvirt XML domain dumps and creates a NetBox importable CSV with VM interfaces. Intended to be used subsequently to libvirt-xml2netbox.py.
Note: we want the VM interfaces to be created with the interface name the operating system is seeing. Since libvirt only knows the host-side interface or network association, and since it was decided that integrating an automated interface name extraction process with a different source which merges with the libvirt data would not be economic, manual editing of the interface names in the resulting CSV - according to the data presented by the VM operating systems - is required.

Created and Last modified: 02/01/2022 by Georg Pfuetzenreuter <georg@lysergic.dev>
"""

import os
import xml.etree.ElementTree as xmlet
import pandas

cluster = "xxx"
indir = "xmls/" + cluster + "/domains"
outfile = cluster + "_interfaces.csv"

columns = [ "virtual_machine", "name", "enabled", "mac_address", "mtu", "description", "mode" ]
rows = []


for domainxml in os.listdir(indir):
    xmlparse = xmlet.parse(indir + "/" + domainxml)
    xmlroot = xmlparse.getroot()
    domain = xmlroot.find("name").text
    for interface in xmlroot.findall("devices/interface"):
        interface_type = next(iter(interface.attrib.values()))
        if interface_type ==  "network":
            source = interface.find("source").attrib["network"]
        if interface_type ==  "bridge":
            source = interface.find("source").attrib["bridge"]
        mac_address = interface.find("mac").attrib["address"]
        model = interface.find("model").attrib["type"]
        enabled = "true"
        mtu  = "1500"
        mode = "access"
        description = "Imported from libvirt. Model: " + model +  "."

        rows.append(
                {
                    "virtual_machine": domain,
                    "name": source,
                    "enabled": enabled,
                    "mac_address": mac_address,
                    "mtu": mtu,
                    "description": description,
                    "mode": mode
                }
        )

convert = pandas.DataFrame(rows, columns=columns)
convert.to_csv(outfile, index=False)