使用subprocess在Python中测试与MySQL的连接

1 投票
1 回答
2871 浏览
提问于 2025-04-18 01:06

我正在尝试在我的Python脚本中使用子进程和Bash命令来测试与MySQL的连接。我想确保用户提供的密码是正确的,然后再尝试连接并发送更多的MySQL命令。我知道通过导入MySQLdb可以很简单地做到这一点,但我想学习如何让这个方法有效。

这是我现在的代码:

root_password = getpass.getpass("Enter the password of the database root user: ")
try:
   subprocess.check_call("mysql -u root -p%s" % root_password, shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT)
except:
   print "Incorrect password provided."

当密码正确时,标准输入会停在那里等待进一步的提示,但我希望它能退出,这样我就可以执行以下命令:

mysql_cmd = 'mysql -u root -p{0} -Bse "CREATE DATABASE {1}; CREATE USER {2}@localhost IDENTIFIED BY \'{3}\'; GRANT SELECT, CREATE, INSERT, UPDATE, DELETE, ALTER, DROP, LOCK TABLES ON {1}.* TO {2}@localhost IDENTIFIED BY \'{3}\'; FLUSH PRIVILEGES;"'.format(root_password, database_name, database_user, database_password)
subprocess.call(mysql_cmd, shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT)

没错,你猜对了;我正在尝试把一个Bash脚本转换成Python代码。

1 个回答

0

来自 使用 Connector/Python 连接 MySQL:

import mysql.connector
from mysql.connector import errorcode

try:
    conn = mysql.connector.connect(user='root', password=password, 
                                   database='test') # MySQL 4.1+
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exists")
    else:
        print(err)
else:
    conn.close()

如果在输入正确密码后,mysql 命令显示了提示符,那么你可以使用 Popen.communicate() 来发送 exit 命令:

from subprocess import Popen, PIPE, DEVNULL, STDOUT

p = Popen(["mysql", "-u", "root", "-p", password],
          stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(b"exit")
if p.returncode != 0:
    print('incorrect password')

请记住,评论中提到的安全问题

撰写回答