python used sshtunnel can't connect to mysql - mysql

I'm trying to use sshtunnel and MySQLdb in python2.7 to tunnel my connection and facing following problem:
I used Sequel Pro to connect mysql was OK, but the python code did not work!
Sequel Pro is like this:
connect info
and code is like this:
`from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('2.2.2.2', 22),
ssh_username='name2',
ssh_password='mypassword',
remote_bind_address=('127.0.0.1', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='name1',
password='mypassword',
host='1.1.1.1',
database='mydata',
port=3306)
I searched some example code like:
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
(_host, _ssh_port),
ssh_username=_username,
ssh_password=_password,
remote_bind_address=(_remote_bind_address, _remote_mysql_port),
local_bind_address=(_local_bind_address, _local_mysql_port)
) as tunnel:
connection = MySQLdb.connect(
user=_db_user,
password=_db_password,
host=_local_bind_address,
database=_db_name,
port=_local_mysql_port)
I want to know that did I do the right way to built ssh or connect to mysql? Thanks for help!
update:
the error message:
2017-06-15 17:52:58,415| ERROR | Could not connect to gateway 1.1.1.1:22 : 110
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1483, in __enter__
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1225, in start
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1037, in _raise
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway

Update your code to add the local_bind_address:
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('2.2.2.2', 22),
ssh_username='name2',
ssh_password='mypassword',
remote_bind_address=('127.0.0.1', 3306),
local_bind_address = ('1.1.1.1', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='name1',
password='mypassword',
host='1.1.1.1',
database='mydata',
port=3306)
Unless you specify your Localhost (as '1.1.1.1' in your case) & Port; MYSQL service will not be available for the localhost.
I Hope this helps.

Related

Why do I get TCP/IP error when trying to create DB in my Lambda?

So I'm trying to deploy my Django project using lambda, with zappa. I'm using MySQL for DB engine. Now after doing some research, I realized that I needed to create a custom Django command to create DB, since I'm using MySQL. So I created crate_db command, zappa updated, then ran zappa manage dev create_db. Then I got this error: 2004 (HY000): Can't create TCP/IP socket (97)
below is my create_db.py file, for your information.
import sys
import logging
import mysql.connector
import os
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
rds_host = os.environ.get("MY HOST")
db_name = os.environ.get("")
user_name = os.environ.get("MY USERNAME")
password = os.environ.get("MY PASSWORD")
port = os.environ.get("3306")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class Command(BaseCommand):
help = 'Creates the initial database'
def handle(self, *args, **options):
print('Starting db creation')
try:
db = mysql.connector.connect(host=rds_host, user=user_name,
password=password, db="mysql", connect_timeout=10)
c = db.cursor()
print("connected to db server")
c.execute("""CREATE DATABASE bookcake_db;""")
c.execute("""GRANT ALL ON bookcake_db.* TO 'ryan'#'%'""")
c.close()
print("closed db connection")
except mysql.connector.Error as err:
logger.error("Something went wrong: {}".format(err))
sys.exit()
Any ideas? Thanks.

How to change the authentication configuration of mysql connector to python?

I was trying to connect MySQL with python via the following code.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="qwerty",
auth_plugin="mysql_native_password"
)
print(mydb)
It gave me the following error:-
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
My connector version is:-
C:\Users\samar>pip install mysql-connector-python
Requirement already satisfied: mysql-connector-python in c:\users\samar\anaconda3\lib\site-packages (8.0.21)
import pymysql
host="localhost"
user="root"
passwd="qwerty"
db="<give db name"
def dbConnectivity(host,user, passwd, db):
try:
db = pymysql.connect(host=host,
user=user,
passwd=passwd,
db=db)
cursor = db.cursor()
print("Great !!! Connected to MySQL Db")
return cursor
except pymysql.Error as e:
print("Sorry !! The error in connecting is:" + str(e))
return str(e)
dbConnectivity(host,user,passwd,db)

Not able to connect to MySQL and PostgreSQL

I tried to use Jupiter notebook to connect MySQL and PostgreSQL. I don't know why it did not work anymore. The error message is "ERROR:root:Internal Python error in the inspect module".
Below is the traceback from this internal error.
In the beginning, I have no problem using sqlite3 to link database
Here is my code using squlite3
pitchfork_db = sqlite3.connect("pitchfork.db")
reviews.to_sql('reviews', pitchfork_db, index=False, if_exists='replace')
artists.to_sql('artists', pitchfork_db, index=False, if_exists='replace')
content.to_sql('content', pitchfork_db, index=False, if_exists='replace')
genres.to_sql('genres', pitchfork_db, index=False, if_exists='replace')
labels.to_sql('labels', pitchfork_db, index=False, if_exists='replace')
years.to_sql('years', pitchfork_db, index=False, if_exists='replace')
I can perform the query I want to
pitchfork_cursor = pitchfork_db.cursor()
pitchfork_cursor.execute("SELECT title, artist, score FROM reviews WHERE
score=10")
colnames = [x[0] for x in pitchfork_cursor.description]
pitchfork_df = pitchfork_cursor.fetchall()
pd.DataFrame(pitchfork_df, columns=colnames)
I got error message using MySQL:
"Traceback (most recent call last):
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it"
Here is my code to MySQL:
import mysql.connector
mysqlpassword = os.getenv("mysqlpassword")
dbserver = mysql.connector.connect(
user='root',
passwd=mysqlpassword,
host="localhost"
)
I got error message using PostgreSQL:
"Traceback (most recent call last):
psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting"
Here is my code to PostgreSQL
import psycopg2
pgpassword = os.getenv("pgpassword")
dbserver = psycopg2.connect(
user='postgres',
password=pgpassword,
host="localhost"
)
dbserver.autocommit = True
I stuck here for several hours, any comments will be great! Thank you!

Query my database on AWS over an SSH tunnel with Pandas

I am trying to query to my database running on AWS over an SSH tunnel with Pandas. But I fail login. Also there is one key that I use to connect on SQL client (Sequel Pro) that I don't know how to use in my python code.
This is the key: heroes-us-west-1-master.cheme3bzdejb.us-west-1.rds.amazonaws.com
This is my code:
with SSHTunnelForwarder(
(host, 22),
ssh_username=ssh_username,
ssh_private_key=ssh_private_key,
remote_bind_address=(localhost, 3306)
) as server:
conn = db.connect(host=localhost,
port=server.local_bind_port,
user=user,
passwd=password,
db=database)
return pd.read_sql_query(q, conn)
df = query("SELECT stores.name, stores.address\
FROM stores;")
This is the error message:
Traceback (most recent call last):
File "connection.py", line 32, in <module>
FROM stores;")
File "connection.py", line 22, in query
remote_bind_address=(localhost, 3306)
File "/Users/Solal/Desktop/SQL/venv/lib/python3.6/site-packages/sshtunnel.py", line 904, in __init__
logger=self.logger
File "/Users/Solal/Desktop/SQL/venv/lib/python3.6/site-packages/sshtunnel.py", line 1095, in _consolidate_auth
raise ValueError('No password or public key available!')
ValueError: No password or public key available!

MySQLdb in Python: "Can't connect to MySQL server on 'localhost'"

I have installed MySQLdb for Python and I am able to import MySQLdb. Now I try to connect to the MySQL Community Server on my local machine, using this code:
db=MySQLdb.connect(
host="localhost",
user="br_admin",
passwd="blabla",
db="br_brain"
)
This code fails with this error:
Traceback (most recent call last):
File "<pyshell#22>", line 5, in <module>
db="brainse_brain"
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
How do I resolve this error?
Make sure to provide the proper host and port:
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'yourdbname',
'USER': 'root',
'PASSWORD': 'your password',
'HOST': '127.0.0.1',
'PORT': '3306',
},
This is my settings.py file config for my django app.
Same for you please take host "127.0.0.1" and port "3306".
This might solve your problem.
And for python idle I've tested like...
>>> import MySQLdb
>>> Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="yoruname", passwd="yourpwd", db="test")
>>> Cursor = Con.cursor()
>>> sql = "SELECT * FROM test.testing"
>>> Cursor.execute(sql)
2L
I had the same trouble too, I'm working on a Windows of 64 bits, and the solution just was changing the host variable value. I had set "localhost" when the correct value have to be "127.0.0.1". However, when I'm working on Windows of 32 bits. I can set "localhost" or "127.0.0.1" in the host variable value and no matter, my django's project runs perfectly.
This will work fine :
db = MySQLdb.connect(host="127.0.0.1",user="db_username",passwd="db_password",db="db_name")
or
db= MySQLdb.connect("127.0.0.1","db_username","db_password","db_name")
In Windows 32, if you set host as 127.0.01 it gives the down error:
OperationalError: (2005, "Unknown MySQL server host '127.0.01' (0)")
But if you set host as 127.0.0.1 then you get no error.
If you are using windows you should specify the IP to "127.0.0.1", using "localhost" will give you that error 2003. On Ubuntu I had no problem.
1.Go to MySQL workbench
2.On the task bar above, click on server->and then click on Startup/Shutdown
3.On the screen, click on Start the server and you will get logs of server starting and running
- DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dataflair',
'USER':'root',
'PASSWORD':'',
'HOST':'127.0.0.1',
'PORT':'3306',
'OPTIONS':{
'init_command':"SET sql_mode=STRICT_TRANS_TABLES" }