python db access though ssh user

Solutions on MaxInterview for python db access though ssh user by the best coders in the world

showing results for - "python db access though ssh user"
Anton
03 Jun 2017
1import pymysql
2import paramiko
3import pandas as pd
4from paramiko import SSHClient
5from sshtunnel import SSHTunnelForwarder
6from os.path import expanduser
7
8home = expanduser('~')
9mypkey = paramiko.RSAKey.from_private_key_file(home + pkeyfilepath)
10# if you want to use ssh password use - ssh_password='your ssh password', bellow
11
12sql_hostname = 'sql_hostname'
13sql_username = 'sql_username'
14sql_password = 'sql_password'
15sql_main_database = 'db_name'
16sql_port = 3306
17ssh_host = 'ssh_hostname'
18ssh_user = 'ssh_username'
19ssh_port = 22
20sql_ip = '1.1.1.1.1'
21
22with SSHTunnelForwarder(
23        (ssh_host, ssh_port),
24        ssh_username=ssh_user,
25        ssh_pkey=mypkey,
26        remote_bind_address=(sql_hostname, sql_port)) as tunnel:
27    conn = pymysql.connect(host='127.0.0.1', user=sql_username,
28            passwd=sql_password, db=sql_main_database,
29            port=tunnel.local_bind_port)
30    query = '''SELECT VERSION();'''
31    data = pd.read_sql_query(query, conn)
32    conn.close()
33