在ubuntu上安装mysql服务器后,发现数据库 root 密码不对,看了博客,知道了原因。
但是感觉挺麻烦的,有没有一劳永逸的方法呢,那就是自己写个脚步,以后直接使用就好了。
import pymysql
import sys
import os
#############
# 获取密码
# 参考: https://www.cnblogs.com/super-zhangkun/p/9435974.html
#############
if True: # 这里是想在后期做个扩展,加了一个if 判断。
cnf_file = '/etc/mysql/debian.cnf'
try:
with open(cnf_file,'r') as fr:
print('success')
for l in fr.readlines():
lk = l.split('=')
if lk[0].strip() == 'host':
ms_host = lk[1].strip()
elif lk[0].strip() == 'user':
ms_user = lk[1].strip()
elif lk[0].strip() == 'password':
ms_password = lk[1].strip()
except Exception as e:
print('error open %s'%cnf_file)
print(e)
sys.exit(1)
# 修改 root 密码
db = pymysql.connect(ms_host, ms_user, ms_password, 'mysql')
cursor = db.cursor()
passwd = input('请输入密码:') # 这里可以改进成暗文,不显示出来
sql_str = 'update user set authentication_string=PASSWORD("%s") where user=\'root\';'%passwd
cursor.execute(sql_str)
sql_str = 'update user set plugin="mysql_native_password";'
cursor.execute(sql_str)
sql_str = 'flush privileges;'
cursor.execute(sql_str)
db.close()
$ sudo /home/hocker/disks/diskA/programs/anaconda3/bin/python change_mysql.py
[sudo] password for hocker:
success
请输入密码:abc
/home/hocker/disks/diskA/programs/anaconda3/lib/python3.7/site-packages/pymysql/cursors.py:170: Warning: (1681, "'PASSWORD' is deprecated and will be removed in a future release.")
result = self._query(query)
#---------------------------- 分割线 ------------------------------
$ mysql -uroot -pabc
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.7.29-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
大体运行就是这样,没有毛病,但是得注意,sudo 的时候 要指明一个安装了 pymysql 的python路径。