SSH Tunneling을 활용해 파이썬으로 MYSQL 연결 하기

테리·2022년 2월 10일
0
post-thumbnail

SSH Tunneling

VPN과 같이 원격으로 서버에 접속하는 것으로 외부에 개방되지 않은 서버에 로컬 환경에서 접근하는 것. 다시말해 원격 게이트웨이를 통해 SSH에 접속한 후, 내부에서 접속 가능한 private service에 접근한다.(보완이 중요한 DB는 방화벽을 별도로 깔아두지 않아 외부에서 테스트하기 어렵기 때문에 이 방식을 사용)
SSH Tunneling은 private key를 설정하고 해당 서버내의 MYSQL 서버로 접속하도록 도와줌.

  1. pymysql, sshtunnel 패키지 설치
pip install pymysql
pip install sshtunnel
  1. pymysql, sshtunnel 불러오기
import pymysql
from sshtunnel import SSHTunnelForwarder
if __name__ == '__main__':
# SSH address mapping setup (not actually connects)
    with SSHTunnelForwarder(('ssh터널 host 주소', ssh터널 IP),
                            ssh_username='ssh_username',
                            ssh_pkey='ssh_private_key',
                            remote_bind_address=('mysql_server_host', 3306(mysql_port)),
                           ) as tunnel:
# connect MySQL like local                           
        with pymysql.connect(
            host='127.0.0.1', #(local_host)
            user='db_username',
            passwd='db_password',
            db='db',
            charset='utf8',
            port=tunnel.local_bind_port,
            cursorclass=pymysql.cursors.DictCursor) as conn:
            with conn.cursor() as cur:
                sql = "sql문 작성"
                cur.execute(sql)
                print(sql)
                results = cur.fetchall()
                print(results)
                for result in results:
                    print(result)

참고)

  • 커서(Cursor()) : 쿼리문에 의해서 반환되는 결과값들을 저장하는 메모리 공간
  • 커서의 fetchall() 메서드: 모든 데이타를 한꺼번에 클라이언트로 가져올 때 사용하는 함수로 레코드를 배열 형식으로 저장해주는 역할을 함.
  • Cursor 객체의 execute() 메서드를 사용하여 SQL 문장을 DB 서버에 보낸다.
  • print()를 for문으로 돌리는 이유는 그냥 단순 print(results)를 하면 결과 값이 기존 테이블 처럼 한줄씩 나오는 것이 아니라 전부다 이어져서 나옴. 그렇기 때문에 for문을 사용해서 results값을 result라는 변수에 {}를 기준으로 한줄씩 넣어주고 그걸 출력함.
__name__==__main__

에 관한 자세한 설명은 하단 링크 참조
https://madplay.github.io/post/python-main-function

profile
영화 좋아합니다

0개의 댓글