SSH Tunneling
VPN과 같이 원격으로 서버에 접속하는 것으로 외부에 개방되지 않은 서버에 로컬 환경에서 접근하는 것. 다시말해 원격 게이트웨이를 통해 SSH에 접속한 후, 내부에서 접속 가능한 private service에 접근한다.(보완이 중요한 DB는 방화벽을 별도로 깔아두지 않아 외부에서 테스트하기 어렵기 때문에 이 방식을 사용)
SSH Tunneling은 private key를 설정하고 해당 서버내의 MYSQL 서버로 접속하도록 도와줌.
pip install pymysql
pip install 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)
참고)
__name__==__main__
에 관한 자세한 설명은 하단 링크 참조
https://madplay.github.io/post/python-main-function