python-通过ssh远程连接mysql

通过跳板机ssh远程连接mysql:

import pymysql
from sshtunnel import SSHTunnelForwarder
import requests
import datetime

with SSHTunnelForwarder(
        ssh_address_or_host=('ssh-Ip', 22), 
        ssh_password='ssh-密码',
        ssh_username='ssh-用户',
        remote_bind_address=('数据库连接地址/服务器ip(如:128.1.1.1)', 3306)) as server:
        try:
            server.start()
            connect_stat = pymysql.Connect(host='127.0.0.1', port=server.local_bind_port, user='数据库-user', passwd='数据库-passwd', db='数据库-名', charset='utf8')
            print(connect_stat)
            cursor = connect_stat.cursor()
            # 查询sql
            sql_flag = '''
            SELECT id from t_table
            '''
            cursor.execute(sql_flag)
            fetchall = cursor.fetchall()
            print("size:", len(fetchall))
            for data in fetchall:
               d1 = data[0]
               print('查询数据:', d1)

        except(Exception) as e:
            print('e:', e)
        finally:
            cursor.close()
            connect_stat.close()

你可能感兴趣的:(~python,-数据库-,python,数据库)