Python示例:通过ssh tunnel连接SQL Server

这个示例可以结合着之前的连接MySQL一起来看:参考

代码如下。当然,运行之前,你需要

  • 已经完成了基本的工具安装,这个并不容易(参考)
  • 已经有一个可以正常运行的与连接的SQL Server
  • 已经有一个网络上到SQL Server联通的主机的ssh账号
  • 下面的实例中,还需要一个t_1表,表中有三个字段

import pyodbc
import pandas as pd
import logging
import sshtunnel
from sshtunnel import SSHTunnelForwarder

ssh_host = 'x.x.x.x'
ssh_port=22
ssh_username = 'lilei'
ssh_password = 'xxxxxx'


db_server = 'x.x.x.x'
db_port= 1433
database = 'xxx'
db_username = 'xxx'
db_password = 'xx'


tunnel = SSHTunnelForwarder(
    (ssh_host, ssh_port),
    ssh_username = ssh_username,
    ssh_password = ssh_password,
    remote_bind_address = (db_server, db_port),
)
tunnel.start()


cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=127.0.0.1,'+str(tunnel.local_bind_port)+';DATABASE='+database+';UID='+db_username+';PWD='+ db_password)
cursor = cnxn.cursor()

cursor.execute("SELECT * FROM dbo.t_1;")
row = cursor.fetchone()
while row:
    print('ID: %(id)03s | nick: %(nick)012s | birthdate: %(bd)010s' %
      {'id':row[0],'nick':row[1],'bd':row[2]})
    row = cursor.fetchone()

Leave a Reply

Your email address will not be published. Required fields are marked *