python3 通过ssh登录mysql

import pymysql
from sshtunnel import SSHTunnelForwarder
from config import Cfg


class MYSQL:
    # 初始化函数,初始化连接列表
    def __init__(self, host, port, user, pwd, dbname):
        self.host = host
        self.port = port
        self.user = user
        self.pwd = pwd
        self.dbname = dbname

    # 获取数据库游标对象cursor
    # 游标对象:用于执行查询和获取结果
    def get_cursor(self):
        # ssh 登录跳板机
        server = SSHTunnelForwarder(
            ssh_address_or_host=(Cfg.SSH.HOST, Cfg.SSH.PORT),  # 指定ssh登录的跳转机的address
            ssh_username=Cfg.SSH.USER,  # 跳转机的用户
            # ssh_password='*****',  # 跳转机的密码
            local_bind_address=(Cfg.LOCAL_MYSQL.HOST, Cfg.LOCAL_MYSQL.PORT), # 映射到本机的地址和端口
            remote_bind_address=(self.host, self.port), # 数据库的地址和端口
            ssh_pkey=Cfg.SSH.PRIVATE_KEY)  # rsa 私钥路径
        server.start()
        # 建立数据库连接
        self.db = pymysql.connect(
            user=self.user,
            passwd=self.pwd,
            # host=host,
            host=Cfg.LOCAL_MYSQL.HOST,  # 映射地址local_bind_address ip
            port=Cfg.LOCAL_MYSQL.PORT,  # 映射地址local_bind_address port
            db=self.dbname,             # 需要连接的实例名
            cursorclass=pymysql.cursors.DictCursor)

        # 创建游标对象
        cur = self.db.cursor()

        # 返回
        return cur
class Cfg:
    class MYSQL_TEST:
        HOST = "1.1.1.1"
        PORT = 3306
        USER = "root"
        PWD = "****"
        DB = "test"

   
    class SSH:
        HOST = "2.2.2.2"
        PORT = 22
        USER = "root"
        PRIVATE_KEY = "~.ssh/id_rsa" # rsa private key file path
    # 映射到本地mysql 地址,端口
    class LOCAL_MYSQL:
        HOST = "127.0.0.1"
        PORT = 1268

posted on 2021-03-17 16:05  小菜鸟!!  阅读(352)  评论(0编辑  收藏  举报

导航