[파이썬] 파이썬을 활용한 리눅스 서버 이상 징후 탐지

리눅스 서버는 많은 사용자들이 접속하는 중요한 환경이기 때문에 이상한 동작이나 해킹 시도 등의 이상 징후를 신속하게 감지할 필요가 있습니다. 이러한 이상 징후를 탐지하기 위해 파이썬을 활용할 수 있으며, 다양한 방법을 사용하여 실시간으로 서버 상태를 모니터링 할 수 있습니다.

로그 감시

서버의 로그 파일을 감시하는 것은 이상 징후를 신속하게 감지할 수 있는 중요한 방법입니다. 파이썬의 tail 명령어 등을 활용하여 실시간으로 로그 파일을 읽고, 특정 패턴을 탐지할 수 있습니다. 예를 들어, 로그 파일에서 Authentication failure와 같은 특정 메시지를 감지하면 해당 이벤트를 처리하는 로직을 실행할 수 있습니다.

import subprocess

def monitor_log_file():
    log_file = '/var/log/auth.log'
    tail_cmd = f'tail -f {log_file}'
    process = subprocess.Popen(tail_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while True:
        line = process.stdout.readline()
        if line:
            if 'Authentication failure' in line.decode():
                # 이상 징후 탐지 로직 실행
                handle_authentication_failure()

자원 사용량 모니터링

서버의 자원 사용량을 모니터링하는 것은 서버가 과부하 상태에 있는지를 감지하는 중요한 방법입니다. 파이썬의 psutil 모듈을 사용하여 CPU, 메모리, 디스크 사용량 등을 실시간으로 모니터링할 수 있습니다. 이를 기반으로 서버의 이상 징후를 탐지하고, 적절한 조치를 취할 수 있습니다.

import psutil

def monitor_resource_usage():
    while True:
        cpu_percent = psutil.cpu_percent(interval=1)
        memory_percent = psutil.virtual_memory().percent

        if cpu_percent > 80:
            # CPU 과부하 상태, 이상 징후 탐지 로직 실행
            handle_cpu_overload()
        
        if memory_percent > 90:
            # 메모리 과부하 상태, 이상 징후 탐지 로직 실행
            handle_memory_overload()

알림 시스템 통합

리눅스 서버 이상 징후 탐지 시스템은 즉각적인 대응이 필요한 경우에도 신속하게 알림을 전송할 수 있어야 합니다. 파이썬을 사용하여 다양한 알림 시스템(Slack, 이메일 등)과 통합하여 서버 이상 징후를 탐지하고 즉시 알림을 받을 수 있습니다. 예를 들어, slackclient 패키지를 사용하여 Slack으로 알림을 보내는 기능을 구현할 수 있습니다.

from slack import WebClient

def send_slack_message(message):
    slack_token = 'your-slack-token'
    slack_channel = 'your-channel'
    client = WebClient(token=slack_token)
    client.chat_postMessage(channel=slack_channel, text=message)

서버 이상 징후를 탐지할 때, 해당 이벤트에 대한 알림을 Slack으로 전송하는 로직을 추가할 수 있습니다.

def handle_authentication_failure():
    message = '[Alert] Authentication failure detected on server'
    send_slack_message(message)
    # 추가로 대응해야 할 로직 실행

def handle_cpu_overload():
    message = '[Alert] CPU overload detected on server'
    send_slack_message(message)
    # 추가로 대응해야 할 로직 실행

def handle_memory_overload():
    message = '[Alert] Memory overload detected on server'
    send_slack_message(message)
    # 추가로 대응해야 할 로직 실행

파이썬을 활용한 리눅스 서버 이상 징후 탐지 시스템은 자신의 운영 환경에 맞게 세부적인 기능들을 추가할 수 있으며, 실시간으로 서버 상태를 모니터링하고 이상 징후를 탐지하여 신속하게 대응할 수 있습니다.