Can you please review a little my simple Python code? I wrote this script to get list of hosts from text file and then iterate over these and get IP configured on active network interfaces - and finally add them to JSON dictionary file.
import sys
import json
import wmi
import logging
import os
HOSTS_FILE = sys.argv[1]
JSON_FILE = 'ip_list_PRD.json'
def addhostelement(host_enc, json_dict):
host_name = str(host_enc).rstrip('\n')
logger.info("Trying to get IP configuration of host " + host_name)
hosts_dict = json_dict
hosts_dict['hosts'][host_name] = []
wmi_session = wmi.WMI(host_name)
query_res = wmi_session.query("select IPAddress from Win32_NetworkAdapterConfiguration where IPEnabled='True'")
logger.info("Found " + str(len(query_res)) + " IP addresses")
for instance_ip in query_res:
ip_address = instance_ip.wmi_property("IPAddress")
ip_value = ip_address.value[0]
logger.info("Adding IP address " + ip_value + " to " + host_name + " node")
json_dict['hosts'][host_name].append(ip_value)
with open(JSON_FILE, 'w') as json_output_file:
json.dump(json_dict, json_output_file)
def formatjsonfile():
obj = None
with open(JSON_FILE) as jsonfileformat:
jsondata = json.load(jsonfileformat)
outfile = open(JSON_FILE, 'w')
outfile.write(json.dumps(jsondata,indent=4,separators=(',', ':'),ensure_ascii=True))
outfile.close
if __name__ == "__main__":
logging.basicConfig(level=logging.getLevelName(os.environ.get("LOG_LEVEL", "INFO")),
format="[%(levelname)s] %(funcName)20s() %(message)s")
logger = logging.getLogger(__name__)
with open(HOSTS_FILE, 'r') as hosts_file_read:
host_lines = hosts_file_read.readlines()
with open(JSON_FILE) as json_data:
json_dict = json.load(json_data)
for host_enc in host_lines:
if host_enc not in json_dict:
addhostelement(host_enc, json_dict)
formatjsonfile()