Python-PostgreSQL: How to connect database via network IP - python

For my Django project I am using 'postgresql_psycopg2' and my DB is residing at a common server on the network. How can I connect to that DB using the IP address as 'host' like we do in MySQL? I have tried but it always shows the following error:
OperationalError at /
could not connect to server: Connection refused
Is the server running on host "" and accepting TCP/IP connections on port 5432?

Your problem is not related to Django, you just need to simply put the database server's ip in DATABASES['default']['host'], as you did.
The problem is postgresql denies remote access by default. You have to first edit the pg_hba.conf file on your database server and put a line like this in it:
host db_name user_name 192.168.1.1/32 md5
where you put your target database and user (same as those you enter in django settings) and specify the ip range of the allowed hosts to connect to that database via that user. Then you restart postgresql and now you can remotely connect to the your database. Also check if there isn't any firewall blocking you to access that port on the database server.
For more detailed instructions, see [1] or [2].

Related

Redshift Psycopg2 connection timeout - endpoint ip address is different

I am trying to connect to a free tier redshift cluster through a python script on a local machine, and keep getting the following error:
> psycopg2.OperationalError: connection to server at "<clusterendpoint>" (<clusterip>), port 5439 failed: Connection timed out (0x0000274C/10060)
Is the server running on that host and accepting TCP/IP connections?
I am using psycopg2 using the following code:
rs_conn = psycopg2.connect(
dbname= dbname,
user= username,
password= password,
host = endpointurl,
port = port)
My VPC is publicly available. I have tried adding my ip to the security group, and have also tried adding 0.0.0.0/0 to the security group, but haven't had any luck.
I used boto3 describeclusters() to investigate the problem further, and I did notice that neither the public nor private ip matched the ip shown in the error above associated with the endpoint url. Is that normal? I know that the endpoint url is correct.
Is there a better way to investigate this issue that will give me a better idea as to where the connection is going wrong?

mysql connector error 1130: host not allowed to connect to this MySQL server

I just upgraded to Verizon Fios internet this morning. I have a python script that accesses a database on a MySQL (mariadb) server on a raspberrypi (both are on the same network). It worked with my old internet/IP address, however now I am getting:
mysql.connector.errors.DatabaseError: 1130: Host 'my_computer_name.myfiosgateway.com' is not allowed to connect to this MySQL server
Steps I took leading up to error:
Confirmed new IP address of computer running the script
Changed IP address in configuration file that the python script uses to new IP address
I created a new user in the mysql server with the new host IP address of the laptop running the script
Granted all privileges to the new user on the database on the server
Flushed privileges
Restarted the mysql server
I'm not sure why the error is returning the computer's name, and not the IP address, but I even did the above steps with the exact host name returned in the error and it's still not working. I also compared the GRANTS on the MySQL server from the old IP address to the new one, and they are the same.
I'm able to ping the raspberrypi from my laptop with no issues.
Am I forgetting something? Is there a setting I may have to change on my router? That's the only thing that has changed from before when the script would work.
dbConfig.py
dbConfig = {
'host': 'xxx.xxx.x.xxx',
'database': 'NHL',
'user': 'greg',
'password': 'xxxxxx',
}
Script that accesses database
import dbConfig as guiConfig
import csv
import time
# connect to server
conn = mysql.connect(**guiConfig.dbConfig)
The bind-address in my .cnf file is commented out.
Is it possible that the Laptop running the script has another IP address?
Since the TCP/IP connection to the database works, there must be something wrong with the created MariaDB user or it's privileges. You could set the following parameter in the my.cnf in order to skip the DNS resolving. This improves the connection performance and it seems to confuse you. You should then see the Source IP address of the connection.
[mysqld]
skip-name-resolve

How to setup ssh tunnel dynamically in python?

I am trying to build a tunnel to then connect to an Oracle DB, but tunnel cannot be opened. Error is the following:
ERROR | Problem setting SSH Forwarder up: Couldn't open tunnel localhost:1521 <> XXXXXXXXX:1521 might be in use or destination not reachable.
sshtunnel.HandlerSSHTunnelForwarderError: An error occurred while opening tunnels.
My code is set as:
self.tunnel = sshtunnel.SSHTunnelForwarder((conn_data['gateway'], int(conn_data['gateway_port'])),
ssh_username=conn_data['username'],
ssh_password=password,
remote_bind_address=(conn_data['remote_bind'],
int(conn_data['remote_port'])),
local_bind_address=(conn_data['local_bind'],
int(conn_data['local_port'])))
The code works fine if I am inside the network of the company I work for. But if I am connected through VPN, I get the above error. My guess is that the VPN is built over the same tunnel.
I tried changing the local_port and removing the local bind, but if I do that, I get the error:
cx_Oracle.DatabaseError: ORA-12541: TNS:no listener
So, how can I dynamically set the port of SSHTunnelForwarder so it can access my DB through my already set VPN?
Note: changing the VPN's configuration or not using it is not an option.
Problem solved. The issue was that my VPN was using the same port as me (which caused the first error), and my Oracle connection was pointing to this port also (what caused error ORA-12541).
To solve it, I had to change conn_data['local_port'] to another port and set the port of my oracle connection to this same port:
self.tunnel = sshtunnel.SSHTunnelForwarder((conn_data['gateway'],
int(conn_data['gateway_port'])),
ssh_username=conn_data['username'],
ssh_password=password,
remote_bind_address=(conn_data['remote_bind'], int(conn_data['remote_port'])),
local_bind_address=(conn_data['local_bind'], 1234))
self.connection.connect(conn_data['host'],
port=1234,
username=conn_data['username'],
password=password,
look_for_keys=False)

Python: Using 'Null' for mysql.connector's port argument

I have a mysql database and I fetch it via a domain like www.mydomain-database.com. this domain is given by a company for accessing my database by phpmyadmin. When I browse this domain, it fetches phpmyadmin login page.
I try to connect to this database by the following code:
db = mysql.connector.connect(
host = "www.mydomain-database.com",
user = "root",
passwd = "**",
database = "database",
charset = 'utf8', use_unicode=True
)
When I run this, I get the following exept:
Can't connect to MySQL server on 'https://www.mydomain-database.com:3306' (-2 Name or service not known)
As you can see, connector adds port 3306 to my host; but the url with this port is not valid & it doesn't fetch the phpmyadmin!
So, for canceling that change, I added the port = "" as an argument for my connection but I got another error that mentioned the port must be integer!
Now the question is, how can I remove that port number when connector tries to connect the host?
You have to supply a port. By default MySQL uses port 3306. If your MySQL instance is using a different port, then you can specify that port in the settings.
Do you have access to the MySQL instance?
If so you can try and run:
mysql> SHOW GLOBAL VARIABLES LIKE 'PORT';
to get your port number.
However, your error message refers to server https://
that is not normal, there should not be any reference to https://
Can you check your code in your app and make sure that
host = "www.mydomain-database.com"
and not
host = "https://www.mydomain-database.com"

Remote connection issues with psycopg2 and postgresql

I'm trying to connect to a postgresql database using the following python code:
try:
conn = psycopg2.connect("host = '10.47.65.237' dbname = 'testDB' user = 'pi' password = 'raspberry'")
except:
print("Unable to connect to testDB at 10.47.65.237. Sending Alert.")
This code works with localhost 127.0.0.1 but when I go to a different machine and try to run it with its ip above it won't connect.
Things I've done:
1. Port 5432 is open
2. edited postgresql.conf by adding the line "listen_addresses='10.47.65.138'"
3. edited pg_hba.conf by adding the following configuration "host all all 10.47.65.138 md5"
Any other things I could try or I'm missing?
Running telnet 10.47.65.237 5432 on the client should result in a Connection Refused error, which indicates that the problem has nothing to do with psycopg2.
You have misconfigured the server. listen_addresses controls which IPs the server will answer on, not which IPs the server will permit connections from. Your server's postgresql.conf should have either listen_addresses='10.47.65.237' or listen_addresses='*'. Edit the configuration and restart PostgreSQL on the server, then you should be able to connect successfully using telnet and psycopg2.

Categories