요구 : 디렉토리내 모든 snmp dump 파일을 읽어서 oid 별로 정렬하여 하나의 파일로 생성

import datetime
import os

class Data:
    oid = ''
    line = ''

def snmp_oid_compare(in_name1, len1, in_name2, len2):
    name1 = in_name1
    name2 = in_name2

    # len = minimum of len1 and len2
    len_val = min(len1, len2)

    # find first non-matching OID
    for _ in range(len_val):
        if name1[0] != name2[0]:
            return -1 if name1[0] < name2[0] else 1
        name1 = name1[1:]
        name2 = name2[1:]

    # both OIDs equal up to length of shorter OID
    if len1 < len2:
        return -1
    elif len2 < len1:
        return 1
    else:
        return 0

dir_dump = "./dumps"
def main():
    my_list = []

    if not os.path.isdir(dir_dump):
        print("\n dir [./dumps] not found. exit.")
        exit(0)

    filelist = os.listdir(dir_dump)
    for li in filelist:
        fullpath = dir_dump + "/" + li
        f = open(fullpath, 'r')
        lines = f.readlines()
        i = 0
        for line in lines:
            i += 1
            if 'No Such Object' in line or line[0] != '.':
                print("[skip] not start dot(.) or failed oid: {}".format(line))
                continue
            tokens = line.split("=")

            data = Data()
            data.oid = tokens[0].rstrip()
            data.line = line
            new_oid = list(map(int, filter(None, data.oid.split("."))))
            found = False
            for j, item in enumerate(my_list):
                stored_oid = list(map(int, filter(None, item.oid.split("."))))
                result = snmp_oid_compare( stored_oid, len(stored_oid), new_oid, len(new_oid))
                if result >= 0:
                    my_list.insert(j, data)
                    found = True
                    print("정렬 line:%s,idx:%s,new:%s,old:%s" % (i, j, data.oid, item.oid))
                    break
            if not found:
                my_list.append(data)
        f.close()

    print("\n")
    i = 0
    file_path = "output.txt"
    with open(file_path, "w") as file:
        for item in my_list:
            i += 1
            file.write(f"{item.line}")

    print('Total process lines : {}'.format(i))

if __name__ == "__main__":
    start_time = datetime.datetime.now()
    main()
    end_time = datetime.datetime.now()
    print('Duration: {}'.format(end_time - start_time))

+ Recent posts