IT 관련/유틸리티

사이트 ping 모니터링

islet2 2025. 3. 17. 16:28

이 코드는 다음과 같은 기능을 제공합니다

1-3개의 사이트에 대해 지정된 시간 간격으로 ping을 보냅니다.
각 사이트의 IP 주소와 응답 시간을 표시합니다.
명령행 인수를 통해 사이트와 시간 간격을 지정할 수 있습니다.

python ping_monitor.py -s example.com google.com naver.com -i 30

-s 또는 --sites: ping을 보낼 사이트 목록 (1-3개)
-i 또는 --interval: ping 간격 (초 단위, 기본값: 60초)

출력 예시:

종료하려면 Ctrl+C를 누르세요.
------------------------------------------------------------
[2025-03-17 15:30:45] example.com (IP: 93.184.216.34) - 응답 성공: 125ms
[2025-03-17 15:30:46] google.com (IP: 142.250.207.110) - 응답 성공: 32ms
[2025-03-17 15:30:47] naver.com (IP: 223.130.195.200) - 응답 성공: 45ms
------------------------------------------------------------



PYTHON CODE

import subprocess
import time
import socket
import platform
import argparse
from datetime import datetime

def get_ip_address(hostname):
    """호스트 이름으로부터 IP 주소를 가져오는 함수"""
    try:
        return socket.gethostbyname(hostname)
    except socket.gaierror:
        return "IP 주소를 찾을 수 없음"

def ping_site(hostname):
    """지정된 호스트에 ping을 보내는 함수"""
    # 운영체제에 따라 ping 명령어 옵션 설정
    param = '-n' if platform.system().lower() == 'windows' else '-c'

    # ping 명령어 실행
    command = ['ping', param, '1', hostname]

    try:
        # 현재 시간 기록
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # IP 주소 가져오기
        ip_address = get_ip_address(hostname)

        # ping 명령어 실행 및 결과 획득
        result = subprocess.run(command, capture_output=True, text=True, timeout=5)

        # 성공 여부 확인
        if result.returncode == 0:
            if platform.system().lower() == 'windows':
                for line in result.stdout.splitlines():
                    if '시간' in line or 'time' in line.lower():
                        response_time = line.split('시간=')[-1].split('ms')[0].strip() if '시간=' in line else line.split('time=')[-1].split('ms')[0].strip()
                        return f"[{current_time}] {hostname} (IP: {ip_address}) - 응답 성공: {response_time}ms"
                return f"[{current_time}] {hostname} (IP: {ip_address}) - 응답 성공"
            else:
                for line in result.stdout.splitlines():
                    if 'time=' in line.lower():
                        response_time = line.split('time=')[-1].split(' ms')[0].strip()
                        return f"[{current_time}] {hostname} (IP: {ip_address}) - 응답 성공: {response_time}ms"
                return f"[{current_time}] {hostname} (IP: {ip_address}) - 응답 성공"
        else:
            return f"[{current_time}] {hostname} (IP: {ip_address}) - 응답 실패"
    except subprocess.TimeoutExpired:
        return f"[{current_time}] {hostname} (IP: {ip_address}) - 시간 초과"
    except Exception as e:
        return f"[{current_time}] {hostname} (IP: {ip_address}) - 오류 발생: {str(e)}"

def main():
    # 명령행 인자 파싱
    parser = argparse.ArgumentParser(description='지정된 사이트에 일정 간격으로 ping을 보내는 프로그램')
    parser.add_argument('-s', '--sites', nargs='+', required=True, help='ping을 보낼 사이트 목록 (1-3개)')
    parser.add_argument('-i', '--interval', type=int, default=60, help='ping 간격 (초 단위, 기본값: 60초)')
    args = parser.parse_args()

    # 사이트 수 확인
    if len(args.sites) < 1 or len(args.sites) > 3:
        print("사이트는 1개에서 3개까지만 지정할 수 있습니다.")
        return

    print(f"총 {len(args.sites)}개 사이트에 대해 {args.interval}초 간격으로 ping을 보냅니다.")
    print("종료하려면 Ctrl+C를 누르세요.")
    print("-" * 60)

    try:
        while True:
            for site in args.sites:
                result = ping_site(site)
                print(result)
            print("-" * 60)
            time.sleep(args.interval)
    except KeyboardInterrupt:
        print("\n프로그램을 종료합니다.")

if __name__ == "__main__":
    main()