A
A
Alexander Karabanov2018-04-16 20:08:19
Python
Alexander Karabanov, 2018-04-16 20:08:19

How to connect to MSSQL via SSH tunnel from Python script?

Hello.
This is how the tunnel rises, the connection with MSSQL, as it were, is trying to be established, but that's all and the connection ends endlessly in the pending state:

import pymssql
from sshtunnel import SSHTunnelForwarder
from time import sleep

def query():
  with SSHTunnelForwarder(
      ('111.222.333.444', 22),
       ssh_username='ssh-user',
       ssh_password='ssh-pass',
       remote_bind_address=('192.168.0.2', 1433),
       local_bind_address=('127.0.0.1', 1433),
  ) as tunnel:

      print(tunnel)

      connection = pymssql.connect(server='127.0.0.1', port='1433', user='user', password='pass', database='base')
      cursor = connection.cursor(as_dict=True)
      cursor.execute('SELECT id_country id, name title FROM dbo.Country WHERE id_country > 0')
      for row in cursor:
          print(row['title'])
      sleep(2)
      connection.close()
      sleep(10)
  print('FINISH!')

query()

If you divide the script into two and in one leave the part of the code that raises the tunnel, and in the second leave the part of the code that connects to the MSSQL database and run them in turn, then everything will happen, the tunnel will rise, the script will connect to MSSQL and execute the query.
That is, it is not possible to raise the tunnel and connect to the MSSQL database from one script ...
What am I doing wrong? Or maybe it's some kind of bug?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
planc, 2018-04-16
@planc

remove local_bind_address=('127.0.0.1', 1433),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question