Python/Python for Windows

[Python] check ICMP using ping3 module. (파이썬을 이용한 ping 체크)

Pydole 2019. 8. 19. 18:31

 

 시스템을 운영하다 보면 기본적으로 서버나 네트워크 장비 ICMP 핼스 체크를 지속적으로 해야하는데, python의 ping3 모듈을

이용하여 구현할 수 있다.

 

 

모듈 설치 : pip install ping3

 

 

소스설명

 

우선 프로그램이 pinglist.txt 파일에 ping check 해야하는 리스트를 기입한다.

테스트IP를 설명하자면 203 IP서버는 네트워크가 단절되어 있고, #으로 시작하는 IP는 주석으로 인식하여 check 대상에서 제외된다.

 

 

IP 서버설명

 

10.x.x.201 Test_Server1

10.x.x.202 Test_Server2

10.x.x.203 Test_Server3 → 네트워크 단절

10.x.x.204 Test_Server5

10.x.x.205 Test_Server6

#10.x.x.206 Test_Server7 → 주석처리

​​

import time
from datetime import datetime
from ping3 import ping,verbose_ping

while True:
    with open('pinglist.txt', 'r') as f:
        for line in f.readlines():
            site = line.split('\t')
            if site[0][0] == '#':
                pass
            else:
                result = ping(site[0])
                if result == None:
                    print(site[0] + '\t' + site[1][:-1] + '\t' + ' Ping Check Fail : '+ str(datetime.now())[:19])

                else:
                    print(site[0]+'\t'+site[1][:-1]+'\t'+' Ping Check OK :', '[ Response Time %.2f ] : ' %result+str(datetime.now())[:19])
            time.sleep(1)
        time.sleep(60)

 

실행하면 아래와 같이 결과가 나온다.

10.x.x.201 Test_Server1 Ping Check OK : [ Response Time 0.01 ] : 2019-08-19 18:13:44

10.x.x.202 Test_Server2 Ping Check OK : [ Response Time 0.00 ] : 2019-08-19 18:13:45

10.x.x.203 Test_Server3 Ping Check Fail : 2019-08-19 18:13:50

10.x.x.204 Test_Server5 Ping Check OK : [ Response Time 0.00 ] : 2019-08-19 18:13:51

10.x.x.205 Test_Server6 Ping Check OK : [ Response Time 0.00 ] : 2019-08-19 18:13:52

 

 

 

 

 

 

결과를 다양한 형태의 알림으로 연동하면 실시간 모니터링을 가능하다.

 

 

Python Telegram Interlink (파이썬 텔레그램 연동)

 

Python Slack Interlink (파이썬 Slack Chat 연동)