반응형
[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
반응형
'Coding > Python' 카테고리의 다른 글
[Python & Flask] 플라스크 jinja2.exceptions.TemplateNotFound 에러 메세지 해결방법 !! (0) | 2022.04.21 |
---|---|
[Python & Flask] FORM 태그로 데이터 보내기 (POST, GET) (0) | 2022.04.18 |
[Python] format(포맷팅) 방법 및 사용방법 (%, format,f-string) (0) | 2021.03.22 |
[Python] 코드 실행,작동 시간 측정하기 - time() 함수 이용 (0) | 2021.03.19 |
[Python] Flask에서 Session(세션) 사용 방법 및 예제 (공식문서 참조) (0) | 2021.03.12 |
댓글