NETWORK_ADAPTATER = {
    0: "Ethernet 802.3",
    1: "Token Ring 802.5",
    2: "Fiber Distributed Data Interface (FDDI)",
    3: "Wide Area Network (WAN)",
    4: "LocalTalk",
    5: "Ethernet using DIX header format",
    6: "ARCNET",
    7: "ARCNET (878.2)",
    8: "ATM",
    9: "Wireless",
    10: "Infrared Wireless",
    11: "Bpc",
    13: "CoWan",
    14: "1394",
    15: "Tunnel"
} def write_to_output(str_to_write, output, logger):
    """Writes content to a file, encoding the string in UTF-8 for compatibility issues"""
    try:
        output.write(str_to_write.encode("utf-8"))
    except UnicodeError:
        logger.error(traceback.format_exc())
 def get_csv_writer(csvfile):
    return UnicodeWriter(csvfile, quoting=csv.QUOTE_ALL)
 def write_to_json(header, arr_data, json_writer):
    """Write data in json files using UTF-8"""
    try:
        json_writer.dump_json({
            h: arr_data[index] for index, h in enumerate(header)
        })
    except IndexError:
        json_writer.dump_json({
            header[index]: d for index, d in enumerate(arr_data)
        })
 def close_json_writer(json_writer):
    json_writer.close_current()
 def get_json_writer(json_file):
    return UnicodeJsonDumper(json_file)
 def write_list_to_json(arr_data, json_writer):
    """Write list data in json files using UTF-8"""
    json_writer.list_to_json(arr_data)
 def write_to_csv(arr_data, csv_writer):
    """Writes contents to a CSV file using UTF-8"""
    csv_writer.writerow(arr_data)
 def get_terminal_decoded_string(string):
    return string.decode(sys.stdout.encoding, "ignore")
 def record_sha256_logs(fr, fw):
    with open(fw, "a") as hash_file:
        m = process_sha256(fr)
        hash_file.write(fr + "," + m + "\n")
        hash_file.close()
 def process_md5(path):
    with open(path, "rb") as f:
        return hashlib.md5(f.read()).hexdigest()
 def process_sha1(path):
    with open(path, "rb") as f:
        return hashlib.sha1(f.read()).hexdigest()

import os
import subprocess
import traceback
import psutil
import win32process
import re
import wmi
import datetime
from settings import NETWORK_ADAPTATER
from utils.utils import write_to_output, get_csv_writer, write_to_json, close_json_writer, get_json_writer,\
     write_list_to_json, write_to_csv, get_terminal_decoded_string, record_sha256_logs, process_md5, process_sha1

                        nbtstat_value = ' '.join([n.replace('\n', '') for n in nbtstat_value])
                    if nc.DNSServerSearchOrder:
                        DNS_server = nc.DNSServerSearchOrder[0]
                    if nc.DHCPEnabled:
                        if nc.DHCPServer:
                            DHCP_server = nc.DHCPServer
            yield netcard, adapter_type, description, mac_address, product_name, physical_adapter, product_name, speed,\
                  IPv4, IPv6, DHCP_server, DNS_server, database_path, nbtstat_value

    def _list_arp_table(self):
        cmd = "arp -a"
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, errors = p.communicate()
        output = get_terminal_decoded_string(output)
        item = output.split("\n")
        for i in item:
            yield i

    def _list_route_table(self):
        route_table = self.wmi.Win32_IP4RouteTable()
        for r in route_table:
            yield r.Name, r.Mask

    def _list_sockets_network(self):
        for pid in win32process.EnumProcesses():
            try:
                p = psutil.Process(pid)
                local_addr = ''
                local_port = ''
                remote_addr = ''
                remote_port = ''
                for connection in p.connections():
                    if len(connection.laddr) > 0:
                        local_addr = connection.laddr[0]
                        local_port = connection.laddr[1]
                    if len(connection.raddr) > 0:
                        remote_addr = connection.raddr[0]
                        remote_port = connection.raddr[1]
                    yield pid, p.name(), local_addr, local_port, remote_addr, remote_port, connection.status
            except psutil.AccessDenied:
                self.logger.warning(traceback.format_exc())

    def _list_services(self):
        services = self.wmi.Win32_Service()
        for s in services:
            yield s.Name, s.Caption, s.ProcessId, s.PathName, s.ServiceType, s.Status, s.State, s.StartMode

    def _list_kb(self):
        for kb in self.wmi.Win32_QuickFixEngineering():
            yield kb.Caption, kb.CSName, kb.FixComments, kb.HotFixID, kb.InstallDate, kb.InstalledOn, kb.Name, \
                  kb.ServicePackInEffect, kb.Status

    def _csv_list_running_process(self, list_running):
        self.logger.info("Health : Listing running processes")
        with open(self.output_dir + '%s_processes' % self.computer_name + self.rand_ext, 'ab') as fw:
            csv_writer = get_csv_writer(fw)
            write_to_csv(["COMPUTER_NAME", "TYPE", "PID", "PROCESS_NAME", "COMMAND", "EXEC_PATH"], csv_writer)
            for p in list_running:
                pid = p[0]
                name = p[1]
                cmd = p[2]
                exe_path = p[3]
                write_to_csv(
                    [self.computer_name, 'processes', unicode(pid), name, unicode(cmd), unicode(exe_path)],
                    csv_writer)
        record_sha256_logs(self.output_dir + self.computer_name + '_processes' + self.rand_ext,
                           self.output_dir + self.computer_name + '_sha256.log')

    def _json_list_running_process(self, list_running):
        self.logger.info("Health : Listing running processes")
        if self.destination == 'local':
            with open(self.output_dir + '%s_processes' % self.computer_name + self.rand_ext, 'ab') as fw:
                json_writer = get_json_writer(fw)
                to_write = [["COMPUTER_NAME", "TYPE", "PID", "PROCESS_NAME", "COMMAND", "EXEC_PATH"]]
                to_write += [[self.computer_name, 'processes', unicode(p[0]), p[1], unicode(p[2]), unicode(p[3])]
                             for p in list_running]
                write_list_to_json(to_write, json_writer)
            record_sha256_logs(self.output_dir + self.computer_name + '_processes' + self.rand_ext,
                               self.output_dir + self.computer_name + '_sha256.log')

    def _csv_hash_running_process(self, list_running):
        self.logger.info("Health : Hashing running processes")
        with open(self.output_dir + '%s_hash_processes' % self.computer_name + self.rand_ext, 'ab') as fw:
            csv_writer = get_csv_writer(fw)
            write_to_csv(["COMPUTER_NAME", "TYPE", "PID", "PROCESS_NAME", "EXEC_PATH", "MD5", "SHA1", "CTIME", "MTIME",
                          "ATIME"], csv_writer)
            for p in list_running:
                pid = p[0]
                name = p[1]
                # cmd = p[2]
                exe_path = p[3]
                if exe_path and os.path.isfile(exe_path):
                    ctime = datetime.datetime.fromtimestamp(os.path.getctime(exe_path))
                    mtime = datetime.datetime.fromtimestamp(os.path.getmtime(exe_path))
                    atime = datetime.datetime.fromtimestamp(os.path.getatime(exe_path))
                    md5 = process_md5(unicode(exe_path))
                    sha1 = process_sha1(unicode(exe_path))
                    write_to_csv(
                        [self.computer_name, 'hash processes', unicode(pid), name, unicode(exe_path), md5, sha1, ctime,
                         mtime, atime], csv_writer)
        record_sha256_logs(self.output_dir + self.computer_name + '_hash_processes' + self.rand_ext,
                           self.output_dir + self.computer_name + '_sha256.log')

    def _json_hash_running_process(self, list_running):
        self.logger.info("Health : Hashing running processes")
        if self.destination == 'local':
            with open(self.output_dir + '%s_hash_processes' % self.computer_name + self.rand_ext, 'ab') as fw:
                json_writer = get_json_writer(fw)
                to_write = [["COMPUTER_NAME", "TYPE", "PID", "PROCESS_NAME", "EXEC_PATH", "MD5", "SHA1", "CTIME",
                             "MTIME", "ATIME"]]
                for p in list_running:
                    pid = p[0]
                    name = p[1]
                    # cmd = p[2]
                    exe_path = p[3]
                    if exe_path and os.path.isfile(exe_path):
                        ctime = datetime.datetime.fromtimestamp(os.path.getctime(exe_path))
                        mtime = datetime.datetime.fromtimestamp(os.path.getmtime(exe_path))
                        atime = datetime.datetime.fromtimestamp(os.path.getatime(exe_path))
                        md5 = process_md5(unicode(exe_path))

                        sha1 = process_sha1(unicode(exe_path))
