Connect to external database (mysql) with python - python

I am trying to connect to my website's MySQL database from my own computer. The script I use:
hostaddress = 'sitedezign.net'
username = '*********'
password = '*********'
database = '*********'
db_port = 3306
#connect
db = _mysql.connect(host=hostaddress,user=username,passwd=password,db=database, port=db_port)
However I get the following error
Traceback (most recent call last):
File "C:\Users\Yorian\Desktop\TU\Stage Shore\python_files\Rectify, metadata and upload\sql_test.py", line 25, in <module>
port=db_port)
OperationalError: (2003, "Can't connect to MySQL server on 'sitedezign.net' (10061)")
I have switched my computer's firewall off and also added an outbound rule to my firewall for when I connect to an outbound port 3306 (to allow this)
The user does have the rights, I've tested this by running a php script with the same login data on the server and it connects perfectly fine (host=localhost)
I set the server to allow external connections coming from my IP address (IPv4 as well as IPV6)
The server is from a webhoster so I can not access the server myself.
Anybody that has an idea where things are going wrong?

Related

psycopg2.OperationalError: could not translate host name "xxxxxx.us-east-1.rds.amazonaws.com" to address: Unknown host

I am unable to connect to the PostgreSQL database through psycopg2 for some reason
here is my connection configuration:
conn = psycopg2.connect(
user = "postgres",
password = "xxxxxx",
host = "xxxx.us-east-1.rds.amazonaws.com",
database = "current2",
port = 5432
)
I put sensitive information in x's, but ignoring that, what exactly am I doing wrong?
That is an error with your domain name resolution (DNS) setup and has nothing to do with the database. The DNS server you have configured on your system cannot resolve the host name.
Either use a different DNS server, or use the database server's IP address.

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')
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 user#x.x.x.x
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.
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.

How to use python to connect mysql via ip address?

I want to try to use python to connect to MySQL database.
Connecting to localhost works fine but I can not connect to MySQL database via ip address.
Here is my code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
db = MySQLdb.connect(host="My Computer IP",
user="root", passwd="606", db="testdb",port=3306)
cursor = db.cursor()
cursor.execute("SELECT * FROM table1")
results = cursor.fetchall()
for record in results:
col1 = record[0]
col2 = record[1]
print "%s, %s" % (col1, col2)
db.close()
The error is like this:
OperationalError: (2003, "Can't connect to MySQL server on 'My
Computer IP' (111)")
I found that someone who also has asked the similar question on stackoverflow --> Can't connect to MySQL server error 111
I have tried this method but it still doesn't work.
I don't have the line skip-networking in the document "my.cnf" originally.
So basically, mysql should not listen only 127.0.0.1.
In theory, mysql can listen any IP and I also set the port 3306 to be allowed in my computer.
Does anyone has some suggestion?
This answer works for me: Trying to connect to remote MySQL host (error 2003)
I got the same error, when I connected db using localhost, connection was OK. But using ip 114.***.***.***, from another pc, or from the db server itself, were all failed. And I can ping this ip from another pc.
My error was caused by an intermediate router, when I wanted to access the db via ip (not localhost or 127.0.0.1), the connection request was sent to the router, then forwarded to the db server. And the router didn't have forwarding rules about that.
So I added a rule to the router by its config page, then connected the db successfully.

How to connect to my remote SQL server

I have a linux ubuntu server that I rent from DigitalOcean for storing streaming real time data in MySQL by coding with python.
Problem is that I am coding not in the linux server environment but in my local computer python(personal Windows 10(not a server)). So in the coding, I need to connect to my linux server in order to feed/get the data to/from the linux MySQL server.
I know I need to use MySQLdb library in python to do this. I tried to connect to my linux server by using this MySQLdb in python, but it could not connect to the server.
A different question:
For granting other ip addresses from which I am connect to the mysql server, should I do it whenever my ip address changes? for example, when I work at home I need to grant my home internet ip, and when I work other places do I need to grant that ip addresses?
Anyway, I tried granting to the ip address where I am connecting to the internet, but even after the granting I cannot access to the mysql server.4
What should I do?
Here is the code I used;
import MySQLdb
conn = MySQLdb.connect("000.000.000.0", "root", "password", "name of database")
"000.000.000.0" is the server that I rent and it is a linux server.
"root" is my username of the server
"password" is the password for the server as well as for the mysql.
and then the name of the database I want to connect to.
c = conn.cursor()
c.execute("SELECT * FROM practice")
here I just want to see what's in the "practice" table that I have made in the database.
rows = c.fetchall()
for eachRow in rows:
print eachRow
I don;t know what went wrong.
For Granting I used following code:
GRANT ALL ON nwn.* TO new_username#'00.000.000.00' IDENTIFIED BY 'new_password';
The ip address 00.000.000.000 is Starbucks ip address where I am working on this project right now.I got a message like this:
Query OK, 0 rows affected, 1 warning (0.03 sec)
After that I tried to connect in python on my local window python.And it didn't work and got this python error:
OperationalError: (2003, "Can't connect to MySQL server on '000.000.000.0' (10061)")
What's wrong with this?
Similar question have already been asked here.
Can you connect from your local OS to your remote Database?
mysql -u XXXX -h {IP} -p
Have you granted your client in the Database? Digital Ocean HowTo for this
Create an user for the remote access
GRANT SELECT,DELETE,INSERT,UPDATE ON tablename.* TO 'user'#'your_local_ip';
FLUSH PRIVILEGES;
It's good practice not to grant all privileges for remote users (scripts)
Your local IP should be a static IP, otherwise you have allways change ip or use a dynDNS like Service.
(EDIT)
I just set up an environment:
If you connect to an address that does not exist or the mysql/mariadb instance is not running you get errorcode 2003.'
(2003, "Can't connect to MySQL server on 'my_hostname' (61)")
If you're local host is not granted you get error 1130
(1130, "Host '213.213.213.213' is not allowed to connect to this MariaDB server")
To check if you can access your remote sql server try
mysql -h 123.123.123.123 -u username -p
on youre local windwos machine, where 123.123.123.123 is the IP Adress of your DigitalOcean Server.
To get your public IP Adress (outside of starbucks) you can visit a Site like this
If you REALLY used 0.0.0.0 as ip:
0.0.0.0 in service configuration as ip address is used to bind the service for external access. 0.0.0.0 is like a joker for every ip, but can not be used to access the server/service remotely.

MySQLdb connection problems

I'm having trouble with the MySQLdb module.
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
(I'm using a custom port)
the error I get is:
Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
[root#baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
I tried directly from the python prompt:
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
I'm confused... :(
Changing localhost to 127.0.0.1 solved my problem using MySQLdb:
db = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
Using 127.0.0.1 forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If host is specified as localhost, a Unix socket or pipe will be used.
add unix_socket='path_to_socket' where path_to_socket should be the path of the MySQL socket, e.g. /var/run/mysqld/mysqld2.sock
Make sure that the mysql server is listening for tcp connections, which you can do with netstat -nlp (in *nix). This is the type of connection you are attempting to make, and db's normally don't listen on the network by default for security reasons. Also, try specifying --host=localhost when using the mysql command, this also try to connect via unix sockets unless you specify otherwise. If mysql is not configured to listen for tcp connections, the command will also fail.
Here's a relevant section from the mysql 5.1 manual on unix sockets and troubleshooting connections. Note that the error described (2002) is the same one that you are getting.
Alternatively, check to see if the module you are using has an option to connect via unix sockets (as David Suggests).
I had this issue where the unix socket file was some place else, python was trying to connect to a non-existing socket. Once this was corrected using the unix_socket option, it worked.
Mysql uses sockets when the host is 'localhost' and tcp/ip when the host is anything else. By default Mysql will listen to both - you can disable either sockets or networking in you my.cnf file (see mysql.com for details).
In your case forget about the port=3000 the mysql client lib is not paying any attention to it since you are using localhost and specify the socket as in unix_socket='path_to_socket'.
If you decided to move this script to another machine you will need to change this connect string to use the actual host name or ip address and then you can loose the unix_socket and bring back the port. The default port for mysql is 3306 - you don't need to specify that port but you will need to specify 3000 if that is the port you are using.
As far as I can tell, the python connector can ONLY connect to mysql through a internet socket: unix sockets (the default for the command line client) is not supported.
In the CLI client, when you say "-h localhost", it actually interprets localhost as "Oh, localhost? I'll just connect to the unix socket instead", rather than the internet localhost socket.
Ie, the mysql CLI client is doing something magical, and the Python connector is doing something "consistent, but restrictive".
Choose your poison. (Pun not intended ;) )
Maybe try adding the keyword parameter unix_socket = None to connect()?

Categories

Resources