Created
September 26, 2021 08:38
-
-
Save eshirazi/bb4c272ba5f55bd6e3d18b92e53aacdf to your computer and use it in GitHub Desktop.
Using SQLAlchemy to connect to Microsoft Sql Server database using SOCKS 5 proxy with Python-TDS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socks | |
import pytds | |
from sqlalchemy import create_engine | |
from sqlalchemy.pool import StaticPool | |
host = ... | |
port = 1433 | |
user = ... | |
password = ... | |
socks_proxy_host = ... | |
socks_proxy_port = ... | |
socks_proxy_user = ... | |
socks_proxy_password = ... | |
def create_connection_socks5(host, port, socks_proxy_host, socks_proxy_port, | |
socks_proxy_user, socks_proxy_password): | |
s = socks.socksocket() # Same API as socket.socket in the standard lib | |
s.set_proxy( | |
socks.SOCKS5, | |
socks_proxy_host, | |
username=socks_proxy_user, | |
password=socks_proxy_password, | |
port=socks_proxy_port) | |
# Can be treated identical to a regular socket object | |
s.connect((host, port)) | |
return s | |
def create_pytds_connection_with_socks_proxy(host, port, user, password, socks_proxy_host, socks_proxy_port, | |
socks_proxy_user, socks_proxy_password, database=""): | |
return pytds.connect(host, database, user, password, port=port, sock=create_connection_socks5( | |
host=host, | |
port=port, | |
socks_proxy_host=socks_proxy_host, | |
socks_proxy_port=socks_proxy_port, | |
socks_proxy_user=socks_proxy_user, | |
socks_proxy_password=socks_proxy_password, | |
)) | |
eng = create_engine( | |
"mssql+pytds://{user}:{password}@{host}:{port}".format( | |
host=host, | |
port=port, | |
user=user, | |
password=password, | |
), | |
# poolclass=StaticPool, | |
creator=lambda: create_pytds_connection_with_socks_proxy( | |
host=host, | |
port=port, | |
user=user, | |
password=password, | |
socks_proxy_host=socks_proxy_host, | |
socks_proxy_port=socks_proxy_port, | |
socks_proxy_user=socks_proxy_user, | |
socks_proxy_password=socks_proxy_password, | |
)) | |
print(eng.execute("select 1")).fetchone() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment