Python--判断Mysql启动状态并人工干预下完成启动

功能点:

1、判断Mysql启动状态,如果停止,则启动Mysql服务

2、测试环境:win7_64bit系统,自动提示“需要提权UAC完成Mysql启动”点击“是(Y)”按钮即可,如果不处理这部分则运行时报错:“PermissionError: [WinError 5] 拒绝访问。”

3、兼容Python2.x和3.x,

注意事项:

  • Python3.x环境,在CMD或Pycharm运行功能正常;
  • Python2.x环境,只能在CMD下运行(我也没找到Pycharm下运行的办法)
  • 我的Mysql服务名字就叫MySQL80(Python脚本里MySQL80大小写无所谓)
  • 完全自动提权UAC启动Mysql服务的代码网上也有,但比较邪恶(危险)且需要评估风险,用在完全无人值守的情况还可以

代码如下:

 1 import os,subprocess,time
 2 import ctypes, sys
 3 def checkmysql():
 4     tasklist = []
 5     task = subprocess.Popen('tasklist /nh | find /i "MySQL"',stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
 6     for line in task.stdout.readlines():
 7         tasklist.append(line)
 8     if len(tasklist)==0:
 9         print('Mysql80 is stoped')
10         return False
11     elif len(tasklist)!=0:
12         print('Mysql80 is running...')
13         print('tasklist = ',tasklist)
14         return True
15 def is_admin():
16     try:
17         return ctypes.windll.shell32.IsUserAnAdmin()
18     except:
19         return False
20 
21 if is_admin():
22     if not checkmysql():
23         print('-----')
24         subprocess.Popen('net start mysql80', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
25         time.sleep(5)
26 else:
27     if sys.version_info[0] == 3:
28         ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
29     else:#in python2.x
30         ctypes.windll.shell32.ShellExecuteW(None, u"runas", (sys.executable).encode('utf-8'), (__file__).encode('utf-8'), None, 1)
启动Mysql服务

参考文章:https://blog.csdn.net/qq_17550379/article/details/79006655

posted @ 2019-01-31 17:08  kuzaman  阅读(1019)  评论(0编辑  收藏  举报