python: use 'MySQLdb' module to connect to remote mysql server - python

I have two virtual machines. One is used as Agent, One is used as Master. A Mysql Server is installed on Master(Mysql Client is forbidden to be installed on Master which means I can't use mysql command line on Master). The Mysql server has a default user 'root'. Now I want to write a python script which use 'MySQLdb' module on Agent. The test code is easy. just see as bellow:
#!/usr/bin/python
import MySQLdb
def main():
try:
conn=MySQLdb.connect(host=master ip,user='root',passwd='xxx',db='xxx',port=3306)
cur=conn.cursor()
count = cur.execute('select * from table')
print count
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
if __name__ == "__main__":
main()
however, when I execute it on Agent, there is an error:
Mysql Error 1045: Access denied for user 'root#Agent ip'(using password: YES)
So I don't know why the user is 'root#Agent ip', not the default user of Mysql server on Master. Anyone knows how to solve this problem?

There is a command named GRANT in MySQL. You have to grant permission for root#AgentIP (Where AgentIP is the IP of the system from which you have to access the db.)
The command to be run in the mysql client of the server:
GRANT ALL on mydb.* to 'root'#'YourIP' identified by 'YourPassword'
Only then the MySQL server running in the remote system will grant access to the database.
If not sure of the IP details, you can also specify 'root'#'%' ,
which will allow all requests from user named root from anywhere. This is not a recommended way, but there is such an option.

Related

What does 'DPY-6001: cannot connect to database' mean with python-oracledb?

With Python code that uses the
python-oracledb driver:
import oracledb
import os
un = os.environ.get("PYTHON_USERNAME")
pw = os.environ.get("PYTHON_PASSWORD")
cs = "localhost/doesnotexist"
c = oracledb.connect(user=un, password=pw, dsn=cs)
what does this error message mean?
DPY-6001: cannot connect to database. Service "doesnotexist" is not registered with the listener at host "localhost" port 1521. (Similar to ORA-12514)
The error means that Python successfully reached a computer (in this case
"localhost" using the default port 1521) that is running a database. However
the database service you wanted ("doesnotexist") doesn't exist there.
Technically the error means the listener doesn't know about the service at the
moment. So you might also get this error if the DB is currently restarting.
This error is similar to the ORA-12514 error that you would see when connecting
with python-oracledb in Thick mode, or might see with some other Oracle tools.
The solution is to use a valid service name, for example:
cs = "localhost/xepdb1"
You can:
Check and fix any typos in the service name you used
Check the hostname and port are correct
Ask your DBA for the correct values
Wait a few moments and re-try in case the DB is restarting
Review the connection information in your cloud console or cloud wallet, if you are using a cloud DB
Run lsnrctl status on the database machine to find the known service names

How do I overcome this sql connectivity error with python?

I am not able to connect to MySQL sever using python it gives and error which says
MySQLdb._exceptions.OperationalError: (1130, "Host 'LAPTOP-0HDEGFV9' is not allowed to connect to this MySQL server")
The code I'm using:
import MySQLdb
db = MySQLdb.connect(host="LAPTOP-0HDEGFV9", # your host, usually localhost
user="root", # your username
passwd="abcd13de",
db="testing") # name of the data base
cur = db.cursor()
cur.execute("SELECT * Employee")
for row in cur.fetchall():
print(row[0])
db.close()
This is an authorization problem not a connectivity problem. Is the db running locally? If not, confirm with the admin where it is hosted. If so, try changing the host parameter to 127.0.0.1?
As described here the admin can get the hostname by running:
select ##hostname;
show variables where Variable_name like '%host%';
If the connection was timing out you could try setting the connect_timeout kwarg but that's already None by default.

AWS Python Lambda with Oracle - OID Generation Failed

I'm trying to connect to an Oracle DB using AWS Lambda Python code.
My code is below:
import sys, os
import cx_Oracle
import traceback
def main_handler(event, context):
# Enter your database connection details here
host = "server_ip_or_name"
port = 1521
sid = "server_sid"
username = "myusername"
password = "mypassword"
try:
dsn = cx_Oracle.makedsn(host, port, sid)
print dsn
connection = cx_Oracle.Connection("%s/%s#%s" % (username, password, dsn))
cursor = connection.cursor()
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
error, = exc.args
print >> sys.stderr, "Oracle-Error-Code:", error.code
print >> sys.stderr, "Oracle-Error-Message:", error.message
tb = traceback.format_exc()
else:
tb = "No error"
finally:
print tb
if __name__ == "__main__":
main_handler(sys.argv[0], None)
If have already added all dependencies in "lib" folder, thanks to AWS Python Lambda with Oracle
When running this code, I'm getting:
DatabaseError: ORA-21561: OID generation failed
i've tried to connect using IP of the Oracle server and the name: same error.
Here is the output of the error
Oracle-Error-Code: 21561
Oracle-Error-Message: ORA-21561: OID generation failed
Traceback (most recent call last):
File "/var/task/main.py", line 20, in main_handler
connection = cx_Oracle.Connection("%s/%s#%s" % (username, password, dsn))
DatabaseError: ORA-21561: OID generation failed
For those who have successfully run the CX_Oracle in AWS Lambda Python, can you please help ?
Thanks
Ok, here is the explanation:
Oracle has a funny behavior where if the hostname given by hostname can't be resolved, it will fail connecting to the DB. Fortunately, in Linux, one can override the DNS entry for a session by writing an alias file in /tmp, then setting the environment variable HOSTALIASES to that file.
So adding this code to my function help to generate this file, and now I can successfully connect:
f = open('/tmp/HOSTALIASES','w')
str_host = os.uname()[1]
f.write(str_host + ' localhost\n')
f.close()
Hope it can help someone else !
See the following other question for the resolution to this problem.
sqlplus remote connection giving ORA-21561
Effectively the client requires a host name in order to generate a unique identifier which is used when connecting to the database.
The accepted solution for this correct, but please also be aware that the HOSTALIASES mechanism does require working DNS (as strange as it sounds).
I struggled with this for a few hours having implemented the accepted solution and realised that I was not permitting outbound DNS on the security group attached to by Lambda function VPC interface (my connection was by IP address to Oracle DB, so initially did not think this was required).

Connect on remote MySQL database through Python

I have tried the following script but unfortunately doesn't work. I am using a free MySQL database provider. Any ideas?
import MySQLdb
myDB = MySQLdb.connect(host="208.11.220.249",port=3306,user="XXXXX",passwd="XXXXX",db="XXXXX")
cHandler = myDB.cursor()
cHandler.execute("SHOW DATABASES")
results = cHandler.fetchall()
for items in results:
print items[0]
Currently, I am getting the following error:
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1044, "Access denied for user 'XXXXX'#'%' to database 'XXXXX'")
GRANT ALL
ON *.*
TO user#192.168.39.17 -- client ip address
IDENTIFIED BY 'pwd';
Edit
This is SQL that you'd run on the database in order to ensure that the user has access to everything. pwd is the user's password.
Basically, this answer assumes that the connection issue is a credentials issue.
This is what I would do
See if the port is actually open on that machine.
On the machine you are connecting from, open console/cmd/terminal and see if you can connect using mysql -u XXXX -h 208.11.220.249 -p. If your mysql client can not connect, then there is no way you can connect using python
You don't have permission for connecting to database with this user.
Follow these steps:
1.try connecting to mysql DB:
mysql -h208.11.220.249 -uXXXXX -pXXXXX XXXXX
2.If you don't have permission for connecting to DB ,try creating user that has remote permission
GRANT ALL
ON DB.* -- Database name
TO user#ip -- client ip address
IDENTIFIED BY 'pwd';
3.on the last check my.cnf . "bind-address" must be 0.0.0.0 If you want to connect all remote addresses.
open your database in mysql and type the following :
mysql> GRANT ALL ON *.* TO root#'x' IDENTIFIED BY 'Your-password'
where x is the ip address of the user that wants to access your db.
use this link for more information:
How to Allow MySQL Client to Connect to Remote MySQL server

MySQL error: 2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0"

I'm having an issue connecting to my local MySQL database using Python's MySQLdb library. The script has been working well previously, but I will occasionally get the MySQL error in the title. There seems to be no explanation for when the error occurs, and the script is always run from the same machine with the same arguments.
The MySQL server is running as a service on Windows XP SP3 using port 3306 (locally hosted phpMyAdmin works), and the script is run from an Ubuntu 10.04 guest operating system in Oracle VM VirtualBox.
I am currently working around this issue by opening a command prompt and executing 'net stop MySQL' then 'net start MySQL'. This allows me to run the script a few times again before resulting in the error, which I've been fixing by restarting the MySQL service.
As I am still making changes to the script, there are occasions when the script raises an exception and doesn't exit gracefully, though I do catch the exception and close the cursor and connection.
The code to connect to the database:
def __init__(self):
try:
print "Connecting to the MySQL database..."
self.conn = MySQLdb.connect( host = "192.168.56.1",
user = "guestos",
passwd = "guestpw",
db = "testdb")
self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
print "MySQL Connection OK"
except MySQLdb.Error, e:
print "MySQLdb error %d: %s" % (e.args[0],e.args[1])
raise
The full error generated when this happens is as follows:
MySQLdb error 2013: Lost connection to MySQL server at 'reading initial communication packet', system error: 0
Traceback (most recent call last):
File "search.py", line 45, in <module>
dataHandler = DataHandler()
File "/home/guestos_user/workspace/Search/src/data_handler.py", line 25, in __init__
db = "testdb")
File "/usr/lib/pymodules/python2.6/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 170, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")
sudo vi /etc/mysql/my.cnf
delete
bind-address = 127.0.0.1
then
sudo reboot now
That's it. Be aware that this will make your mysql server less secure as you are exposing it.
I have seen this happen when child processes try to share the same mysql connection id (solution = create new connections for each child process). I'm not sure if this is also possible when sharing connection objects with multiple threads.
However, that's only one of the many possible causes. See VVS's answer in MySQL Error 2013 for a list of troubleshooting resources.
Do you have in your MySQL server an acount called guestos#YOURIPADDRESS?
You must have an account to access to your MySQL server from YOURIPADDRESS!
For example:
Your IP address is 192.168.56.2; then you must create and account if not exist to access.
mysql> create user guestos#192.168.56.2 identified by 'guestpw';
The problem fixed for me just by restarting my mac. Though there might be a more specific fix for it.
I received a similar error when attempting to connect to my MySQL server remotely through a user with the sufficient permissions.
After editing the /etc/mysql/my.cnf file to include
[mysqld]
bind-address=xx.xx.xxx.xxx
where xx.xx.xxx.xxx is my local IP address, I began experiencing the exact same error as you. From there, I found an answer regarding this issue (answered by Coffee Converter) which worked for me, and can be found here: Lost connection to MySQL server at 'reading initial communication packet', system error: 0 on a windows machine
All I did to fix the issue for myself was edit the /etc/hosts.allow to include
mysqld: ALL: allow
Works great now! I hope this helped :)
Could you change the bind-address=localhost and restart MySQL server? Seems like this issue is related to yours: http://forums.mysql.com/read.php?152,355740,355742#msg-355742
Also this-
If MySQL port is wrong result is MySQL client error 2013 "Lost
connection ...". Note that this error also occurs if port forwarding
is disabled in SSH configuration (the configuration parameter
'AllowTcpForwarding' is set to 'no' in the 'sshd_config' file). It
(here) simply tells that there is no connection from SSH to MySQL for
some reason. But the mySQL client API 'thinks' there was one
connection and that is why is says 'Lost connection ...' and not
'Can’t connect...'. There was one successful connection - but not to
the MySQL server - to the SSH daemon only! But the MySQL client API is
not designed to 'see' the difference!
Refer this.
I run a windows server and from time to time the php-win.exe will load and stay in the processes list on the windows task manager.
If you know the host file is correct, then kill the php-win.exe process and restart iis iisreset
If you are running windows then your problem should be solved.
I've had the exact same mysql error (ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0=) and have resolved it by adding a newline to /etc/hosts.deny.
Possibility: your database is corrupted.
I encountered this situation when I was running an UPDATE statement on a specific row of a specific table. (Specifically, I was editing an item in a Django Admin site.) Most of the time the database worked just fine.
I finally resolved the problem by running:
OPTIMIZE TABLE `your_table`
After that everything was OK, no connection lost.
Conclusion:
The problem "Lost connection to MySQL server at 'reading initial communication packet'", sometimes "Can't connect to MySQL server on '127.0.0.1'", could possibly be resolved by running a full database optimization if the database is corrupted. For more info, read this.
Just to further extend the list of possible causes: it could also be as banal as wrong connection data/credentials. I encountered this error in conjunction with sqlalchemy:
sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0
In my code I connect to several different databases and once in a while it happens that I don't get the mapping between the db connections and their credentials (e.g. ip address of server, db-name, password etc.) right, which then also results in the 2013-error (in this case wrapped into an sqlalchemy operational error).
setting.py file set like:
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test2',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3308',
This bug report might be of interest to you. Don't know if this will help you, but some were able to solve it by using the name of the server rather than the ip address in the connection properties.

Categories