Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to Proxy (SOCKS) Database in python

I am trying to connect to a database that needs proxy (socks) to be able to connect, if I use the proxy connection manually, I can connect, but I need to make the script connect to the proxy (socks) of the machine to make this SELECT

SCRIPT

import socket
import socks
import requests
import pymssql

socks.set_default_proxy(socks.SOCKS5, "138.34.133.155", 1080, True, 'user','password')
socket.socket = socks.socksocket

server = '172.43.56.89'
username = 'user'
password = 'password'
database = 'dbname'

conn = requests.get(pymssql.connect(host=server,user=username,password=password,database=database))

cursor = conn.cursor()

cursor.execute("SELECT column FROM table")

row = cursor.fetchall()

conn.close()

for i in row:
    print(i)

OUTPUT

Traceback (most recent call last): File "connection.py", line 15, in conn = requests.get(pymssql.connect(host=server,user=username,password=password,database=database)) File "src\pymssql.pyx", line 642, in pymssql.connect pymssql.OperationalError: (20009, 'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (172.43.56.89:1433)\nNet-Lib error during Unknown error (10060)\n')

like image 820
Luis Henrique Avatar asked Oct 23 '19 14:10

Luis Henrique


2 Answers

I think an option is to mount a local tunnelling sock with port forwarding, to map your database port and act as if your server where a localhost one.

It's really efficient if you're running your python script on a Unix computer.

Something like this system call (for a 3306 mariaDB) :

ssh -L 3306:localhost:3306 [email protected]

First, your run SSH, then, you tell him to enable a port forwarding from the 3306 port to the localhost:3306 port of the server you connect through user@IP.

With this, every query from your local machine:3306 will by send to your MariaDB:3306 server, allowing you to use it as if you where on the server.

like image 141
Blag Avatar answered Oct 31 '22 09:10

Blag


If you do not want to hack into pymssql source code, there're external tools that redirect all TCP traffic over the socks proxy, such as FreeCap for Windows, RedSocks for Linux and Proximac for macOS.

like image 1
Arnie97 Avatar answered Oct 31 '22 10:10

Arnie97