当前位置: 首页 > 工具软件 > sshtunnel > 使用案例 >

Python实践(二)——通过SSHTunnel远程访问数据库

乐正意智
2023-12-01

一、功能

  1. 访问数据库
  2. 数据库需要远程通过SSHTunnel访问

二、实现

import pymysql
from sshtunnel import SSHTunnelForwarder

sshServerB_ip = '192.168.3.126'
sshServerB_port = 22
sshServerB_usr = 'root'
sshServerB_pwd = 'root'
databaseA_ip = 'localhost'
databaseA_port = 3306
databaseA_usr = 'admin'
databaseA_pwd = '******'
databaseA_db = 'new_table'


with SSHTunnelForwarder(
        (sshServerB_ip, sshServerB_port),
        ssh_password=sshServerB_pwd,
        ssh_username=sshServerB_usr,
        remote_bind_address=(databaseA_ip, databaseA_port)) as server:

    db_connect = pymysql.connect(host='127.0.0.1', port=server.local_bind_port, user=databaseA_usr,
                                         passwd=databaseA_pwd, db=databaseA_db)
    cur = db_connect.cursor()
    db_connect.commit()
    sql = "show tables"
    cur.execute(sql)
    myresult = cur.fetchall()
    for x in myresult:
        print(x)
    db_connect.close()
 类似资料: