top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

python script that connects to mySQL DB ask for a password

+1 vote
610 views

Is there a way to make python script that connects to mySQL DB ask for a password on the:

conn = mdb.connect(host, user)
posted Dec 16, 2013 by Sonu Jindal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

may be you think some like this:

import MySQLdb

dsn = {
 'host': "127.0.0.1",
 'user': "root",
 'passwd': "",
 'port': 3306,
 'db': "test"
}

dsn['passwd'] = raw_input("Enter password for %s: " % (dsn['user']))

mysql = MySQLdb.connect(**dsn)
cursor = mysql.cursor(MySQLdb.cursors.DictCursor)

but at this way the password what you type will showing!

answer Dec 16, 2013 by Dewang Chaudhary
To avoid that use getpass.getpass() instead of raw_input().
http://docs.python.org/2/library/getpass.html
Similar Questions
+3 votes

I am using Python 2.7, MySQl 5.5, mysqldb(driver) and trying to connect to the mysql db using Python.

What I have tried

import MySQLdb
db = MySQLdb.connect(host="localhost",
                     user="root", # username
                      passwd="xxxxx", #  password
                      db="TEST") # name of the data base

Even tried 127.0.0.1 as local host

#ERROR
Traceback (most recent call last):
  File "C:/Python27/connect.py", line 6, in <module>
    db="prakash") # name of the data base
  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)")

I am new to python, please help how to proceed?

0 votes

I am trying to use mitmproxy behind a company proxy that requires a user/password login.

The setup is: Local PC's browser -> mitmproxy (on local PC) -> company proxy -> internet.

Based on this SO thread, this is how you use mitmproxy within a Python program. This example works fine when there's no proxy.

from mitmproxy.options import Options
from mitmproxy.proxy.config import ProxyConfig
from mitmproxy.proxy.server import ProxyServer
from mitmproxy.tools.dump import DumpMaster

class Addon(object):
    def __init__(self):
        pass

    def request(self, flow):
        # examine request here 
        pass

    def response(self, flow):
        # examine response here
        pass


if __name__ == "__main__":

    options = Options(listen_host='0.0.0.0', listen_port=8080, http2=True)
    m = DumpMaster(options, with_termlog=False, with_dumper=False)
    config = ProxyConfig(options)

    m.server = ProxyServer(config)
    m.addons.add(Addon())

    try:
        print('starting mitmproxy')
        m.run()
    except KeyboardInterrupt:
        m.shutdown()

Assuming the company proxy is at IP "1.2.3.4" port 3128 and requires a login USER and PASSWORD, how can I change this script to have mitproxy use that proxy instead of going to the internet directly?

Addition info: I am not using mitmdump with the script-parameter to run this script. The goal is to run this from Python 3.8 with a pip-installed mitmproxy

+1 vote

I have kept all the create table SQL querys in a text file. Using readLines i am trying to execute the sql commands as per the code mentioned.

file=open("TABLES.txt","r")
for sql in file.readlines():
self.cursor.execute(sql)

But I am getting Error 1065 ' Query was empty'. More Importantly the tables are being created in the database. The text file is like this.

CREATE TABLE TUserDetails (FirstName VarChar(50) NOT NULL, LastName VarChar(50) NOT NULL, Email_Id VarChar(50) NOT NULL,Type VarChar(50) NOT NULL,Department VarChar(50) NOT NULL,NoOfIncorrectAttempt Integer NOT NULL,Deleted Bit NOT NULL,UserID VarChar(50) NOT NULL,CONSTRAINT TUserDetails_PK PRIMARY KEY CLUSTERED ( UserID ))

CREATE TABLE TRequests(RequestID VarChar(50) NOT NULL,UserID VarChar(50) NOT NULL,Status SmallInt NOT NULL,TimeOfRequest Timestamp NOT NULL,Deleted Bit NOT NULL,Priority Integer NOT NULL,CONSTRAINT TRequests_PK PRIMARY KEY CLUSTERED ( RequestID ))

CREATE TABLE TUserDetailUSERs(UserID VarChar(50) NOT NULL, Type VarChar(50) NOT NULL,Deleted Bit NOT NULL,TimeOfCreation Timestamp NOT NULL,TimeLastUpdated Timestamp NOT NULL,Active Bit NOT NULL,PWDID VarChar(50) NOT NULL,RoleID VarChar(50) NOT NULL,OrganisationID Integer NOT NULL,CONSTRAINT TUserDetailUSERs_PK PRIMARY KEY CLUSTERED ( UserID ))

CREATE TABLE TOrganisations(OrganisationID Integer NOT NULL,OrganisationName VarChar(50) NOT NULL,TimeOfCreation Timestamp NOT NULL,TimeLastUpdated Timestamp NOT NULL, Deleted Bit NOT NULL, CONSTRAINT TOrganisations_PK PRIMARY KEY CLUSTERED ( OrganisationID ))

CREATE TABLE TPWDs(PWDID VarChar(50) NOT NULL,Code VarChar(50) NOT NULL,DateOfCreation Timestamp NOT NULL,DateLastUpdated Timestamp NOT NULL,TimeOfDeletion Timestamp NOT NULL, CONSTRAINT TPWDs_PK PRIMARY KEY CLUSTERED ( PWDID ))

CREATE TABLE TRoles(RoleID VarChar(50) NOT NULL,RoleName VarChar(50) NOT NULL,Description VarChar(50) NOT NULL,TimeOfCreation Timestamp NOT NULL, RoleLastUpdated VarChar(50) NOT NULL, Deleted Bit NOT NULL, CONSTRAINT TRoles_PK PRIMARY KEY CLUSTERED ( RoleID ))

I checked running each sql query individually, and it is qorking file. Now although the tables are being created in the database but i am getting error 1065 as mentioned above

+1 vote

$ python -m pip install MySQL-python

Collecting MySQL-python
 Downloading MySQL-python-1.2.5.zip (108kB)
 100% | –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ –ˆ| 112kB 260kB/s
 930 [main] python2.7 12948 child_info_fork::abort: address space needed by 'datetime.dll' (0x870000) is already occupied
 Error [Errno 11] Resource temporarily unavailable while executing command python setup.py egg_info
Exception:
Traceback (most recent call last):
 File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
 status = self.run(options, args)
 File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 324, in run
 requirement_set.prepare_files(finder)
 File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 380, in prepare_files
 ignore_dependencies=self.ignore_dependencies))
 File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 634, in _prepare_file
 abstract_dist.prep_for_dist()
 File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 129, in prep_for_dist
 self.req_to_install.run_egg_info()
 File "/usr/lib/python2.7/site-packages/pip/req/req_install.py", line 439, in run_egg_info
 command_desc='python setup.py egg_info')
 File "/usr/lib/python2.7/site-packages/pip/utils/__init__.py", line 667, in call_subprocess
 cwd=cwd, env=env)
 File "/usr/lib/python2.7/subprocess.py", line 390, in __init__
 errread, errwrite)
 File "/usr/lib/python2.7/subprocess.py", line 917, in _execute_child
 self.pid = os.fork()
OSError: [Errno 11] Resource temporarily unavailable

Anyone hit similar issue?

0 votes

I am having trouble matching Python data types with those of MySQL. MySQL has about 7 basic data types including Blobs, Binaries, etc. It also has a rich selection of geometry types. In addition, types like INT have 7 or 8 different options like Primary Key, zero fill, auto inc, etc. I can't seem to find anything in python to match these. I am trying to build a model.py for an existing database that was created with MySQL Workbench.

I do not wish to use anything other than MySQL because of the complexity of my storage needs (searchable text, PDF, Audio, Video and Photos). The text searches will often be word phrase searches through thousands of documents. I need the speed and the data type flexibility.

How do I build or modify a model.py to do this. I really don't want to write a model.py manually. That would really be a major pain. Workbench to the database an import to Django and edit is my choice. Unfortunately, the model.py produced has lost most of the functionality of the original database and I can't seem to figure out how to fix it.

...