[Python]2023.08.10

망구씨·2023년 8월 10일
0

Python

목록 보기
7/7
post-thumbnail

복습

           수업내용 -------------------------->  dba 작업 편하게 하기 

1장. 파이썬 설치
2장. 파이썬 변수
3장. if 문과 loop문 ------------------------> dba 자동화 스크립트
4장. 문자열 함수들 1. 테이블 스페이스 사용량 조회
5장. 리스트 함수들 2. 락 waiting 세션 조회
6장. 딕셔너리 함수들 3. Oracle db와 파이썬 연동
7장. 함수 생성 4. alert log file 분석
8장. 예외처리 5. 테이블 정의서 엑셀 자동생성
9장. 클래스
10장. 자동화
자동화 스크립트를 코드 추가하기 편하도록 정리

       오라클  ---------------------------->  파이썬 
         ↓                                                     ↓
      SQL 과 PL/SQL                                1. 자동화 스크립트 
                                                            2. 시각화
                                                            3.  slack 메신져 프로그램에
                                                                db 상태 알림  

인스턴스 변수와 클래스 변수

클래스를 사용하는 이유?
ex) 어제만든 총 클래스 내에 총충전함수, 총을쏘는함수가 서로 밀접한 연관이 있는 경우 클래스 내에 함수로 구성해야한다. 총알을 충전한만큼 쏴야하므로 클래스내에 함수로 구성해야한다.

✔️ 클래스를 구성하는 요소 2가지
1. 변수
2. 함수
✔️ 클래스 내에서 사용할 수 있는 변수 2가지
1. 인스턴스(instance) 변수 : 이름 그대로 즉시 변경할 수 있는 변수
2. 클래스(class) 변수 : 클래스(설계도)로 객체(제품)을 생성한 이후에는 즉시 변경 불가능

__init__ 생성자 함수. 이름 변경 못함 card1 = Card() 만들면 바로 즉시 ! 실행됨.

문법예제1

# 인스턴스 변수 설명 예제
class  Card():                    # 카드 설계도 만듭니다.
    def  __init__(self):         # 설계도를 가지고  객체를 생성할때 바로 작동되는 함수
        self.money = 0          #  money 라는 변수에 값을 0 을 넣었습니다.
 
        self.raise_amount = 1.1   # 인스턴스 변수(멤버)
 
        print('카드가 발급 되었습니다. ', self.money, '원이 충전되어 있습니다.' )
 
    def  charge( self,  num2 ):                           # 돈을 충전하는 함수입니다.
        num = int( num2 * self.raise_amount)       # 적립율만큼 곱해서 충전합니다.
        print ( num, '원이 충전 되었습니다.')
        self.money = self.money +num                # 돈을 num 숫자만큼 장전합니다.
        print('현재 카드의 충전금액은 ', self.money, '입니다.')
 
    def  consume( self, num ):                          # card 를 쓰는 함수입니다.

        self.money =  self.money - num    # 가지고 있는 돈에서 사용할 돈만큼 차감해도

        if  self.money >= 0:                                # 돈이 있다면
            print( num, '원이 사용되었습니다.' )     # 돈을 씁니다.
       
        elif  self.money < 0 :                          # 돈이 없다면
            print('잔액이 없습니다.')                   # 없다는 메세지를 출력합니다.
                                                      
        print(  self.money, '원 남았습니다.')
 -------------------------------------------------------------------------
  card1 = Card() # 카드가 발급 되었습니다.  0 원이 충전되어 있습니다.
  card1.charge(10000) # 11000 원이 충전 되었습니다. 현재 카드의 충전금액은  11000 입니다.
  card1.consume(5000) # 5000 원이 사용되었습니다. 83000 원 남았습니다.        

인스턴스 변수 설명 예제4 100000 원을 충전하려고 합니다. 20%로 적립합니다. (지금은 1.1)

card2.raise_amount= 1.2 # 인스턴스 변수라서 즉시 변경이 됩니다.
card2.charge(100000)


위 이미지는 인스턴스 변수 만드는 방법.
✅ 카드 발급 이후에도 얼마든지 인스턴스 변수의 값을 변경할 수 있습니다.

문법예제2. card2 카드를 발급하세요 !

card2 = Card()

문법예제3. card2 카드에 10000원을 충전합니다.

card2.charge(10000)

✅ 적립율이 충전금액의 10% 이므로 11000 원이 충전되었습니다.

문법예제4. 100000원을 충전을 하려고 합니다. 20% 로 적립합니다.

card2.raise_amount = 1.2    #  인스턴스 변수라 즉시 변경이 됩니다. 
card2.charge(100000)

문법예제5. 이번에는 클래스 변수로 raise_amount 변수를 구성해서 Card 설계도를 다시 생성합니다.

class  Card():                    # 카드 설계도 만듭니다.

    raise_amount = 1.1   # 클래스 변수

    def  __init__(self):         # 설계도를 가지고  객체를 생성할때 바로 작동되는 함수
        self.money = 0          #  money 라는 변수에 값을 0 을 넣었습니다.
 
        print('카드가 진짜로 발급 되었습니다. ', self.money, '원이 충전되어 있습니다.' )
 
    def  charge( self,  num2 ):                           # 돈을 충전하는 함수입니다.
        num = int( num2 * Card.raise_amount)       # 적립율만큼 곱해서 충전합니다.
        print ( num, '원이 충전 되었습니다.')
        self.money = self.money +num                # 돈을 num 숫자만큼 장전합니다.
        print('현재 카드의 충전금액은 ', self.money, '입니다.')
 
    def  consume( self, num ):                          # card 를 쓰는 함수입니다.

        self.money =  self.money - num # 가지고 있는 돈에서 사용할 돈만큼 차감해도

        if  self.money >= 0:                                # 돈이 있다면
            print( num, '원이 사용되었습니다.' )     # 돈을 씁니다.
       
        elif  self.money < 0 :                          # 돈이 없다면
            print('잔액이 없습니다.')                   # 없다는 메세지를 출력합니다.
                                                      
        print(  self.money, '원 남았습니다.')

card3.charge(10000)

card3.raise_amount=1.3
card3.charge(10000)

✅ 함수 밖으로 raise_amount를 빼고, 적립할 때 charge함수안에 num = int( num2 * self.raise_amount)num = int( num2 * 클래스명.raise_amount)로 바꿔준다
✅ 인스턴스 변수는 즉시 변경할 수 있지만 클래스 변수는 변경할 수 없습니다.

문제 111. 총 클래스를 수정해서 총 클래스로 총을 생산하면 총이 만들어졌습니다. 라는 메세지가 출력되게 설계도를 수정하기

class Gun(): # class이름은 카멜케이스로 앞글자 대문자 !
    def  __init__(self):  
        print('총이 만들어졌습니다.' )

    def charge(self,num):
        self.bullet = num
        print(self.bullet, '발이 장전되었습니다.')
      
    def shoot(self,num):
        for i in range(1, num + 1):
            if self.bullet > 0: # 충전한 총알이 있다면 
                print('탕!')    # 탕탕!
                self.bullet = self.bullet -1 # 총알 하나 깎고
            elif  self.bullet == 0: # 총알이 0개면(다썼으면)
                print('총알이 없습니다!')
                break
-----------------------------------
 gun1 = Gun()

문제 112. 총알을 충전할 떄 10발 충전하면 11발 충전될 수 있도록 기존 충전 총알에 10% 더 충전될 수 있도록 총 클래스를 생성하는데, 적립율 변수를 클래스변수로 설정하기.

class Gun(): # class이름은 카멜케이스로 앞글자 대문자 !
    raise_amount = 1.1

    def  __init__(self):  
        self.bullet = 0
        print('총이 만들어졌습니다.' )

    def charge(self,num):
        num = int(num * Gun.raise_amount)
        print(num, '발이 장전되었습니다.')
        self.bullet = self.bullet + num
        print('현재 충전된 총알은 ', self.bullet, '개 입니다.')

    def shoot(self,num):
        for i in range(1, num + 1):
            if self.bullet > 0: # 충전한 총알이 있다면 
                print('탕!')    # 탕탕!
                self.bullet = self.bullet -1 # 총알 하나 깎고
            elif  self.bullet == 0: # 총알이 0개면(다썼으면)
                print('총알이 없습니다!')
                break
-------------------------------------------------------------------------------------
 gun1 = Gun(20)

상속

💡 클래스로 코딩했을 때 가장 큰 장점이 상속이다.

                           팀장님(카드 기본 기능)
                           
             팀원1                 팀원2                팀원3   
         (영화할인카드)         (주유할인카드)       (편의점 할인 카드)

카드 기본기능을 상속받고, 나는 영화할인 카드만, 주유할인카드만, 편의점 할인카드만 만들면 된다. 
만약 상속이 안되었었다면 팀원 1이만든 기본기능, 2가만든 기본기능이 모두 다 달랐을 것.

문법예제1. 기존에 만들었던 카드 클래스의 기본 기능을 다 물려받고 영화카드 클래스를 생성하시오!

class Movie_Card(Card): # 괄호 안에 부모클래스명을 넣어주면 된다.
    pass

✅ 아무것도 코딩하지 않았지만 mcard1=Movie_Card()로 카드를 발급하면 아래 이미지와 같이 부모카드처럼 발급 메세지가 나온다. 충전, 사용도 마찬가지!

문법예제2. oil_card 설계도를 생성하고, oil_card를 다음과 같이 발급하시오

class Oil_Card(Card): 
    pass

문법예제3. 영화 카드 클래스를 생성하는데, 카드 기본 기능은 팀장님이 만든 카드클래스를 ㅅ상속받고, 나는 영화관에서 영화할인이 30%가 되도록 클래스 생성하기

  • 카드 기본기능을 물려받고, consume함수를는 오버라이딩한다. -> 덮어쓴다.
class  Movie_Card(Card):
    def   consume( self, num, place):
        if   place=='영화관':
            num = 0.7 * num
            self.money = self.money - num

            if  self.money >= 0:
                print( place ,' 에서 ', num, '원이 사용되었습니다.')
            elif  self.money < 0:
                print('잔액이 없습니다')

        else:
            self.money = self.money - num

            if  self.money >= 0:
                print( place ,' 에서 ', num, '원이 사용되었습니다.')
            elif  self.money < 0:
                print('잔액이 없습니다')

문제 113. 위 영화할인 카드 클래스를 다시 생성하는데 이번에는 다음과 같이 영화할인 카드를 발급받으면 영화할인카드가 발급되었습니다 라고 메세지 출력하게 하시오

class  Movie_Card(Card):

    def  __init__(self):  
    print('영화할인 카드가 발급되었습니다.' )
    
    def   consume( self, num, place):
        if   place=='영화관':
            num = 0.7 * num
            self.money = self.money - num

            if  self.money >= 0:
                print( place ,' 에서 ', num, '원이 사용되었습니다.')
            elif  self.money < 0:
                print('잔액이 없습니다')

        else:
            self.money = self.money - num

            if  self.money >= 0:
                print( place ,' 에서 ', num, '원이 사용되었습니다.')
            elif  self.money < 0:
                print('잔액이 없습니다')
------------------------------------------------------

mcard2 = Movie_Card()         

테이블 스페이스 사용량 시각화

             Orale ------------------> 파이썬
         sql과 plsql          
         시각화    
# 1. 테이블 스페이스의 공간 사용량을 조회하는 프로시저 생성
# 2. 프로시저를 파이썬에서 연동해서 호출
# 3. 데이터 시각화 함수 생성
# 4. DBA 자동화 스크립트에 함수 추가

1. 테이블 스페이스의 공간 사용량을 조회하는 프로시저 생성

create or replace procedure get_ts_data
 ( p_x out sys_refcursor )
is
  sql_query varchar2(4000):
begin 
  sql_query := 'select  t.tablespace_name,
                        round(((t.total_size - f.free_size) / t.total_size),2) * 100 usedspace
                   from (select tablespace_name, sum(bytes)/1024/1024 total_size
                           from dba_data_files
                           group by tablespace_name) t,
                           (select  tablespace_name, sum(bytes)/1024/1024 free_size
                                       from dba_free_space
                                       group by tablespace_name) f
                   where t.tablespace_name = f.tablespace_name(+)';
  
  open p_x for sql_query;
end;
/

2. 프로시저를 파이썬에서 연동해서 호출

import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
db = cx_Oracle.connect('c##scott','tiger', dsn)
cursor  = db.cursor()

# v_result =  cursor.var( cx_Oracle.STRING ) 데이터를 하나만 받을 때 
v_result =  cursor.var( cx_Oracle.CURSOR ) 
cursor.callproc( 'get_ts_data',  [v_result]   )

result = v_result.getvalue()

a = [] # 빈 리스트 만들고
for i in result :
    a.append(i[0],i[1]) #a에 append시킨다. i의 0, 1번째 요소들로 구성
print(a)
# [['SYSTEM', 63], ['SYSAUX', 92], ['UNDOTBS1', 3], ['USERS', 95]]

# cursor.close()
# db.close()

위 결과를 판다스 데이터 프레임으로 구성

import pandas as pd

df = pd.Data.Frame(a, columns = ['tablespace_name','usedspace'])
df

3. 데이터 시각화 함수 생성

import matplotlib.pyplot as plt

plt.figure(figsize=(8,6)) # 그래프 사이즈 (가로 8, 세로6)

df['freespace'] = 100 - df['usedspace'] # 컬럼추가
plt.bar(df['tablespace_name'], df['usedspace'], color = 'green', label = 'Used space') 
plt.bar(df['tablespace_name'], df['freespace'], bottom = df['usedspace'], color = 'orange', label = 'freespace')

plt.title("Tablespace Used Space") # 그래프 제목
plt.xlabel("Tablespace Name")
plt.ylabel("Space(%)")
plt.legend()
plt.show()


✅ 라벨이름이 레전드에 달리는 것이다.

위 스크립트를 함수로 생성하기

def ts_space_bar():
    
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    
    v_result =  cursor.var( cx_Oracle.CURSOR )
    cursor.callproc( 'get_ts_data',  [v_result]   )
    
    result = v_result.getvalue()
    
    a  = [ ]
    for   i   in   result:
        a.append( [ i[0], i[1] ] )
    
        # 위의 결과를 판다스 데이터 프레임으로 구성 
    
    import    pandas    as    pd
    
    df =  pd.DataFrame(  a ,   columns= ['tablespace_name', 'usedspace' ] )
    
    
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(8,6)) # 그래프 사이즈 (가로 8, 세로6)
    
    df['freespace'] = 100 - df['usedspace'] # 컬럼추가
    plt.bar(df['tablespace_name'], df['usedspace'], color = 'green', label = 'Used space') 
    plt.bar(df['tablespace_name'], df['freespace'], bottom = df['usedspace'], color = 'orange', label = 'freespace')
    
    plt.title("Tablespace Used Space") # 그래프 제목
    plt.xlabel("Tablespace Name")
    plt.ylabel("Space(%)")
    plt.legend()
    plt.xticks(rotation=45)
    plt.show()

-------------------------------------------------------------------
ts_space_bar()

4. 자동화 스크립트에 함수 추가

# 1. 오라클 연동 함수

def   oracle_table(table_name):
    import cx_Oracle
    import pandas as pd

    dsn = cx_Oracle.makedsn('localhost', 1521, 'xe')
    db = cx_Oracle.connect('c##scott', 'tiger', dsn)
    cursor = db.cursor()   
    
    query = f"SELECT * FROM {table_name}"
    
    cursor.execute(query )  

    row = cursor.fetchall()   

    colnames = cursor.description

    col = [ ] 
    for  i   in   colnames:
        col.append( i[0].lower()  )

    df = pd.DataFrame(row , columns = col )
    return ( df )
    

#2. dba 자동화 스크립트


def  find_lock():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()

    v_result =  cursor.var( cx_Oracle.STRING )
    cursor.callproc( 'lock_find',  [v_result]   )

    result = v_result.getvalue()
    return  str(result) + '개의 락 waiting 세션이 발견되었습니다.'


#3. 테이블 스페이스 사용량 조회 함수

def ts_space_bar():
    
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    
    v_result =  cursor.var( cx_Oracle.CURSOR )
    cursor.callproc( 'get_ts_data',  [v_result]   )
    
    result = v_result.getvalue()
    
    a  = [ ]
    for   i   in   result:
        a.append( [ i[0], i[1] ] )
    
        # 위의 결과를 판다스 데이터 프레임으로 구성 
    
    import    pandas    as    pd
    
    df =  pd.DataFrame(  a ,   columns= ['tablespace_name', 'usedspace' ] )
    
    
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(8,6)) # 그래프 사이즈 (가로 8, 세로6)
    
    df['freespace'] = 100 - df['usedspace'] # 컬럼추가
    plt.bar(df['tablespace_name'], df['usedspace'], color = 'green', label = 'Used space') 
    plt.bar(df['tablespace_name'], df['freespace'], bottom = df['usedspace'], color = 'orange', label = 'freespace')
    
    plt.title("Tablespace Used Space") # 그래프 제목
    plt.xlabel("Tablespace Name")
    plt.ylabel("Space(%)")
    plt.legend()
    plt.xticks(rotation=45)
    plt.show()


def  easy_dba():

    while   True:
        print( """ ===  dba 작업을 편하게 수행하기 위한 스크립트 총모음 ====

            0.  프로그램을 종료하려면 0번을 누르세요.
            1.  테이블 스페이스  사용량을 확인하려면 1번을 누르세요
            2.  현재 데이터베이스 락(lock) 발생했는지 확인하려면 2번을 누르세요
            3.  오라클와 연동하게 싶으면 3번을 누르세요
            4.  alert log file 을 분석하고 싶다면 4번을 누르세요

            """)

        num =  int( input('원하는 번호를 입력하세요 ~' )  )
        
        if num == 0:
            print('종료되었습니다.')
            break

        elif  num == 1:
            
            ts_space_bar()
            print('그래프를 출력했습니다.')
            break
            
        elif  num == 2:
            message = find_lock()
            print(message) 
            break
            
        elif  num ==3:
            import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
            import  pandas  as  pd
            dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
            db = cx_Oracle.connect('c##scott','tiger', dsn)
            cursor  = db.cursor()
            cursor.execute(""" select  * from  emp """)
            row = cursor.fetchall()
            colname = cursor.description
            col=[]
            for  i   in   colname:
                col.append( i[0].lower() )

            emp = pd.DataFrame (list(row), columns=col)

            print(' 잘 연동되었습니다')
            break

        elif num == 4:
            jobs = open("C:\\app\\ITWILL\\product\\18.0.0\\diag\\rdbms\\xe\\xe\\trace\\alert_xe.log",  encoding='cp949', errors='ignore')

            data = jobs.read()
            data2= data.split()
            k = [  ]                             
            for  i  in  data2:               
                if  'ora-' in  i.lower():     
                    k.append(i)       
                          
            import   pandas   as   pd       

            df = pd.DataFrame(  k,  columns=['col1'] ) 
            from   pandasql  import   sqldf    
         

            q = """  select  col1, count(*)
                            from  df
                            group by  col1
                            order by 2 desc;   """

            print(sqldf(q) )
            break

문제 114. 자동화 스크립트 3번 스크립트를 함수로 만들어서 코드를 작성하기
(함수이름: connect_oracle)

#4. 오라클 연동 함수
def connect_oracle():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    import  pandas  as  pd
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    cursor.execute(""" select  * from  emp """)
    row = cursor.fetchall()
    colname = cursor.description
    col=[]
    for  i   in   colname:
        col.append( i[0].lower() )
    
    emp = pd.DataFrame (list(row), columns=col)
    
    print(' 잘 연동되었습니다')

문제 115. 자동화 스크립트의 4번 스크립트를 함수로 만들어서 코드 작성하기
(함수이름: alert_analyst)

# 1. 오라클 연동 함수

def   oracle_table(table_name):
    import cx_Oracle
    import pandas as pd

    dsn = cx_Oracle.makedsn('localhost', 1521, 'xe')
    db = cx_Oracle.connect('c##scott', 'tiger', dsn)
    cursor = db.cursor()   
    
    query = f"SELECT * FROM {table_name}"
    
    cursor.execute(query )  

    row = cursor.fetchall()   

    colnames = cursor.description

    col = [ ] 
    for  i   in   colnames:
        col.append( i[0].lower()  )

    df = pd.DataFrame(row , columns = col )
    return ( df )



#2. dba 자동화 스크립트


def  find_lock():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()

    v_result =  cursor.var( cx_Oracle.STRING )
    cursor.callproc( 'lock_find',  [v_result]   )

    result = v_result.getvalue()
    cursor.close()
    db.close()
    return  str(result) + '개의 락 waiting 세션이 발견되었습니다.'


# 3. 테이블 스페이스 사용량 조회 함수

def ts_space_bar():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()

    v_result =  cursor.var( cx_Oracle.CURSOR )
    cursor.callproc( 'get_ts_data',  [v_result]   )

    result = v_result.getvalue()

    a  = [ ]
    for   i   in   result:
        a.append( [ i[0], i[1] ] )

        # 위의 결과를 판다스 데이터 프레임으로 구성 

    import    pandas    as    pd

    df =  pd.DataFrame(  a ,   columns= ['tablespace_name', 'usedspace' ] )


    import   matplotlib.pyplot   as    plt 

    plt.figure( figsize=(10, 6)  )   #  그래프 사이즈 (가로 10, 세로 6) 

    df['freespace'] = 100 - df['usedspace']  # freespace 컬럼 추가

    plt.bar(  df['tablespace_name'],  df['usedspace'],  color='blue' , label='used space')  
    plt.bar(  df['tablespace_name'],  df['freespace'], bottom=df['usedspace'],  color='orange', label='freespace')

    plt.title("Tablespace Used Space")  # 그래프 제목 
    plt.xlabel("Tablespace Name")  # x 축 제목
    plt.ylabel("Space (%) ")            # y 축 제목
    plt.legend()
    plt.xticks(rotation=45)
    plt.show()

#4. 오라클 연동 함수

def connect_oracle():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    import  pandas  as  pd
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    cursor.execute(""" select  * from  emp """)
    row = cursor.fetchall()
    colname = cursor.description
    col=[]
    for  i   in   colname:
        col.append( i[0].lower() )

    emp = pd.DataFrame (list(row), columns=col)

    print(' 잘 연동되었습니다')
    
#5. alert logfile 분석

def alert_analyst():
    jobs = open("C:\\app\\ITWILL\\product\\18.0.0\\diag\\rdbms\\xe\\xe\\trace\\alert_xe.log",  encoding='cp949', errors='ignore')

    data = jobs.read()
    data2= data.split()
    k = [  ]                             
    for  i  in  data2:               
        if  'ora-' in  i.lower():     
            k.append(i)       
                  
    import   pandas   as   pd       

    df = pd.DataFrame(  k,  columns=['col1'] ) 
    from   pandasql  import   sqldf    


    q = """  select  col1, count(*)
                    from  df
                    group by  col1
                    order by 2 desc;   """

    print(sqldf(q) )
    



def  easy_dba():

    while   True:
        print( """ ===  dba 작업을 편하게 수행하기 위한 스크립트 총모음 ====

            0.  프로그램을 종료하려면 0번을 누르세요.
            1.  테이블 스페이스  사용량을 확인하려면 1번을 누르세요
            2.  현재 데이터베이스 락(lock) 발생했는지 확인하려면 2번을 누르세요
            3.  오라클와 연동하게 싶으면 3번을 누르세요
            4.  alert log file 을 분석하고 싶다면 4번을 누르세요

            """)

        num =  int( input('원하는 번호를 입력하세요 ~' )  )
        
        if num == 0:
            break

        elif  num == 1:
            
           ts_space_bar()
           break
            
        elif  num == 2:
            message = find_lock()
            print(message) 
            break
            
        elif  num ==3:
            connect_oracle() 
            break

        elif num == 4:
            alert_analyst()
            break

슬랙, 오라클, 파이썬 연동하기

  • 데이터 베이스에 어떤 문제가 생겼을 때 슬랙으로 메세지가 오게 하는 방법

"
데이터베이스에 어떤 문제가 생겼을때 slack 으로 메세지가 오게 하는 방법"

  1. slack 에 들어가서 회원가입을 하고 프로그램을 다운로드 받습니다.

  2. slack 의 API 토큰을 구합니다.

    API 토큰을 구하는 방법은 다음과 같습니다. Slack에서는 봇 생성 및 관리를 위한 토큰을 생성할 수 있도록 API 토큰을 제공합니다.

  3. Slack 워크스페이스에 로그인하고 Slack API 페이지로 이동합니다.

  4. 페이지 상단에 있는 "Your Apps" 메뉴를 클릭합니다.

  5. "Create an App" 버튼을 클릭하여 새로운 앱을 생성합니다.

  6. 앱의 이름과 워크스페이스를 선택한 후 "Create App"을 클릭합니다.

  7. 생성된 앱의 설정 페이지로 이동한 후, 왼쪽 메뉴에서 "Basic Information"을 선택합니다.

  8. 페이지 상단에 있는 "Add features and functionality" 섹션에서 "Permissions"을 선택합니다.

  9. "Scopes" 섹션에서 원하는 권한을 추가합니다. 메시지를 보낼 수 있는 권한인 chat:write를 추가해야 합니다.

  10. 권한을 추가한 후 페이지 상단에 있는 "Install to Workspace" 섹션으로 이동합니다.

  11. "Install App to Workspace" 버튼을 클릭하여 앱을 워크스페이스에 설치합니다.

  12. 설치 후, 페이지에 "OAuth Tokens for Your Workspace" 섹션이 나타날 것입니다.
    여기에서 "Bot User OAuth Token"을 찾아 복사합니다. 이 토큰이 다른 봇의 API 토큰입니다.

슬랙과 파이썬 연동하기 전체코드

import requests

# 슬랙 API 토큰
slack_token = '토큰 번호를 여기에 붙이세요'

# 메시지를 보낼 채널 이름
channel = 'test'

# 보낼 메시지 내용
message = '안녕하세요, 파이썬과 슬랙 연동 테스트 중입니다!'

# 슬랙 API 엔드포인트 URL
url = f'https://slack.com/api/chat.postMessage'

# API 호출을 위한 헤더 설정
headers = {
    'Authorization': f'Bearer {slack_token}',
    'Content-Type': 'application/json'
}

# API 호출 데이터
data = {
    'channel': channel,
    'text': message
}

# 슬랙 API 호출
response = requests.post(url, headers=headers, json=data)

# API 응답 확인
if response.status_code == 200:
    print('메시지가 성공적으로 전송되었습니다.')
else:
    print('메시지 전송에 실패하였습니다.')
    print('응답:', response.text)

import requests 는 파이썬과 다른 서버와 통신할 때 사용하는 모듈이다.

문제 116. 위 코드를 slack_bot이라는 함수로 생성하기

def slack_bot():
  import requests

  # 슬랙 API 토큰
  slack_token = '토큰 번호를 여기에 붙이세요'

  # 메시지를 보낼 채널 이름
  channel = 'test'

  # 보낼 메시지 내용
  message = '안녕하세요, 파이썬과 슬랙 연동 테스트 중입니다!'

  # 슬랙 API 엔드포인트 URL
  url = f'https://slack.com/api/chat.postMessage'

  # API 호출을 위한 헤더 설정
  headers = {
      'Authorization': f'Bearer {slack_token}',
      'Content-Type': 'application/json'
  }

  # API 호출 데이터
  data = {
      'channel': channel,
      'text': message
  }

  # 슬랙 API 호출
  response = requests.post(url, headers=headers, json=data)

  # API 응답 확인
  if response.status_code == 200:
      print('메시지가 성공적으로 전송되었습니다.')
  else:
      print('메시지 전송에 실패하였습니다.')
      print('응답:', response.text)

문제 117. 데이터베이스에 lock이 발생하면, true를 return하는 함수 생성

def lock_is_trigger():
    message = find_lock()
    if int(message[0]) >= 1:
        return True
        
lock_is_trigger()        

문제 118.무한 루프를 돌려서 락이 발생하면 슬랙에

import time 
while True :
    if lock_is_trigger() : # 만약 lock_is_trigger()가 True를 리턴하면
        slack_bot() # slack_bot() 함수를 실행해라.
    time.sleep(5) # 5초마다 락 상태 확인하려고 5초동안 멈춘다.    
  1. find_lock()
  2. slack_bot()
  3. lock_is_trigger()
# 1. 오라클 연동 함수

def   oracle_table(table_name):
    import cx_Oracle
    import pandas as pd

    dsn = cx_Oracle.makedsn('localhost', 1521, 'xe')
    db = cx_Oracle.connect('c##scott', 'tiger', dsn)
    cursor = db.cursor()   
    
    query = f"SELECT * FROM {table_name}"
    
    cursor.execute(query )  

    row = cursor.fetchall()   

    colnames = cursor.description

    col = [ ] 
    for  i   in   colnames:
        col.append( i[0].lower()  )

    df = pd.DataFrame(row , columns = col )
    return ( df )



#2. dba 자동화 스크립트


def  find_lock():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()

    v_result =  cursor.var( cx_Oracle.STRING )
    cursor.callproc( 'lock_find',  [v_result]   )

    result = v_result.getvalue()
    cursor.close()
    db.close()
    return  str(result) + '개의 락 waiting 세션이 발견되었습니다.'


# 3. 테이블 스페이스 사용량 조회 함수

def ts_space_bar():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()

    v_result =  cursor.var( cx_Oracle.CURSOR )
    cursor.callproc( 'get_ts_data',  [v_result]   )

    result = v_result.getvalue()

    a  = [ ]
    for   i   in   result:
        a.append( [ i[0], i[1] ] )

        # 위의 결과를 판다스 데이터 프레임으로 구성 

    import    pandas    as    pd

    df =  pd.DataFrame(  a ,   columns= ['tablespace_name', 'usedspace' ] )


    import   matplotlib.pyplot   as    plt 

    plt.figure( figsize=(10, 6)  )   #  그래프 사이즈 (가로 10, 세로 6) 

    df['freespace'] = 100 - df['usedspace']  # freespace 컬럼 추가

    plt.bar(  df['tablespace_name'],  df['usedspace'],  color='blue' , label='used space')  
    plt.bar(  df['tablespace_name'],  df['freespace'], bottom=df['usedspace'],  color='orange', label='freespace')

    plt.title("Tablespace Used Space")  # 그래프 제목 
    plt.xlabel("Tablespace Name")  # x 축 제목
    plt.ylabel("Space (%) ")            # y 축 제목
    plt.legend()
    plt.xticks(rotation=45)
    plt.show()

#4. 오라클 연동 함수

def connect_oracle():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    import  pandas  as  pd
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    cursor.execute(""" select  * from  emp """)
    row = cursor.fetchall()
    colname = cursor.description
    col=[]
    for  i   in   colname:
        col.append( i[0].lower() )

    emp = pd.DataFrame (list(row), columns=col)

    print(' 잘 연동되었습니다')
    
#5. alert logfile 분석

def alert_analyst():
    jobs = open("C:\\app\\ITWILL\\product\\18.0.0\\diag\\rdbms\\xe\\xe\\trace\\alert_xe.log",  encoding='cp949', errors='ignore')

    data = jobs.read()
    data2= data.split()
    k = [  ]                             
    for  i  in  data2:               
        if  'ora-' in  i.lower():     
            k.append(i)       
                  
    import   pandas   as   pd       

    df = pd.DataFrame(  k,  columns=['col1'] ) 
    from   pandasql  import   sqldf    


    q = """  select  col1, count(*)
                    from  df
                    group by  col1
                    order by 2 desc;   """

    print(sqldf(q) )
    
#6. slack 에 메세지 보내는 함수


def  slack_bot():
    import  requests    #  다른 서버와 통신할 때 사용하는 모듈

    # 슬랙 API 토큰
    slack_token = '토큰'

    # 메시지를 보낼 채널 이름
    channel = 'test'

    # 보낼 메시지 내용
    message = '현재 오라클 데이터베이스에 락 waiting 세션이 발견 되었습니다.'

    # 슬랙 API 엔드포인트 URL
    url = f'https://slack.com/api/chat.postMessage'

    # API 호출을 위한 헤더 설정
    headers = {
        'Authorization': f'Bearer {slack_token}',
        'Content-Type': 'application/json'
    }

    # API 호출 데이터
    data = {
        'channel': channel,
        'text': message
    }

    # 슬랙 API 호출
    response = requests.post(url, headers=headers, json=data)

    # API 응답 확인
    if response.status_code == 200:
        print('메시지가 성공적으로 전송되었습니다.')
    else:
        print('메시지 전송에 실패하였습니다.')
        print('응답:', response.text)
        
#7. 락이 발생하면 True 를 리턴하는 함수

def   lock_is_trigger():
    message = find_lock()
    if   int(message[0]) >= 1:
        return  True        


# easy_dba 함수 

def  easy_dba():

    while   True:
        print( """ ===  dba 작업을 편하게 수행하기 위한 스크립트 총모음 ====

            0.  프로그램을 종료하려면 0번을 누르세요.
            1.  테이블 스페이스  사용량을 확인하려면 1번을 누르세요
            2.  현재 데이터베이스 락(lock) 발생했는지 확인하려면 2번을 누르세요
            3.  오라클와 연동하게 싶으면 3번을 누르세요
            4.  alert log file 을 분석하고 싶다면 4번을 누르세요
            5.  슬랙과 연동하여 락 메세지 보내기 

            """)

        num =  int( input('원하는 번호를 입력하세요 ~' )  )
        
        if num == 0:
            break

        elif  num == 1:
            
           ts_space_bar()
           break
            
        elif  num == 2:
            message = find_lock()
            print(message) 
            break
            
        elif  num ==3:
            connect_oracle() 
            break

        elif num == 4:
            alert_analyst()
            break
            
        elif  num==5:
            
            import  time 

            while  True:
                if   lock_is_trigger() :     
                    slack_bot()              
                time.sleep(5)   

문제 120. (마지막) 슬랙에 락세션이 몇개 발견되었는지 !

result = 0
def slack_bot():
    import requests
    
    # 슬랙 API 토큰
    slack_token = '토큰토큰'
    
    # 메시지를 보낼 채널 이름
    channel = 'test'
    
    # 보낼 메시지 내용
    message = f"현재 오라클 데이터베이스에 {result}개의 락 waiting 세션이 발견되었습니다."
    
    # 슬랙 API 엔드포인트 URL
    url = f'https://slack.com/api/chat.postMessage'
    
    # API 호출을 위한 헤더 설정
    headers = {
        'Authorization': f'Bearer {slack_token}',
        'Content-Type': 'application/json'
    }
    
    # API 호출 데이터
    data = {
        'channel': channel,
        'text': message
    }
    
    # 슬랙 API 호출
    response = requests.post(url, headers=headers, json=data)
    
    # API 응답 확인
    if response.status_code == 200:
        print('메시지가 성공적으로 전송되었습니다.')
    else:
        print('메시지 전송에 실패하였습니다.')
        print('응답:', response.text)


def find_lock ():    
    global result         
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    
    v_result = cursor.var(cx_Oracle.STRING)
    cursor.callproc('lock_find',[v_result])            
                 
    result = v_result.getvalue()
    return(result ,'개의 락 waiting 세션이 발견되었습니다.')      
          

def   lock_is_trigger():
    message = find_lock()
    if   int(message[0]) >= 1:
        return  True

✅ find_lock() 쪽에서 몇개의 락이 발생한건지 뜨길래 result를 공유하면 될 거라 생각해서 글로벌 함수로 만들어주고 사용했다.

최종코드

# 1. 오라클 연동 함수

def   oracle_table(table_name):
    import cx_Oracle
    import pandas as pd

    dsn = cx_Oracle.makedsn('localhost', 1521, 'xe')
    db = cx_Oracle.connect('c##scott', 'tiger', dsn)
    cursor = db.cursor()   
    
    query = f"SELECT * FROM {table_name}"
    
    cursor.execute(query )  

    row = cursor.fetchall()   

    colnames = cursor.description

    col = [ ] 
    for  i   in   colnames:
        col.append( i[0].lower()  )

    df = pd.DataFrame(row , columns = col )
    return ( df )



#2. dba 자동화 스크립트


def find_lock ():    
    global result         
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    
    v_result = cursor.var(cx_Oracle.STRING)
    cursor.callproc('lock_find',[v_result])            
                 
    result = v_result.getvalue()
    return(result ,'개의 락 waiting 세션이 발견되었습니다.')   


# 3. 테이블 스페이스 사용량 조회 함수

def ts_space_bar():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()

    v_result =  cursor.var( cx_Oracle.CURSOR )
    cursor.callproc( 'get_ts_data',  [v_result]   )

    result = v_result.getvalue()

    a  = [ ]
    for   i   in   result:
        a.append( [ i[0], i[1] ] )

        # 위의 결과를 판다스 데이터 프레임으로 구성 

    import    pandas    as    pd

    df =  pd.DataFrame(  a ,   columns= ['tablespace_name', 'usedspace' ] )


    import   matplotlib.pyplot   as    plt 

    plt.figure( figsize=(10, 6)  )   #  그래프 사이즈 (가로 10, 세로 6) 

    df['freespace'] = 100 - df['usedspace']  # freespace 컬럼 추가

    plt.bar(  df['tablespace_name'],  df['usedspace'],  color='blue' , label='used space')  
    plt.bar(  df['tablespace_name'],  df['freespace'], bottom=df['usedspace'],  color='orange', label='freespace')

    plt.title("Tablespace Used Space")  # 그래프 제목 
    plt.xlabel("Tablespace Name")  # x 축 제목
    plt.ylabel("Space (%) ")            # y 축 제목
    plt.legend()
    plt.xticks(rotation=45)
    plt.show()

#4. 오라클 연동 함수

def connect_oracle():
    import  cx_Oracle  # 오라클과 파이썬을 연동하기 위한 모듈
    import  pandas  as  pd
    dsn = cx_Oracle.makedsn( 'localhost' , 1521, 'xe') 
    db = cx_Oracle.connect('c##scott','tiger', dsn)
    cursor  = db.cursor()
    cursor.execute(""" select  * from  emp """)
    row = cursor.fetchall()
    colname = cursor.description
    col=[]
    for  i   in   colname:
        col.append( i[0].lower() )

    emp = pd.DataFrame (list(row), columns=col)

    print(' 잘 연동되었습니다')
    
#5. alert logfile 분석

def alert_analyst():
    jobs = open("C:\\app\\ITWILL\\product\\18.0.0\\diag\\rdbms\\xe\\xe\\trace\\alert_xe.log",  encoding='cp949', errors='ignore')

    data = jobs.read()
    data2= data.split()
    k = [  ]                             
    for  i  in  data2:               
        if  'ora-' in  i.lower():     
            k.append(i)       
                  
    import   pandas   as   pd       

    df = pd.DataFrame(  k,  columns=['col1'] ) 
    from   pandasql  import   sqldf    


    q = """  select  col1, count(*)
                    from  df
                    group by  col1
                    order by 2 desc;   """

    print(sqldf(q) )
    
#6. slack 에 메세지 보내는 함수


result = 0
def slack_bot():
    import requests
    
    # 슬랙 API 토큰
    slack_token = 'ㅇㅇㅇㅇ'
    
    # 메시지를 보낼 채널 이름
    channel = 'test'
    
    # 보낼 메시지 내용
    message = f"현재 오라클 데이터베이스에 {result}개의 락 waiting 세션이 발견되었습니다."
    
    # 슬랙 API 엔드포인트 URL
    url = f'https://slack.com/api/chat.postMessage'
    
    # API 호출을 위한 헤더 설정
    headers = {
        'Authorization': f'Bearer {slack_token}',
        'Content-Type': 'application/json'
    }
    
    # API 호출 데이터
    data = {
        'channel': channel,
        'text': message
    }
    
    # 슬랙 API 호출
    response = requests.post(url, headers=headers, json=data)
    
    # API 응답 확인
    if response.status_code == 200:
        print('메시지가 성공적으로 전송되었습니다.')
    else:
        print('메시지 전송에 실패하였습니다.')
        print('응답:', response.text)
        
#7. 락이 발생하면 True 를 리턴하는 함수

def   lock_is_trigger():
    message = find_lock()
    if   int(message[0]) >= 1:
        return  True        


# easy_dba 함수 

def  easy_dba():

    while   True:
        print( """ ===  dba 작업을 편하게 수행하기 위한 스크립트 총모음 ====

            0.  프로그램을 종료하려면 0번을 누르세요.
            1.  테이블 스페이스  사용량을 확인하려면 1번을 누르세요
            2.  현재 데이터베이스 락(lock) 발생했는지 확인하려면 2번을 누르세요
            3.  오라클와 연동하게 싶으면 3번을 누르세요
            4.  alert log file 을 분석하고 싶다면 4번을 누르세요
            5.  슬랙과 연동하여 락 메세지 보내기 

            """)

        num =  int( input('원하는 번호를 입력하세요 ~' )  )
        
        if num == 0:
            break

        elif  num == 1:
            
           ts_space_bar()
           break
            
        elif  num == 2:
            message = find_lock()
            print(message) 
            break
            
        elif  num ==3:
            connect_oracle() 
            break

        elif num == 4:
            alert_analyst()
            break
            
        elif  num==5:
            
            import  time 

            while  True:
                if   lock_is_trigger() :     
                    slack_bot()              
                time.sleep(5)   
profile
Slow and steady wins the race.

0개의 댓글