Profile picture

[Python] 슬랙(Slack) 봇을 이용하여 웹 서버 로그 알림 보내기

JaehyoJJAng2023년 08월 16일

새 채널 생성하기

image

슬랙에 incomming WebHooks 앱 추가하기

image

앱 설치할 채널 선택

image

URL 저장하기

image

슬랙에 메시지 전송하기

from typing import Dict,Union,List
import requests as rq
import environ
import json
import sys
import random
import paramiko

# ======= Type Hint =======
SLACK_DATA = Dict[str,Union[str,List[Dict[str,Union[str,List[Dict[str,str]]]]]]]
# =======           =======

def get_environment(file)-> environ.Env:
    """ 환경변수 관리 """
    env : environ.Env = environ.Env(DEBUG=(bool,False))
    env.read_env(file)
    return env        

class Slack:    
    def __init__(self) -> None:
        self._web_hook_url : str = get_environment(file='.secret.env')('WEB_HOOK')

    def send_msg(self,title:str,msg:str)-> None:
        slack_data : SLACK_DATA = {
            "username": "NotificationBot", # 보내는 사람 이름
            "icon_emoji": ":satellite",
            "attachments": [
                {
                    "color": "#9733EE",
                    "fields": [
                        {
                            "title": title,
                            "value": msg,
                            "short": "false",
                        }
                    ]
                }
            ]
        }
        
        # Set Headers's Byte
        byte_length : str = str(sys.getsizeof(slack_data))
        
        # Set Headers
        headers : Dict[str,str] = {"Content-Type": "application/json","Content-Length": byte_length}
        
        response = rq.post(self._web_hook_url,data=json.dumps(slack_data),headers=headers)
        
        if response.status_code != 200:
            error = {"Error" : {"code" : response.status_code, "text": response.text}}
            raise Exception(error)

class Monitoring(Slack):
    def __init__(self) -> None:
        super().__init__()
        # Get Server IP
        self._ip : str = get_environment(file='.ip.env')('IP') 
        
        # Get Server PASS
        self._pass : str = get_environment(file='.ip.env')('PASSWORD') 
        
        # Set SSHClient Instance
        self.ssh : paramiko.SSHClient = paramiko.SSHClient() 
    
    def connect_server(self)-> None:
        """ 서버 접속 """
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(hostname=self._ip,port='22',username='ncloud',password=self._pass)
    
    def execute_command(self,command:str)-> None:
        """ 명령어 실행 """
        stdin,stdout,stderr = self.ssh.exec_command(command=command)
        stdout : str = ''.join(stdout.readlines()).strip()
        
        # 메시지 보내기
        self.send_msg(title='result',msg=stdout)
    
def main()-> None:
    # Create Monitoring Instance
    monitor : Monitoring = Monitoring()
    
    # Connect Server
    monitor.connect_server()
    
    # Set command
    command : str = """
    cd ~/git/API-Server-Practice/04_Message_States_Server\ REST\ API; docker-compose logs jazzmessages | awk '{print $3}' | grep -v "[A-Z*]" """.strip()
    
    # Execute Command
    monitor.execute_command(command=command) 
    
if __name__ == '__main__':
    main()

메시지 전송 결과

image


Loading script...