Python3登录跳板机访问MySQL数据库

      生产环境的数据库基于安全的原因是无法直连访问的,但是有时本地测试的时候又需要访问生产环境的库,这时候就需要登录跳板机来中转。

     目前登录跳板机有两种:

  1. 使用paramiko    
  2. 使用sshtunnel.

     以下以sshtunnel为例实现:

import os
import pymysql
from sshtunnel import SSHTunnelForwarder
KEY_FILE = os.path.join(os.path.dirname(__file__), "../id_rsa.pem")
TUNNEL = SSHTunnelForwarder(("192.168.1.2", 22),       #跳板机的地址
                            ssh_username="guest",
                            ssh_password="xxxxxxxx",   #跳板机访问密码,和key二选一
                            ssh_pkey=KEY_FILE,
                            remote_bind_address=("192.168.1.10", 3306))  #目标数据库地址&端口
TUNNEL.start()

conn = pymysql.connect(host='127.0.0.1',
                       port=TUNNEL.local_bind_port,    #默认
                       user="user",                    
                       password="pas123",
                       database="target_db")
cursor = conn.cursor()    
cursor.execute("SELECT * FROM table")
data = cursor.fetchall()
cursor.close()

TUNNEL.stop()

当然也可以使用with的方式启动SSHTunnelForwarder, 但是实际测试中,会导致进程无法正常结束(可能是那没配置对吧),暂时忽略。

 

 

 


版权声明:本文为wuhendadi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。