Python에서 시스템 모니터링을 위한 psutil 라이브러리

1. 개요

psutil(Process and System Utilities)은 파이썬 기반 시스템 모니터링 및 프로세스 관리에 최적화된 라이브러리입니다. 운영체제 간 호환성과 다양한 하드웨어 정보 수집 기능을 통해 CPU, 메모리, 디스크, 네트워크 상태를 실시간으로 분석할 수 있습니다. 이 도구는 서버 모니터링, 성능 최적화, 자동화 스크립트 개발 등 다양한 분야에서 활용됩니다.

주요 기능:
  • 운영체제 중립성: 리눅스, 윈도우, macOS, FreeBSD 지원
  • 자원 상태 분석: CPU 사용률, 메모리 할당량, 디스크 사용량 등의 데이터 제공
  • 프로세스 제어: 실행 중인 프로세스의 생성/종료, 자식 프로세스 관리
  • 실시간 모니터링: 시스템 부하 추적 및 경고 기능
  • 네트워크 통신 추적: 포트 상태, 패킷 전송량 확인
  • 사용자 세션 관리: 로그인한 사용자 정보 조회
  • 고성능 구현: C 언어 기반 내부 구조로 효율성 확보

2. 설치 방법

pip install psutil

설치 후 버전 확인 예시:

import psutil
print(f"라이브러리 버전: {psutil.__version__}")
print(f"CPU 코어 수: {psutil.cpu_count()}")

3. 핵심 기능

1) CPU 상태 분석

import psutil
import time

# 전체 CPU 사용률 확인
total_cpu = psutil.cpu_percent(interval=1)
print(f"총 CPU 사용률: {total_cpu}%")

# 각 코어별 사용률 출력
for idx, usage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
    print(f"코어 {idx}: {usage}%")

# 주파수 정보 검색
freq_info = psutil.cpu_freq()
print(f"현재 주파수: {freq_info.current:.2f}MHz")

2) 메모리 상태 추적

mem_data = psutil.virtual_memory()
print(f"메모리 총량: {mem_data.total/(1024**3):.2f}GB")
print(f"사용 중 메모리: {mem_data.used/(1024**3):.2f}GB")
print(f"메모리 사용률: {mem_data.percent}%")

swap_data = psutil.swap_memory()
print(f"SWAP 공간: {swap_data.total/(1024**3):.2f}GB")
print(f"SWAP 사용률: {swap_data.percent}%")

3) 디스크 사용 현황

for partition in psutil.disk_partitions():
    try:
        usage = psutil.disk_usage(partition.mountpoint)
        print(f"디스크: {partition.device}")
        print(f"  총 용량: {usage.total/(1024**3):.2f}GB")
        print(f"  사용량: {usage.used/(1024**3):.2f}GB")
        print(f"  사용률: {usage.percent}%")
    except PermissionError:
        print("  접근 권한 없음")

4. 고급 기능

1) 프로세스 관리

current_proc = psutil.Process()
print(f"프로세스 ID: {current_proc.pid}")
print(f"프로세스 이름: {current_proc.name()}")
print(f"CPU 사용률: {current_proc.cpu_percent()}%")
print(f"메모리 소비: {current_proc.memory_info().rss/(1024**2):.2f}MB")

for proc in psutil.process_iter(['pid','name','cpu_percent','memory_percent']):
    if proc.info['cpu_percent'] > 10:
        print(f"PID: {proc.info['pid']}, 이름: {proc.info['name']}, "
              f"CPU: {proc.info['cpu_percent']}%, 메모리: {proc.info['memory_percent']:.2f}%")

2) 네트워크 모니터링

network_stats = psutil.net_io_counters(pernic=True)
for interface, stats in network_stats.items():
    print(f"인터페이스 {interface}:")
    print(f"  송신량: {stats.bytes_sent/(1024**2):.2f}MB")
    print(f"  수신량: {stats.bytes_recv/(1024**2):.2f}MB")

connections = psutil.net_connections()
for conn in connections[:5]:
    print(f"연결: {conn.laddr} → {conn.raddr}, 상태: {conn.status}")

5. 실무 적용 사례

1) 시스템 모니터링 스크립트

import psutil
import time
from datetime import datetime

def monitor_system():
    CPU_LIMIT = 80
    MEM_LIMIT = 85
    DISK_LIMIT = 90
    
    cpu_usage = psutil.cpu_percent(interval=1)
    mem_usage = psutil.virtual_memory().percent
    disk_usage = psutil.disk_usage('/').percent
    
    alerts = []
    if cpu_usage > CPU_LIMIT:
        alerts.append(f"CPU 과부하: {cpu_usage}%")
    if mem_usage > MEM_LIMIT:
        alerts.append(f"메모리 과다 사용: {mem_usage}%")
    if disk_usage > DISK_LIMIT:
        alerts.append(f"디스크 공간 부족: {disk_usage}%")
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] CPU: {cpu_usage}%, 메모리: {mem_usage}%, 디스크: {disk_usage}%"
    print(log_entry)
    
    if alerts:
        print("경고:", "; ".join(alerts))
    
    return alerts

while True:
    monitor_system()
    time.sleep(60)

2) 프로세스 관리 도구

def track_process(target_name):
    for proc in psutil.process_iter(['pid','name','cpu_percent','memory_info']):
        if target_name.lower() in proc.info['name'].lower():
            mem_mb = proc.info['memory_info'].rss / (1024**2)
            print(f"프로세스: {proc.info['name']}")
            print(f"PID: {proc.info['pid']}")
            print(f"CPU 사용: {proc.info['cpu_percent']}%")
            print(f"메모리: {mem_mb:.2f}MB")
            
            if mem_mb > 1024:
                print("경고: 메모리 사용량 초과!")

track_process("python")

태그: psutil 시스템 모니터링 프로세스 관리 Python 라이브러리 네트워크 모니터링

7월 9일 01:18에 게시됨