I'm tring to understand what I should do in order to connect to a remote MySQL server using SSH.
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
('192.168.0.60', 22),
ssh_password="MySSHPASSWORD",
ssh_username="MUSSHUserName",
remote_bind_address=('192.168.0.30', 3306)) as server:
conn = MySQLdb.connect(user='UserNameOnSQLSERVER', passwd='PasswordOnSQLSERVER', host='192.168.0.60', db='myDB',
port=server.local_bind_port)
I've been able to connect to this server with the above configuration throw MySQL Workbench and Run queries and everything worked great
The problem is that when I'm trying to connect this DB by the above code I keep getting error:
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '192.168.0.60' (10060)")
I also tried to change the ip in MySQLdb.connect to be
conn = MySQLdb.connect(user='kiboUser', passwd='Lb24#db30#kL68', host='192.168.0.60', db='dbKiboDashboard',
port=server.local_bind_port)
and I got the following error:
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '192.168.0.30' (10060)")
Can please someone help me understand what im doing wrong
Thanks
remote_bind_address is the one you are tunneling into. Make sure to verify the server's TCP port that is listening.
To verify this, you could try the command
netstat
or
netstat -tln
This should work:
with SSHTunnelForwarder(
('ServerIP', sshport), #The server's IP and SSH port
ssh_password="MySSHPASSWORD",
ssh_username="MUSSHUserName",
remote_bind_address=('127.0.0.1', 3306)) as server: #The server's TCP IP and port, you're tunneling
conn = MySQLdb.connect(user='UserNameOnSQLSERVER', passwd='PasswordOnSQLSERVER', host='127.0.0.1',
port=server.local_bind_port) #Your TCP IP and port (your end of the tunnel)
Related
I want to create a temporary MySQL database for unit testing in Python. I decided to go with docker as the tests will be run on different machines.
As a first thing I run the container:
client = docker.from_env()
container = client.containers.run("ubuntu/mysql", detach=True, ports={3306:3307},environment={
'MYSQL_USER':'mysqluser',
'MYSQL_PASSWORD':'password',
'MYSQL_DATABASE':'mydb',
})
print('Container Started : {}'.format(container.status))
And then I try to connect using SQLAlchemy:
engine = sa.create_engine(f'mysql+pymysql://mysqluser:password#localhost:3307/mydb')
engine.connect()
which returns:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
EDIT
After putting sleep(10) after container.run, the response is different:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
Do you know what I'm doing wrong?
What I want to do is to connect to MySQL database on port 3307 (as one server already runs on the host). Then I want to create and populate a table.
EDIT2
Switching ports to {3307:3306} returns error:
docker.errors.APIError: 500 Server Error for http+docker://localhost/v1.41/containers/67a04b384bf3d39407881d4dfc73961932a3ce72fe8dc82c3cd6aedd57da2821/start: Internal Server Error ("driver failed programming external connectivity on endpoint hopeful_leakey (97840eb42d2c09b5e9754b634481d8e048c57ba2de8ffc10b34261de2f76600b): Error starting userland proxy: listen tcp4 0.0.0.0:3306: bind: address already in use")
I have problem to connect to my postgreSQL database.
I have databasename, password, hostname, port and I use this:
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
But I got error like this:
Is the server running on host "...." and accepting TCP/IP connections on port 5432
I don't know if I used correctly host, I insert the value of hostname.
What is the difference between hostname and host? Anyone could help me?
psycopg2.connect(dbname=dbname, user=user, password=password, host=postgres_address, port=postgres_port)
This is working example to connect, you must define early dbname, user, password, postgres_address. If you have connection error, you can use ping for testing connection and telnet for testing openning port. Or you can use Beaver for test connection to postgres server.
Most likely your database has a firewall, be sure to whitelist the IP you are trying to connect from.
Difference of host and hostname
The difference of host and hostname really depends on the context. In your context of psycopg2 and PostgreSQL connection, the host normally means the IP address of the PostgreSQL server or the resolvable name of the PostgreSQL server such as DNS name if it has. If you are running linux server, the output of command hostname is unlikely to work in your case.
psycopg2 connection
Your connection string looks OK. But I will suggest you to use below connection format:
import psycopg2
try:
connection = psycopg2.connect(user = "sysadmin",
password = "pynative##29",
host = "127.0.0.1",
port = "5432",
database = "postgres_db")
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
You should use the IP address as the host value.
Troubleshooting
In the case of connection error, you should use other tools to test the connection of PostgreSQL server such as psql, pgAdmin4 or DBeaver.
You can also use telnet or netcat tools to test the network connection of PostgreSQL server, such as
telnet PostgreSQL_ip_address 5432
nc -v PostgreSQL_ip_address 5432
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.
I've tried to use Peewee with sshtunnel to connect to a remote mysql db:
with SSHTunnelForwarder(
('server.pt', 9922),
ssh_password="pass_ssh",
ssh_username="user_ssh",
remote_bind_address=('localhost', 3306)) as server:
myDB = pw.MySQLDatabase("dbname", user="db_user", passwd="db_pass")
But I get an error
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
Could you help me?
You probably need to include the local port that you've bound the tunnel to from the server object:
myDb = pw.MySQLDatabase("dbname", host="localhost", port=server.local_bind_port, user="db_user", passwd="db_pass")
See here for an example.
I am trying to connect to remote database using SSH tunneling however I am getting error. I am not sure exactly what is wrong, as when I create ssh tunnel from command line I am able to access the database, however same is not working from python.
command to create ssh tunner, which is working fine.
ssh -L 30080:phpmyadmin-www:80 root#host
however, following code is not working.
def __init__(self, host="127.0.0.1", user="root", password="pass", db="database"):
sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG
with SSHTunnelForwarder(
('hubif-delphi-dev.qa-egnyte.com', 22),
ssh_private_key="/home/egnyte/.ssh/id_rsa",
ssh_username="root",
remote_bind_address=('host', 80),
local_bind_address=('127.0.0.1', 30080)) as server:
print "successfully connected to ssh"
con = MySQLdb.connect(user=user, passwd=password, db=db, host='127.0.0.1', port=server.local_bind_port)
self.cur = con.cursor()
I am getting following error, while trying to create MySQL connection.
2017-03-06 10:20:23,509| ERROR | Secsh channel 0 open FAILED: Connection refused: Connect failed
2017-03-06 10:20:23,509| ERROR | Could not establish connection from ('127.0.0.1', 30080) to remote side of the tunnel
---------------------------------------- Stacktrace removed ----------------------------------------
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")