2009-02-02 2 views
4

nagios3의 status.dat 파일을 구문 분석하고 Python 스크립트를 사용하여 XML로 출력하고 싶습니다. xml 부분은 쉬운 부분이지만 파일을 구문 분석하는 방법은 무엇입니까? 멀티 라인 정규식을 사용 하시겠습니까? 많은 호스트와 서비스를 모니터링 할 때 파일이 커질 수 있습니다. 전체 파일을 메모리에로드하는 것이 현명합니까?
중요한 상태와 호스트가 속한 서비스 만 추출하면됩니다.nagios status.dat 파일을 구문 분석하는 방법은 무엇입니까?

모든 도움과 올바른 방향을 가리키는 것이 매우 감사하겠습니다.

LE 여기에 파일이 보이는 방법은 다음과 같습니다

######################################## 
#   NAGIOS STATUS FILE 
# 
# THIS FILE IS AUTOMATICALLY GENERATED 
# BY NAGIOS. DO NOT MODIFY THIS FILE! 
######################################## 

info { 
    created=1233491098 
    version=2.11 
    } 

program { 
    modified_host_attributes=0 
    modified_service_attributes=0 
    nagios_pid=15015 
    daemon_mode=1 
    program_start=1233490393 
    last_command_check=0 
    last_log_rotation=0 
    enable_notifications=1 
    active_service_checks_enabled=1 
    passive_service_checks_enabled=1 
    active_host_checks_enabled=1 
    passive_host_checks_enabled=1 
    enable_event_handlers=1 
    obsess_over_services=0 
    obsess_over_hosts=0 
    check_service_freshness=1 
    check_host_freshness=0 
    enable_flap_detection=0 
    enable_failure_prediction=1 
    process_performance_data=0 
    global_host_event_handler= 
    global_service_event_handler= 
    total_external_command_buffer_slots=4096 
    used_external_command_buffer_slots=0 
    high_external_command_buffer_slots=0 
    total_check_result_buffer_slots=4096 
    used_check_result_buffer_slots=0 
    high_check_result_buffer_slots=2 
    } 

host { 
    host_name=localhost 
    modified_attributes=0 
    check_command=check-host-alive 
    event_handler= 
    has_been_checked=1 
    should_be_scheduled=0 
    check_execution_time=0.019 
    check_latency=0.000 
    check_type=0 
    current_state=0 
    last_hard_state=0 
    plugin_output=PING OK - Packet loss = 0%, RTA = 3.57 ms 
    performance_data= 
    last_check=1233490883 
    next_check=0 
    current_attempt=1 
    max_attempts=10 
    state_type=1 
    last_state_change=1233489475 
    last_hard_state_change=1233489475 
    last_time_up=1233490883 
    last_time_down=0 
    last_time_unreachable=0 
    last_notification=0 
    next_notification=0 
    no_more_notifications=0 
    current_notification_number=0 
    notifications_enabled=1 
    problem_has_been_acknowledged=0 
    acknowledgement_type=0 
    active_checks_enabled=1 
    passive_checks_enabled=1 
    event_handler_enabled=1 
    flap_detection_enabled=1 
    failure_prediction_enabled=1 
    process_performance_data=1 
    obsess_over_host=1 
    last_update=1233491098 
    is_flapping=0 
    percent_state_change=0.00 
    scheduled_downtime_depth=0 
    } 

service { 
    host_name=gateway 
    service_description=PING 
    modified_attributes=0 
    check_command=check_ping!100.0,20%!500.0,60% 
    event_handler= 
    has_been_checked=1 
    should_be_scheduled=1 
    check_execution_time=4.017 
    check_latency=0.210 
    check_type=0 
    current_state=0 
    last_hard_state=0 
    current_attempt=1 
    max_attempts=4 
    state_type=1 
    last_state_change=1233489432 
    last_hard_state_change=1233489432 
    last_time_ok=1233491078 
    last_time_warning=0 
    last_time_unknown=0 
    last_time_critical=0 
    plugin_output=PING OK - Packet loss = 0%, RTA = 2.98 ms 
    performance_data= 
    last_check=1233491078 
    next_check=1233491378 
    current_notification_number=0 
    last_notification=0 
    next_notification=0 
    no_more_notifications=0 
    notifications_enabled=1 
    active_checks_enabled=1 
    passive_checks_enabled=1 
    event_handler_enabled=1 
    problem_has_been_acknowledged=0 
    acknowledgement_type=0 
    flap_detection_enabled=1 
    failure_prediction_enabled=1 
    process_performance_data=1 
    obsess_over_service=1 
    last_update=1233491098 
    is_flapping=0 
    percent_state_change=0.00 
    scheduled_downtime_depth=0 
    } 

그것은 호스트의 수를 가질 수와 호스트 서비스의 수에는 제한이 없습니다.

답변

5

Nagiosity 당신이 원하는 것을 정확하게 수행을 mk_livestatus. 당신이 약간 안드레아의 솔루션을 조정할 경우 http://mathias-kettner.de/checkmk_livestatus.html

+0

을 Nagiosity는 "XML로 Nagios의 실시간 상태 다다이즘과 출력을합니다." 2011 년 이후로 업데이트되지는 않았지만 단지 작은 파이썬 스크립트 일뿐입니다. – AnneTheAgile

2

의 Nagios와 설정 파일을 알고 있지만 구조는 아주 간단 보인다하지 마십시오 단순히

<identifier> 
    <attribute name="attribute-name">attribute-value</attribute> 
</identifier> 

모든 번역 될 수

# comment 
identifier { 
    attribute= 
    attribute=value 
} 

루트 수준의 내부에 포함 된 <의 Nagios > 태그.

값에 줄 바꿈이 표시되지 않습니다. nagios에는 다중 행 값이 있습니까?

속성 값 내에서 등호를 처리해야하므로 정규식을 비 탐욕심으로 설정해야합니다.

2

이 같은 것을 할 수 있습니다 : 다음

def parseConf(filename): 
    conf = [] 
    with open(filename, 'r') as f: 
     for i in f.readlines(): 
      if i[0] == '#': continue 
      matchID = re.search(r"([\w]+) {", i) 
      matchAttr = re.search(r"[ ]*([\w]+)=([\w\d]*)", i) 
      matchEndID = re.search(r"[ ]*}", i) 
      if matchID: 
       identifier = matchID.group(1) 
       cur = [identifier, {}] 
      elif matchAttr: 
       attribute = matchAttr.group(1) 
       value = matchAttr.group(2) 
       cur[1][attribute] = value 
      elif matchEndID: 
       conf.append(cur) 
    return conf 

def conf2xml(filename): 
    conf = parseConf(filename) 
    xml = '' 
    for ID in conf: 
     xml += '<%s>\n' % ID[0] 
     for attr in ID[1]: 
      xml += '\t<attribute name="%s">%s</attribute>\n' % \ 
        (attr, ID[1][attr]) 
     xml += '</%s>\n' % ID[0] 
    return xml 

수행하려고 :

http://code.google.com/p/nagiosity/

9

, 환장, yerself를 얻을 :

print conf2xml('conf.dat') 
+0

해당 문서에 따라 MK_Livestatus는 DB 사용의 중복과 오버 헤드를 방지합니다. "Livestatus는 Nagios Event Broker API를 사용하고 Nagios 프로세스에 바이너리 모듈을로드하지만 NDO와는 달리 Livestatus는 데이터를 적극적으로 쓰지 않고 필요할 때 데이터를 검색 할 수있는 소켓을 엽니 다." [영어 비틀기 - 편집] 그것은 정기적 인 업데이 트를 받고있는 것 같습니다. – AnneTheAgile

2

당신은 status.dat뿐만 아니라 objects.cache 그것은 Nagios는 두 개의 서로 다른 형식을 사용하여 선택한 이유 수수께끼 조금

def parseConf(source): 
conf = [] 
for line in source.splitlines(): 
    line=line.strip() 
    matchID = re.match(r"(?:\s*define)?\s*(\w+)\s+{", line) 
    matchAttr = re.match(r"\s*(\w+)(?:=|\s+)(.*)", line) 
    matchEndID = re.match(r"\s*}", line) 
    if len(line) == 0 or line[0]=='#': 
     pass 
    elif matchID: 
     identifier = matchID.group(1) 
     cur = [identifier, {}] 
    elif matchAttr: 
     attribute = matchAttr.group(1) 
     value = matchAttr.group(2).strip() 
     cur[1][attribute] = value 
    elif matchEndID and cur: 
     conf.append(cur) 
     del cur 
return conf 

모두를 구문 분석하는 코드를 사용할 수 있습니다 이 파일들에 대해서는, 일단 당신이 그들을 둘다 사용 가능한 파이썬 객체로 파싱했다면, 외부 명령 파일을 통해 꽤 많은 마법을 쓸 수 있습니다.

만약 누군가 진짜 xml dom에 이것을 가져 오는 해결책을 가지고 있다면 정말 좋을 것입니다.

+0

정말 고마워! 참고 : parseConf 시작 부분에서 정규식을 컴파일하여 런타임을 약 절반으로 줄일 수 있습니다. – abesto

2

지난 몇 달 동안 Nagios status.dat 및 objects.cache를 구문 분석하고 Nagios 데이터를 실제로 조작하는 데 유용한 모델을 작성하는 도구를 작성하고 출시했습니다. 우리는이를 단순화 된 '미니'Nagios 인 내부 작업 대시 보드로 사용합니다. 그 지속적인 개발과 나는 테스트와 문서를 소홀히했지만 코드가 너무 미친되지 않으며 나는 따라하기 상당히 쉽습니다.나를 어떻게 생각하는지 보자

... https://github.com/zebpalmer/NagParser

+0

NagParser/nagparser/Services/nicetime.py에서 코드를 고맙게 생각합니다! 또한 날짜를 올바르게 번역 할 수있는 perl one -liner를 발견했습니다. http://geekpeek.net/nagios-log-convert-timestamp/. 내 서버에서 그것은 많은 1969 날짜를 찾습니다 :). – AnneTheAgile

2

이 뻔뻔 위의 예에서 도난당한 데, 는 여기 버전의 Nagios 부분의 배열을 포함하는 딕셔너리를 반환 파이썬 2.4 구축합니다.

def parseConf(source): 
    conf = {} 
    patID=re.compile(r"(?:\s*define)?\s*(\w+)\s+{") 
    patAttr=re.compile(r"\s*(\w+)(?:=|\s+)(.*)") 
    patEndID=re.compile(r"\s*}") 
    for line in source.splitlines(): 
     line=line.strip() 
     matchID = patID.match(line) 
     matchAttr = patAttr.match(line) 
     matchEndID = patEndID.match(line) 
     if len(line) == 0 or line[0]=='#': 
      pass 
     elif matchID: 
      identifier = matchID.group(1) 
      cur = [identifier, {}] 
     elif matchAttr: 
      attribute = matchAttr.group(1) 
      value = matchAttr.group(2).strip() 
      cur[1][attribute] = value 
     elif matchEndID and cur: 
      conf.setdefault(cur[0],[]).append(cur[1])    
      del cur 
    return conf 

모든 이름을 '개발 운영'로 시작 CONTACTGROUPS이 당신의 호스트 얻으려면 : 자신의 문서 당

nagcfg=parseConf(stringcontaingcompleteconfig) 
hostlist=[host['host_name'] for host in nagcfg['host'] 
      if host['contact_groups'].startswith('devops')]