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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章