Created
April 23, 2020 19:36
-
-
Save revolutionisme/ff6a81ecff314d63b77361810d28ed33 to your computer and use it in GitHub Desktop.
Python xample to run query using ssh tunneling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import pymysql as db | |
import pandas as pd | |
from sshtunnel import SSHTunnelForwarder | |
logging.basicConfig( | |
format="%(asctime)s : %(levelname)s : %(message)s", level=logging.DEBUG | |
) | |
# ssh variables | |
ssh_host = 'ssh_or_bastion_host_name' | |
ssh_username = 'ssh_username' | |
ssh_private_key = 'private_key_absolute_path' | |
# database variables | |
db_server_host = 'database_server_host_name' | |
user = 'usnermane_to_the_db' | |
password = 'password_to_the_db' | |
database = 'database_name' | |
localhost = '127.0.0.1' | |
def run_query(q): | |
with SSHTunnelForwarder( | |
(ssh_host, 22), | |
ssh_username=ssh_username, | |
ssh_private_key=ssh_private_key, | |
remote_bind_address=(db_server_host, 3306), | |
) as tunnel: | |
print(tunnel) | |
logging.info(f"Tunnel is up: {tunnel.tunnel_is_up}") | |
logging.info( | |
f"Trying to connect to host {tunnel.local_bind_host} on port {tunnel.local_bind_port}" | |
) | |
conn = db.connect( | |
host=tunnel.local_bind_host, | |
port=tunnel.local_bind_port, | |
user=user, | |
passwd=password, | |
db=database, | |
) | |
logging.info("Created connection!") | |
result = pd.read_sql_query(q, conn) | |
logging.info(result) | |
return result | |
if __name__ == "__main__": | |
q = "SELECT * from TABLE_NAME LIMIT 5" | |
result = run_query(q) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment