728x90
반응형

개요

그룹웨어 DB인 Postgresql에서 User View Table에 임직원이 추가 되거나 부서 이동 하였을 경우

그룹웨어에 먼저 업데이트 되는데 이 데이터를 긁어와서 LDAP에도 자동으로 업데이트 되도록 List를 추출하는 작업이다

Python으로 임직원 목록을 불러오며, 외주직원은 제외하거나, 퇴사한 직원, 전체 부서 리스트 등을 추출 한다.

#-*- coding: euc-kr -*-
import boto3
import json
import psycopg2
import requests
import sys
import chardet

sys.stdout = open('/usr/share/openldap-servers/userList.json', 'w')

try:
    conn_string = "host='gw.testhub.com' dbname='tims' user='test' password='test2164!@' port='5432'"
    conn = psycopg2.connect(conn_string)
    cur = conn.cursor()
    #qry_origin = "select userid, status, username, mailaddr, deptname, updated_at from view_user where updated_at >= current_timestamp + '-240 minute' and deptcode not like 'E%' and order by updated_at desc"
    qry_origin = "select userid, status, username, mailaddr, deptname, updated_at from view_user where deptcode not like 'E%'"
    qry = u"select row_to_json(tmp) from ("+ qry_origin +") tmp;"
    cur.execute(qry)
    rownum = int(cur.rowcount)
    i=0
    while i < rownum:
        result = cur.fetchone()[0]
        print(json.dumps(result, ensure_ascii=False).encode('utf8'))
        i = i + 1
    cur.close()
    conn.close()
except psycopg2.DatabaseError as db_err:
    print('!!! not connected !!!', db_err)

sys.stdout.close()

sys.stdout = open('/usr/share/openldap-servers/userStopList.json', 'w')

try:
    conn_string = "host='gw.testhub.com' dbname='tims' user='test' password='test2164!@' port='5432'"
    conn = psycopg2.connect(conn_string)
    cur = conn.cursor()
    #qry_origin = "select userid, status, username, mailaddr, updated_at from view_user where updated_at >= current_timestamp + '-240 minute' and status='STOP'"
    qry_origin = "select userid, status, username, mailaddr, updated_at from view_user where status='STOP'"
    qry = u"select row_to_json(tmp) from ("+ qry_origin +") tmp;"
    cur.execute(qry)
    rownum = int(cur.rowcount)
    i=0
    while i < rownum:
        result = cur.fetchone()[0]
        print(json.dumps(result, ensure_ascii=False).encode('utf8'))
        i = i + 1
    cur.close()
    conn.close()
except psycopg2.DatabaseError as db_err:
    print('!!! not connected !!!', db_err)

sys.stdout.close()

sys.stdout = open('/usr/share/openldap-servers/gwTotalGroupList.lst', 'w')

try:
    conn_string = "host='gw.testhub.com' dbname='tims' user='test' password='test2164!@' port='5432'"
    conn = psycopg2.connect(conn_string)
    cur = conn.cursor()
    qry_origin = "select distinct deptcode, deptname from view_user where deptcode not like 'E%'"
    qry = u"select row_to_json(tmp) from ("+ qry_origin +") tmp;"
    cur.execute(qry)
    rownum = int(cur.rowcount)
    i=0
    while i < rownum:
        result = cur.fetchone()[0]
        print(json.dumps(result, ensure_ascii=False).encode('utf8'))
        i = i + 1
    cur.close()
    conn.close()
except psycopg2.DatabaseError as db_err:
    print('!!! not connected !!!', db_err)

sys.stdout.close()

Lambda로도 비슷하게 가능하다.

import boto3
import json
import psycopg2 #PostgreSQL 과 연결하려면 반드시 있어야 되는 드라이버 (람다에서는 레이어 붙이는걸로 처리 가능)
import requests

def lambda_handler(event, context):
    
    print('db connect')
    conn = psycopg2.connect(host='gw.testhub.com', dbname='tims', user='test', password='test2164!@', port='5432') #DB 접속 구문 
    print('db connect success!')
    cur = conn.cursor() #커서 생성 (쿼리 칠 때 필요함)
    print('start query')
    
    qry_origin = "select status, empno, username, mailaddr, deptcode, deptname, dutycode, positionname, dutyname, updated_at from view_user where updated_at >= current_timestamp + '-10 minute' and status like 'STOP' and dutyname is null order by updated_at desc"
    qry = "select row_to_json(tmp) from ("+ qry_origin +") tmp;" #쿼리문 (row_to_json으로 바로 JSON 형식으로 뽑아다줌)
    
    cur.execute(qry) #쿼리 실행
    rownum = int(cur.rowcount)  # DB 총 행 개수 구하기
    print(rownum)
    
    i=0
    while i < rownum: #쿼리 결과 값 나온 행 수 만큼 반복해서 
        result = cur.fetchone()[0] #cur.fetchone()로 한 행 결과값 묶어주기 (fetchall() 을 호출하면 전체 행 값이 나옴) ([0] 을 넣어줘야 대괄호나 괄호가 안생김)
        req_url = requests.post('https://intra.testhub.com:7075/RF_COUNT/minsu/insertUsr', json = result) #결과 값 URL 호출
        print(result)
        print(req_url)
        i = i + 1
   

    cur.close()
    conn.close()
728x90
300x250

+ Recent posts