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通过pil模块将raw图片转换成png图片的方法
Mar 16 Python
Python使用scrapy采集时伪装成HTTP/1.1的方法
Apr 08 Python
浅谈python类属性的访问、设置和删除方法
Jul 25 Python
Python实现动态加载模块、类、函数的方法分析
Jul 18 Python
Django 中自定义 Admin 样式与功能的实现方法
Jul 04 Python
python使用SQLAlchemy操作MySQL
Jan 02 Python
如何基于python实现归一化处理
Jan 20 Python
python实现字符串和数字拼接
Mar 02 Python
Django中和时区相关的安全问题详解
Oct 12 Python
Python通过Schema实现数据验证方式
Nov 12 Python
python uuid生成唯一id或str的最简单案例
Jan 13 Python
python可视化分析的实现(matplotlib、seaborn、ggplot2)
Feb 03 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运行出现Notice : Use of undefined constant 的完美解决方案分享
2012/03/05 PHP
Laravel中批量赋值Mass-Assignment的真正含义详解
2017/09/29 PHP
关于PHP求解三数之和问题详析
2020/11/09 PHP
JavaScript 精粹读书笔记(1,2)
2010/02/07 Javascript
Egret引擎开发指南之运行项目
2014/09/03 Javascript
javascript 获取浏览器版本
2015/01/21 Javascript
jQuery实现的在线答题功能
2015/04/12 Javascript
javascript图片滑动效果实现
2021/01/28 Javascript
全面解析Bootstrap排版使用方法(标题)
2015/11/30 Javascript
总结Javascript中的隐式类型转换
2016/08/24 Javascript
js导出excel文件的简洁方法(推荐)
2016/11/02 Javascript
一句jQuery代码实现返回顶部效果(简单实用)
2016/12/28 Javascript
使用BootStrap实现标签切换原理解析
2017/03/14 Javascript
微信小程序实现缓存根据不同的id来进行设置和读取缓存
2017/06/12 Javascript
想用好React的你必须要知道的一些事情
2017/07/24 Javascript
JS禁止浏览器右键查看元素或按F12审查元素自动关闭页面示例代码
2017/09/07 Javascript
JS与CSS3实现图片响应鼠标移动放大效果示例
2018/05/04 Javascript
layui实现table加载的示例代码
2018/08/14 Javascript
浅谈vue引用静态资源需要注意的事项
2018/09/28 Javascript
解决vue-cli 打包后自定义动画未执行的问题
2019/11/12 Javascript
原生JavaScript实现的无缝滚动功能详解
2020/01/17 Javascript
简单了解JavaScript arguement原理及作用
2020/05/28 Javascript
[46:21]Liquid vs LGD 2018国际邀请赛淘汰赛BO3 第一场 8.23
2018/08/24 DOTA
[46:14]完美世界DOTA2联赛PWL S3 Magma vs INK ICE 第一场 12.11
2020/12/16 DOTA
python简单线程和协程学习心得(分享)
2017/06/14 Python
Python3.4 splinter(模拟填写表单)使用方法
2018/10/13 Python
详解如何将 Canvas 绘制过程转为视频
2021/01/25 HTML / CSS
植物选择:Botanic Choice
2017/02/15 全球购物
汽车电子与维修专业大学生求职信
2013/09/28 职场文书
合作协议书怎么写
2014/04/18 职场文书
坎儿井导游词
2015/02/09 职场文书
2015年银行客户经理工作总结
2015/04/01 职场文书
小学教师个人工作总结2015
2015/04/20 职场文书
2015年学校教研室主任工作总结
2015/07/20 职场文书
小学四年级班主任工作经验交流材料
2015/11/02 职场文书
vue.js 使用原生js实现轮播图
2022/04/26 Vue.js