Python管理Windows服务小脚本


Posted in Python onMarch 12, 2018

本文实例为大家分享了Python管理Windows服务的具体代码,供大家参考,具体内容如下

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:        LinuxBashShellScriptForOps:ServiceControl.py
User:        Guodong
Create Date:    2016/10/14
Create Time:    17:57


Example of program with many options using docopt, control system service.
Usage:
 ServiceControl.py SERVICE_NAME SERVICE_ACTION
 ServiceControl.py SERVICE_ACTION SERVICE_NAME
 ServiceControl.py --version | -v
 ServiceControl.py --help | -h
Arguments:
 SERVICE_NAME service name
 SERVICE_ACTION service action in ["start", "stop", "restart", "status"]
Options:
 -h --help      show this help message and exit
 -v --version     show version and exit
"""
import sys
import codecs
import locale
import psutil
import win32serviceutil
import time
from collections import OrderedDict

from docopt import docopt

UNKNOWN = 0
STOPPED = 1
START_PENDING = 2
STOP_PENDING = 3
RUNNING = 4

status_code = {
  0: "UNKNOWN",
  1: "STOPPED",
  2: "START_PENDING",
  3: "STOP_PENDING",
  4: "RUNNING"
}


def get_system_encoding():
  """
  The encoding of the default system locale but falls back to the given
  fallback encoding if the encoding is unsupported by python or could
  not be determined. See tickets #10335 and #5846
  """
  try:
    encoding = locale.getdefaultlocale()[1] or 'ascii'
    codecs.lookup(encoding)
  except Exception:
    encoding = 'ascii'
  return encoding


DEFAULT_LOCALE_ENCODING = get_system_encoding()


# try:
#   result = result.decode(DEFAULT_LOCALE_ENCODING)
# except UnicodeDecodeError:
#   # UnicodeDecodeError - preventive treatment for non-latin Windows.
#   return ''

def is_iterable(source):
  if source is not None:
    try:
      iter(source)
    except TypeError:
      return False
    return True
  else:
    raise RuntimeError("argument cannot be None")


def status_service(service_name):
  try:
    result = win32serviceutil.QueryServiceStatus(service_name)[1]
    if result == START_PENDING:
      print "service %s is %s, please wait" % (service_name, status_code[result])
      time.sleep(2)
      return RUNNING
    elif result == STOP_PENDING:
      print "service %s is %s, please wait" % (service_name, status_code[result])
      time.sleep(2)
      return STOPPED
    else:
      return result if result is not None else 0
  except Exception as e:
    if e.message:
      raise RuntimeError(e.message)
    elif e.args:
      # print e.args
      args = list()
      for arg in e.args:
        if is_iterable(arg):
          args.append(unicode(eval(repr(arg)), 'gbk'))
        else:
          args.append(arg)
      print "Error:", args[-1], tuple(args)
      raise RuntimeError
    else:
      raise RuntimeError("Uncaught exception, maybe it is a 'Access Denied'") # will not reach here


def start_service(service_name):
  status = status_service(service_name)
  if status == STOPPED:
    pass
  elif status == RUNNING:
    print "service %s already started" % service_name
    return status

  try:
    print "starting %s" % service_name
    win32serviceutil.StartService(service_name)
  except Exception as e:
    if e.message:
      raise RuntimeError(e.message)
    elif e.args:
      # print e.args
      args = list()
      for arg in e.args:
        if is_iterable(arg):
          args.append(unicode(eval(repr(arg)), 'gbk'))
        else:
          args.append(arg)
      print "Error:", args[-1], tuple(args)
      raise RuntimeError
    else:
      raise RuntimeError("Uncaught exception, maybe it is a 'Access Denied'") # will not reach here
  return status_service(service_name)


def stop_service(service_name):
  status = status_service(service_name)
  if status == STOPPED:
    print "service %s already stopped" % service_name
    return status
  elif status == RUNNING:
    pass
  else:
    return status
  try:
    print "stopping %s" % service_name
    win32serviceutil.StopService(service_name)
  except Exception as e:
    if e.message:
      print e.message
    elif e.args:
      # print e.args
      args = list()
      for arg in e.args:
        if is_iterable(arg):
          args.append(unicode(eval(repr(arg)), 'gbk'))
        else:
          args.append(arg)
      print "Error:", args[-1], tuple(args)
      raise RuntimeError
    else:
      raise RuntimeError("Uncaught exception, maybe it is a 'Access Denied'") # will not reach here
  return status_service(service_name)


def restart_service(service_name):
  status = status_service(service_name)
  if status == START_PENDING or status == RUNNING:
    if status == START_PENDING:
      time.sleep(2)
    stop_service(service_name)
    status = status_service(service_name)
    if status == STOPPED or status == STOP_PENDING:
      if status == STOP_PENDING:
        time.sleep(2)
      return start_service(service_name)
  elif status == STOPPED or status == STOP_PENDING:
    print "service %s not running." % service_name
    return start_service(service_name)
  else:
    return status_service(service_name)


def do_service(service_name, service_action):
  # https://docs.python.org/2/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python
  # http://python.jobbole.com/82008/
  valid_action = ["start", "stop", "restart", "status"]
  maps = {
    "start": "start_service(service_name)",
    "stop": "stop_service(service_name)",
    "restart": "restart_service(service_name)",
    "status": "status_service(service_name)",
  }
  if service_name == "" or service_action == "":
    raise RuntimeError("service_name and service_action cannot be empty.")
  if service_action in valid_action:
    return eval(maps[service_action])
  else:
    raise RuntimeError("bad service_action '%s', valid action is %s" % (service_action, valid_action))


def list_service():
  service_dict = OrderedDict()
  for service in psutil.win_service_iter():
    service_dict[service.name()] = service.display_name()
  return service_dict


def is_valid_service_name(service_name):
  if service_name.lower() in [name.lower() for name, display_name in list_service().items()]:
    return True
  else:
    return False


if __name__ == '__main__':
  SERVICE_ACTION = ["start", "stop", "restart", "status"]
  arguments = docopt(__doc__, version='1.0.0rc2')

  if arguments['SERVICE_NAME'] != "" and arguments['SERVICE_ACTION'] != "":
    if arguments['SERVICE_ACTION'] in SERVICE_ACTION:
      pass
    elif arguments['SERVICE_NAME'] in SERVICE_ACTION:
      tmp = arguments['SERVICE_ACTION']
      arguments['SERVICE_ACTION'] = arguments['SERVICE_NAME']
      arguments['SERVICE_NAME'] = tmp
    else:
      print __doc__
      sys.exit(1)

    if is_valid_service_name(arguments['SERVICE_NAME']):
      pass
    else:
      raise RuntimeError("server '%s' not exist" % arguments['SERVICE_NAME'])

    return_code = do_service(arguments['SERVICE_NAME'], arguments['SERVICE_ACTION'])

    try:
      print status_code[return_code]
    except KeyError:
      print "return_code is %s." % return_code
  else:
    print __doc__
    sys.exit(1)

# TODO(Guodong Ding) run a command as administrator with administrative privilege, use 'runas' command?
state_command = "C:\WINDOWS\System32\sc.exe query MySQL56"
start_command = "C:\WINDOWS\System32\sc.exe start MySQL56"
stop_command = "C:\WINDOWS\System32\sc.exe stop MySQL56"

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中django框架通过正则搜索页面上email地址的方法
Mar 21 Python
Python命令行参数解析模块optparse使用实例
Apr 13 Python
Python 中 list 的各项操作技巧
Apr 13 Python
Python探索之SocketServer详解
Oct 28 Python
Tensorflow卷积神经网络实例
May 24 Python
浅析Python 读取图像文件的性能对比
Mar 07 Python
python scatter散点图用循环分类法加图例
Mar 19 Python
python文件转为exe文件的方法及用法详解
Jul 08 Python
python GUI库图形界面开发之PyQt5打开保存对话框QFileDialog详细使用方法与实例
Feb 27 Python
python 服务器运行代码报错ModuleNotFoundError的解决办法
Sep 16 Python
Python的logging模块基本用法
Dec 24 Python
Python中常见的导入方式总结
May 06 Python
python实现教务管理系统
Mar 12 #Python
python编写弹球游戏的实现代码
Mar 12 #Python
python学生管理系统代码实现
Apr 05 #Python
python图书管理系统
Apr 05 #Python
怎么使用pipenv管理你的python项目
Mar 12 #Python
python实现图书管理系统
Mar 12 #Python
python实现快速排序的示例(二分法思想)
Mar 12 #Python
You might like
深入php 正则表达式的学习探讨
2013/06/06 PHP
php5.3 注意事项说明
2013/07/01 PHP
php检测url是否存在的方法
2015/04/14 PHP
PHP如何通过AJAX方式实现登录功能
2015/11/23 PHP
php采用session实现防止页面重复刷新
2015/12/24 PHP
PHP实现Markdown文章上传到七牛图床的实例内容
2020/02/11 PHP
jquery 动态创建元素的方式介绍及应用
2013/04/21 Javascript
5秒后跳转效果(setInterval/SetTimeOut)
2013/05/03 Javascript
JavaScript分秒倒计时器实现方法
2015/02/02 Javascript
JavaScript判断字符长度、数字、Email、电话等常用判断函数分享
2015/04/01 Javascript
详解JavaScript中void语句的使用
2015/06/04 Javascript
javascript瀑布流布局实现方法详解
2016/02/17 Javascript
详解AngularJS控制器的使用
2016/03/09 Javascript
JS for...in 遍历语句用法实例分析
2016/08/24 Javascript
Node.js + Redis Sorted Set实现任务队列
2016/09/19 Javascript
使用zrender.js绘制体温单效果
2019/10/31 Javascript
[35:26]DOTA2上海特级锦标赛B组小组赛#2 VG VS Fnatic第三局
2016/02/26 DOTA
python二叉树的实现实例
2013/11/21 Python
python3第三方爬虫库BeautifulSoup4安装教程
2018/06/19 Python
浅谈flask源码之请求过程
2018/07/26 Python
Python爬虫框架Scrapy常用命令总结
2018/07/26 Python
python 自定义对象的打印方法
2019/01/12 Python
Python后台开发Django的教程详解(启动)
2019/04/08 Python
django框架两个使用模板实例
2019/12/11 Python
纯css3实现鼠标经过图片显示描述的动画效果
2014/09/01 HTML / CSS
详解CSS3的box-shadow属性制作边框阴影效果的方法
2016/05/10 HTML / CSS
阿波罗盒子:Apollo Box
2017/08/14 全球购物
世界上最受欢迎的花店:1-800-Flowers.com
2020/06/01 全球购物
博士生入学考试推荐信
2013/11/17 职场文书
企业厂长岗位职责
2013/12/17 职场文书
会计工作心得体会
2014/01/13 职场文书
人事任命书范文
2014/06/04 职场文书
大学生就业自荐书
2014/06/16 职场文书
2015年党支部公开承诺书
2015/01/22 职场文书
2015年父亲节活动总结
2015/02/12 职场文书
简历中自我评价范文
2015/03/11 职场文书