본문 바로가기
Coding/Python

[Python] 파이썬 코드 SSH 터널링으로 aws rds DB 접속&연결 (mysql)

by 포스트it 2022. 4. 15.
반응형

 

[Python] 파이썬 코드 SSH 터널링으로 aws rds DB 접속&연결 (mysql)

 

SSHTunnelForwarder, pymysql 를 import 해주시고,

ssh 터널링 할 준비를 해주세요.

1. ec2 host

2. ec2 user

3. ssh 키파일

4. rds 엔드포인트 && port

5. db 아이디 및 페스워드, 포트번호

 

아래코드에 순서대로 넣어주시면 끝입니다 !

from sshtunnel import SSHTunnelForwarder
import pymysql
 
with SSHTunnelForwarder(
    ('test.public-ec2-instance.amazonaws.com'),
    ssh_username="ec2-user",
    ssh_pkey="~/ssh-tunnel-rds.pem",
    remote_bind_address=('aws-rds-endpoint.amazonaws.com', 3306)
) as tunnel:
    print("== SSH Tunnel ==")
 
    db = pymysql.connect(
        host='127.0.0.1', user="root",
        password="1234", port=tunnel.local_bind_port
    )
    # Run sample query in the database to validate connection
    try:
        # Print all the databases
        with db.cursor() as cur:
            cur.execute('SHOW DATABASES')
            for r in cur:
                print(r)
    finally:
        db.close()
 
print("SSH 터널링 완료 !!")

 

 

db 접속 정보가 127.0.0.1(localhost) 인 이유는

우리는 aws ec2로 ssh 터널링 접속을 했기 때문에

aws ec2 입장이 되어서 localhost가 되는겁니다. 

728x90
반응형

댓글