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

SSHTUNNEL(跳板机)连接数据库

容柏
2023-12-01
from PyMySQL import pymysql
from sshtunnel import SSHTunnelForwarder
import sshtunnel
import paramiko

# 正常链接
# db=pymysql.connect(host='192.xxx.xxx.xx',
#                      user='sale',
#                      password='Sale',
#                      database='ub')

# 跳板机链接                  密码正常链接,秘钥验证有问题,server.start有问题
server = SSHTunnelForwarder(
    ssh_address_or_host="ssh域名",
    ssh_port=622,
    ssh_username='zha',
    #ssh_pkey='~/.ssh/id_rsa',
    #ssh_private_key_password="C:/Users/Administrator/.ssh/id_rsa", 
    ssh_password="wW0ODd1",                     #密码验证太慢,私钥验证代码链接不上                              
    remote_bind_address=("172.xx.xx.xxx", 06)) 
server.start()
db=pymysql.connect(host='127.0.0.1',   
                user='root',
                password='1o9pSW',
                database='ub',
                port=server.local_bind_port,
                charset='gbk')  
                     
cursor=db.cursor()
sql="SELECT CE FROM `ub`.`pany` where CO='002215'"
cursor.execute(sql)
#单个数据
data = cursor.fetchone()
#多个数据
#results = cursor.fetchall()
print(data)
db.close()
server.stop()




# paramiko     有点问题,我还没调试,先放着
# with sshtunnel.open_tunnel(
#     ('ssh域名', 60022),
#     ssh_username='zha',
#     # ssh_pkey="C:/Users/Administrator/.ssh/id_rsa",
#     # ssh_private_key_password="123456",
#     ssh_password="wW0O",
#     remote_bind_address=("172.00.00.000", 2345),
# )as tunnel:
#     client=paramiko.SSHClient()
#     client.load_system_host_keys()
#     client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#     db=client.connect(host='127.0.0.1',   
#                     user='root',
#                     password='1o9',
#                     database='ub',
#                     port=tunnel.local_bind_port,
#                     charset='gbk')
#     cursor=db.cursor()
#     sql="SELECT COMP FROM `ub`.`cc_com` where COM='7139c15'"
#     cursor.execute(sql)
#     #单个数据
#     data = cursor.fetchone()
#     print(data)
#     db.close()
#     client.close()

 类似资料: