How do I filter nested cases to be filter out python

user2671444

I have an ascii plain text file input file with main case and nested case as below: I want to compare the instances start with '$' between details and @ExtendedAttr = nvp_add functions in input file below for each case under switch($specific-trap), but when i run the script under section python script, all nested cases are also print out, I dont want the nested cases to be print out here and for script to only consider cases under switch($specific-case). How should i do this help! :

Input file:
************
case ".1.3.6.1.4.1.27091.2.9": ###  - Notifications from JNPR-TIMING-MIB (1105260000Z)

    log(DEBUG, "<<<<< Entering... juniper-JNPR-TIMING-MIB.include.snmptrap.rules 
 >>>>>")

    @Agent = "JNPR-TIMING-MIB"
    @Class = "40200"

    $OPTION_TypeFieldUsage = "3.6"

    switch($specific-trap)
    {
        case "1": ### trapMsgNtpStratumChange

            ##########
            # $1 = trapAttrSource
            # $2 = trapAttrSeverity
            ##########

             $trapAttrSource = $1
             $trapAttrSeverity = lookup($2, TrapAttrSeverity)

             $OS_EventId = "SNMPTRAP-juniper-JNPR-TIMING-MIB-trapMsgNtpStratumChange"

             @AlertGroup = "NTP Stratum Status"
             @AlertKey = "Source: " + $trapAttrSource
             @Summary = "NTP Stratum Changes" + " ( " + @AlertKey + " ) "

        switch($2)
        {
            case "1":### clear
                $SEV_KEY = $OS_EventId + "_clear"
                @Summary = "End of: " + @Summary

                $DEFAULT_Severity = 1
                $DEFAULT_Type = 2
                $DEFAULT_ExpireTime = 0

            case "2":### none
                $SEV_KEY = $OS_EventId + "_none"

                $DEFAULT_Severity = 2
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            case "3":### minor
                $SEV_KEY = $OS_EventId + "_minor"

                $DEFAULT_Severity = 3
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            case "4":### major
                $SEV_KEY = $OS_EventId + "_major"

                $DEFAULT_Severity = 4
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            case "5":### critical
                $SEV_KEY = $OS_EventId + "_critical"

                $DEFAULT_Severity = 5
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            default:
                $SEV_KEY = $OS_EventId + "_unknown"

                $DEFAULT_Severity = 2
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0
        }

        update(@Severity)

        $trapAttrSeverity = $trapAttrSeverity + " ( " + $2 + " )"

        @Identifier = @Node + " " + @AlertKey + " " + @AlertGroup + " " + 
      $DEFAULT_Type + " " + @Agent + " " + @Manager + " " + $specific-trap

        if(match($OPTION_EnableDetails, "1") or match($OPTION_EnableDetails_juniper,
      "1")) {
            details($trapAttrSource,$trapAttrSeverity)
        }
        @ExtendedAttr = nvp_add(@ExtendedAttr, "trapAttrSource", $trapAttrSource, 
     "trapAttrSeverit")

    case "2": ### trapMsgNtpLeapChange

        ##########
        # $1 = trapAttrSource
        # $2 = trapAttrSeverity
        ##########

        $trapAttrSource = $1
        $trapAttrSeverity = lookup($2, TrapAttrSeverity)

        $OS_EventId = "SNMPTRAP-juniper-JNPR-TIMING-MIB-trapMsgNtpLeapChange"

        @AlertGroup = "NTP Leap Status"
        @AlertKey = "Source: " + $trapAttrSource
        @Summary = "NTP Leap Changes" + " ( " + @AlertKey + " ) "

        switch($2)
        {
            case "1":### clear
                $SEV_KEY = $OS_EventId + "_clear"
                @Summary = "End of: " + @Summary

                $DEFAULT_Severity = 1
                $DEFAULT_Type = 2
                $DEFAULT_ExpireTime = 0

            case "2":### none
                $SEV_KEY = $OS_EventId + "_none"

                $DEFAULT_Severity = 2
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            case "3":### minor
                $SEV_KEY = $OS_EventId + "_minor"

                $DEFAULT_Severity = 3
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            case "4":### major
                $SEV_KEY = $OS_EventId + "_major"

                $DEFAULT_Severity = 4
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            case "5":### critical
                $SEV_KEY = $OS_EventId + "_critical"

                $DEFAULT_Severity = 5
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0

            default:
                $SEV_KEY = $OS_EventId + "_unknown"

                $DEFAULT_Severity = 2
                $DEFAULT_Type = 1
                $DEFAULT_ExpireTime = 0
        }

        update(@Severity)

        $trapAttrSeverity = $trapAttrSeverity + " ( " + $2 + " )"

        @Identifier = @Node + " " + @AlertKey + " " + @AlertGroup + " " + 
        $DEFAULT_Type + " " + @Agent + " " + @Manager + " " + $specific-trap

        if(match($OPTION_EnableDetails, "1") or match($OPTION_EnableDetails_juniper, 
       "1")) {
            details($trapAttrSource,$trapAttrSeverity)
        }
        @ExtendedAttr = nvp_add(@ExtendedAttr, "trapAttrSource", $trapAttrSource, 
       "trapAttrSeverity", $trapAttrSeverity)


Below is the code which I use suggested by Vaibhav Aggarwal one of the member in 
this stakeoverflow.

Python Script
**************

 import re


`caselines_index = []
 cases = []
 readlines = []

 def read(in_file):
 global cases
 global caselines_index
 global readlines
 with open(in_file, 'r') as file:
    for line in file.readlines():
       readlines.append(line.strip())
    for line in readlines:
       case_search = re.search("case\s\".+?\"\:\s", line)
         if case_search:
           caselines_index.append(readlines.index(line))
#print caselines_index
caselines_index_iter = iter(caselines_index)
int_line_index = int(next(caselines_index_iter))
int_next_index = int(next(caselines_index_iter))
while True:
  try:
    case_text = ' '.join(readlines[int_line_index:int_next_index]).strip()
    case = [readlines[int_line_index].strip(), case_text]
    cases.append(case)
    int_line_index = int_next_index
    int_next_index = int(next(caselines_index_iter))
  except StopIteration:
    case_text = ' '.join(readlines[int_line_index:len(readlines) - 1]).strip()
    case = [readlines[int_line_index].strip(), case_text]
    cases.append(case)
    break

def work():
  MATCH = 1
   for case_list in cases:
     details = []
     nvp_add = []
     caseline = case_list[0].strip()
     nvp = re.findall("details\(.+?\)", case_list[1].strip())

    for item in nvp:
        result_list = re.findall("(\$.+?)[\,\)]", item)

    for result in result_list:
        if "$*" not in result:
            details.append(result)

    nvp = re.findall("nvp_add\(.+?\)", case_list[1].strip())

    for item in nvp:
       result_list = re.findall("(\$.+?)[\,\)]", item)

    for result in result_list:
       if "$*" not in result:
          nvp_add.append(result)

missing_from_details, missing_from_nvp_add = [], []
missing_from_details = [o for o in nvp_add if o not in set(details)]
missing_from_nvp_add = [o for o in details if o not in set(nvp_add)]
if missing_from_nvp_add or missing_from_details:
  MATCH = 0
  print caseline + "   LINE - " + str(readlines.index(caseline) + 1)
  for mismatch in missing_from_details:
    print "Missing from details:"
    print mismatch
  for mismatch in missing_from_nvp_add:
    print "Missing from nvp_add:"
    print mismatch
  print "\n"
 if MATCH == 1:
   print "MATCH"
 else:
   print "MISMATCHES"


def main():
  in_file = "C:/target1.txt"
  read(in_file)
  work()


if __name__=="__main__":
main()
Vaibhav Aggarwal
import re
from sys import stdout

#stdout = open("result.txt", 'w+')


def read(in_file):
  cases = []
  caselines_index = []
  readlines = []
  readlines_num = []
  with open(in_file, 'r') as file:
    readfile = file.read().strip()
    for line in readfile.split('\n'):
      readlines_num.append(line.strip())
    regex = re.compile("switch\(\$\d\).+?\}", re.DOTALL)
    readfile = re.sub(regex, ' ', readfile)
    for line in readfile.split('\n'):
      readlines.append(line.strip())
    for line in readlines:
      case_search = re.search("case\s\".+?\"\:\s", line)
      if case_search:
        caselines_index.append(readlines.index(line))
    #print caselines_index
    caselines_index_iter = iter(caselines_index)
    try:
      int_line_index = int(next(caselines_index_iter))
    except:
      print "No cases found"
    try:
      int_next_index = int(next(caselines_index_iter))
    except:
      int_next_index = len(readlines) - 1
    while True:
      try:
        case_text = ' '.join(readlines[int_line_index:int_next_index]).strip()
        match1 = re.search("nvp_add", case_text)
        match2 = re.search("details", case_text)
        if match1 or match2:
          case = [readlines[int_line_index].strip(), readlines_num.index(readlines[int_line_index]) + 1, case_text]
          cases.append(case)
        int_line_index = int_next_index
        int_next_index = int(next(caselines_index_iter))
      except StopIteration:
        case_text = ' '.join(readlines[int_line_index:len(readlines) - 1]).strip()
        case = [readlines[int_line_index].strip(), readlines_num.index(readlines[int_line_index]), case_text]
        cases.append(case)
        break
  return cases

def work(cases):
  MATCH = 1
  for case_list in cases:
    details = []
    nvp_add = []
    caseline = case_list[0].strip()
    nvp = re.findall("details\(.+?\)", case_list[2].strip())

    for item in nvp:
      result_list = re.findall("(\$.+?)[\,\)]", item)

      for result in result_list:
        if "$*" not in result:
          details.append(result)

    nvp = re.findall("nvp_add\(.+?\)", case_list[2].strip())

    for item in nvp:
      result_list = re.findall("(\$.+?)[\,\)]", item)

      for result in result_list:
        if "$*" not in result:
          nvp_add.append(result)

    missing_from_details, missing_from_nvp_add = [], []
    missing_from_details = [o for o in nvp_add if o not in set(details)]
    missing_from_nvp_add = [o for o in details if o not in set(nvp_add)]
    if missing_from_nvp_add or missing_from_details:
      MATCH = 0
      print caseline + "   LINE - " + str(case_list[1] + 1)
      for mismatch in missing_from_details:
        print "Missing from details:"
        print mismatch
      for mismatch in missing_from_nvp_add:
        print "Missing from nvp_add:"
        print mismatch
      print "\n"
  if MATCH == 1:
    print "MATCH"
  else:
    print "MISMATCHES"


def main():
  in_file = "target1.txt"
  cases = read(in_file)
  work(cases)


if __name__=="__main__":
  main()

This will filter out all the switches that are nested. This will only work in your case with your input file.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to do a filter nested in TypeScript

分類Dev

How do I filter out random sample from dataframe in which there are different sample size for each value, in python?

分類Dev

How do I filter out values from these JSON objects

分類Dev

How do I filter through nested JSON data in AngularJS

分類Dev

In CloudWatch Insights, how do I filter out log entries that don't have a parsed value?

分類Dev

How do I filter out "useful" mounts from /etc/mtab or /proc/mounts

分類Dev

How do I use -Filter (with regex)?

分類Dev

How do filter and convert unicode to integer in python

分類Dev

How can I filter out text twice in Powershell?

分類Dev

MongoDB how to filter in nested array

分類Dev

How to do "OR" filter in slick

分類Dev

HQL variables Filter cases

分類Dev

Postgres: how do I filter by a datetime field with infinity and -infinity?

分類Dev

How do i filter an array inside of a array of objects?

分類Dev

How do I filter values from a Vec and still return a Vec?

分類Dev

How do I filter a GlideRecord Query for tasks by a Change Request Field

分類Dev

How do I use a filter within a mutate statement?

分類Dev

How do I filter specific word from a values

分類Dev

How do I filter a list sorted from Checkbox Values in Angular?

分類Dev

Pandas: how do I select(filter) a subgroup within a subgroup?

分類Dev

How do I filter both parents and children in a O(1) queries?

分類Dev

NodeJS Loopback - How do I filter models by its relations

分類Dev

How do I plot the frequency response of a digital filter in MATLAB?

分類Dev

How do I filter resources provided by dependencies in Maven?

分類Dev

How to filter out from count distinct query

分類Dev

How to filter some files out of my directory?

分類Dev

How to filter out harmonics (DSP) using MATLAB?

分類Dev

How to filter out Hibernate log entries

分類Dev

How to filter nested object not equal in Angular?

Related 関連記事

  1. 1

    How to do a filter nested in TypeScript

  2. 2

    How do I filter out random sample from dataframe in which there are different sample size for each value, in python?

  3. 3

    How do I filter out values from these JSON objects

  4. 4

    How do I filter through nested JSON data in AngularJS

  5. 5

    In CloudWatch Insights, how do I filter out log entries that don't have a parsed value?

  6. 6

    How do I filter out "useful" mounts from /etc/mtab or /proc/mounts

  7. 7

    How do I use -Filter (with regex)?

  8. 8

    How do filter and convert unicode to integer in python

  9. 9

    How can I filter out text twice in Powershell?

  10. 10

    MongoDB how to filter in nested array

  11. 11

    How to do "OR" filter in slick

  12. 12

    HQL variables Filter cases

  13. 13

    Postgres: how do I filter by a datetime field with infinity and -infinity?

  14. 14

    How do i filter an array inside of a array of objects?

  15. 15

    How do I filter values from a Vec and still return a Vec?

  16. 16

    How do I filter a GlideRecord Query for tasks by a Change Request Field

  17. 17

    How do I use a filter within a mutate statement?

  18. 18

    How do I filter specific word from a values

  19. 19

    How do I filter a list sorted from Checkbox Values in Angular?

  20. 20

    Pandas: how do I select(filter) a subgroup within a subgroup?

  21. 21

    How do I filter both parents and children in a O(1) queries?

  22. 22

    NodeJS Loopback - How do I filter models by its relations

  23. 23

    How do I plot the frequency response of a digital filter in MATLAB?

  24. 24

    How do I filter resources provided by dependencies in Maven?

  25. 25

    How to filter out from count distinct query

  26. 26

    How to filter some files out of my directory?

  27. 27

    How to filter out harmonics (DSP) using MATLAB?

  28. 28

    How to filter out Hibernate log entries

  29. 29

    How to filter nested object not equal in Angular?

ホットタグ

アーカイブ