I have a python script that connects to a remote MySQL database using the python library MySQLdb. It works fine but how can I get it to connect through a proxy that I'm behind when at work. I can connect via the command line in ssh, but how do I get the python script to use the proxy settings. There doesnt seem to be any options in the MySQLdb commands for proxy configurations.
import MySQLdb as mdb
conn=mdb.connect(host='mysite.com',user='myuser',passwd='mypassword',db='mydb')
cursor = conn.cursor()
To use a proxy in Python, first import the requests package. Next create a proxies dictionary that defines the HTTP and HTTPS connections. This variable should be a dictionary that maps a protocol to the proxy URL. Additionally, make a url variable set to the webpage you're scraping from.
Another way to pass a proxy address to Python is to set the http_proxy and https_proxy environment variables. If you set environment variables, you don't need to define any proxies in your code. Just be aware that proxy settings passed through code now override settings set via environment variables.
Python supports relational database systems. Python database APIs are compatible with various databases, so it is very easy to migrate and port database application interfaces.
I know this is a rather old post, but I thought I'd answer it anyway.
you can use your SSH connection as a proxy
The easiest way it to use proxychains
The default port for proxychains is 9050 so when when you connect to the remote host include the -D
parameter like:
ssh -D 9050 -l user remotehost
Then from a separate terminal window, or using screen
, on your local machine any command you preface with proxychains
is routed through the SSH server, for example:
proxychains python myscript.py
will route all outbound TCP requests, whether a database connection or a urllib2/requests HTTP(S) request.
Proxychains is not specific to python, but anything. You can just as easily launch a web browser or anything else. Try proxychains firefox
or proxychains curl https://api.ipify.org
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With