Python管理Windows服务小脚本

本文实例为大家分享了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脚本作为Windows服务启动代码详解
  • 代码讲解Python对Windows服务进行监控
  • Python编写Windows Service服务程序
  • Python制作Windows系统服务
  • python实现在windows服务中新建进程的方法
  • 在Windows服务器下用Apache和mod_wsgi配置Python应用的教程
  • python实现监控windows服务并自动启动服务示例
  • 解决python写的windows服务不能启动的问题
(0)

相关推荐

  • python脚本作为Windows服务启动代码详解

    我们首先来看下全部代码: # -*- coding: cp936 -*- import win32serviceutil import win32service import win32event class test1(win32serviceutil.ServiceFramework): _svc_name_ = "test_python" _svc_display_name_ = "test_python" def __init__(self, args):

  • python实现监控windows服务并自动启动服务示例

    使用Python 2.7 + pywin32 + wxpython开发 每隔一段时间检测一下服务是否停止,如果停止尝试启动服务.进行服务停止日志记录 AppMain.py 复制代码 代码如下: #!/usr/bin/env python#-*- encoding:utf-8 -*- """1. 每隔一分钟检测一次服务状态2. 如果发现服务状态已经停止,那么尝试启动服务3. 自动记录日志4. 任务栏图标显示""" import sys;reload

  • 解决python写的windows服务不能启动的问题

    报"服务没有及时响应或控制请求"的错误,改用pyinstaller生成也是不行:查资料后修改setup.py如下即可,服务名.脚本名请自行替换: 复制代码 代码如下: #!/usr/bin/python  #-*-coding:cp936-*-from distutils.core import setupimport py2exe class Target:    def __init__(self, **kw):        self.__dict__.update(kw)   

  • Python编写Windows Service服务程序

    如果你想用Python开发Windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用Python来做这个事情必须要借助第三方模块pywin32,自己去下载然后安装(注意下载符合自己OS的版本). 1.示例分析 1).幸运的是这里有一个简单的服务模版,足以满足大多数人的要求: #encoding=utf-8 #ZPF import win32serviceutil import win32service import win32event class

  • 代码讲解Python对Windows服务进行监控

    我们首先来看下python的全部代码,大家可以直接复制后测试: #-*- encoding: utf-8 -*- import logging import wmi import os import time from ConfigParser import ConfigParser import smtplib from email.mime.text import MIMEText import socket from datetime import datetime import re i

  • Python制作Windows系统服务

    最近有个Python程序需要安装并作为Windows系统服务来运行,过程中碰到一些坑,整理了一下. Python服务类 首先Python程序需要调用一些Windows系统API才能作为系统服务,具体内容如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time import win32api import win32event import win32service import win32serviceuti

  • 在Windows服务器下用Apache和mod_wsgi配置Python应用的教程

    最近开发了一个 Google Analytics 相关的应用,但需要在 Windows 下部署,结合网上的相关经验,最终选择了 apache+mod_wsgi 这样的配置. 修改python应用 复制代码 代码如下: Note that mod_wsgi requires that the WSGI application entry point be called 'application'. If you want to call it something else then you wou

  • python实现在windows服务中新建进程的方法

    本文实例讲述了python实现在windows服务中新建进程的方法.分享给大家供大家参考.具体实现方法如下: 需要安装的软件:python和pywin32,我这里装的分别是python-2.6.amd64.pywin32-217.win-amd64-py2.6 文件名:dma_ws.py #!python import win32serviceutil import win32service import win32event import os from subprocess import P

  • Python管理Windows服务小脚本

    本文实例为大家分享了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 Exa

  • 利用Python实现自动扫雷小脚本

    自动扫雷一般分为两种,一种是读取内存数据,而另一种是通过分析图片获得数据,并通过模拟鼠标操作,这里我用的是第二种方式. 一.准备工作 1.扫雷游戏 我是win10,没有默认的扫雷,所以去扫雷网下载 http://www.saolei.net/BBS/ 2.python 3 我的版本是 python 3.6.1 3.python的第三方库 win32api,win32gui,win32con,Pillow,numpy,opencv 可通过 pip install --upgrade SomePac

  • Python制作Windows按键通知脚本

    目录 前言 1.准备 2.源码使用与解析 2.1 源码使用 2.2 源码分析 3.扩展触发通知 前言 对于键盘没有背光灯的同学而言,切换大小写或控制Num键开关的时候没有提示,经常需要试探性地输入一些字符来判断开关是否打开,体验非常糟糕. 因此,有人就想到自制脚本这一招,一旦触发大小写切换或Num键切换就进行windows通知提示: https://github.com/skate1512/Toggle_Keys_Notification 今天我们来试试这个脚本,此外,我们还可以基于这个项目,扩

  • Python版Mssql爆破小脚本

    Mssql Python版本爆破小脚本,需要安装 MSSQL-python.exe 可以看出代码量很少,用法:保存代码为MssqlDatabaseBlasting.py,cmd切换到 MssqlDatabaseBlasting.py路径下,并 执行 MssqlDatabaseBlasting.py即可开始破解 import pymssql common_weak_password = ('','123456','test','root','admin','user')#密码字典 mssql_us

  • Python版Mysql爆破小脚本

    Mysql Python版本爆破小脚本,需要安装Python插件MySQL-python.exe,可以看出代码量很少,(注意:里用户名和密码都是类似字典.用法:保存代码为MysqlDatabaseBlasting.py,cmd切换到 MysqlDatabaseBlasting.py路径下,并 执行 MysqlDatabaseBlasting.py即可开始破解 ) import MySQLdb #coding=gbk #目标IP mysql数据库必须开启3360远程登陆端口 mysql_usern

  • python实现windows下文件备份脚本

    在windows下用python脚本实现文件的备份,参考<A Byte of Python3>第十一章(Page59). #!/usr/bin/python # -*- coding: cp936 -*- import os import time source = ['E:\\'] # 待备份文件在E盘根目录下 running = True while running: your_source = raw_input("Your own path or your own file

  • Python实现图片尺寸缩放脚本

    最近由于网站对图片尺寸的需要,用python写了个小脚本,方便进行图片尺寸的一些调整,特记录如下: # coding=utf-8 import Image import shutil import os class Graphics: infile = 'D:\\myimg.jpg' outfile = 'D:\\adjust_img.jpg' @classmethod def fixed_size(cls, width, height): """按照固定尺寸处理图片&quo

  • python常用小脚本实例总结

    目录 前言 打印16进制字符串 文件合并 多线程下载图集 多线程下载图片 爬虫抓取信息 爬虫多线程下载电影名称 串口转tcp工具 远程读卡器server端 黑客rtcp反向链接 调用c的动态库示例 tcp的socket连接报文测试工具 报文拼接与加解密测试 二进制文件解析工具 抓取动漫图片 抓取网站模板 总结 前言 日常生活中常会遇到一些小任务,如果人工处理会很麻烦. 用python做些小脚本处理,能够提高不少效率.或者可以把python当工具使用,辅助提高一下办公效率.(比如我常拿python

随机推荐