Python管理Windows服务小脚本
本文实例为大家分享了Python管理Windows服务的具体代码,供大家参考,具体内容如下
#!/usr/bin/python
#encoding:utf-8
#-*-coding:utf8-*-
"""
CreatedbyPyCharm.
File:LinuxBashShellScriptForOps:ServiceControl.py
User:Guodong
CreateDate:2016/10/14
CreateTime:17:57
Exampleofprogramwithmanyoptionsusingdocopt,controlsystemservice.
Usage:
ServiceControl.pySERVICE_NAMESERVICE_ACTION
ServiceControl.pySERVICE_ACTIONSERVICE_NAME
ServiceControl.py--version|-v
ServiceControl.py--help|-h
Arguments:
SERVICE_NAMEservicename
SERVICE_ACTIONserviceactionin["start","stop","restart","status"]
Options:
-h--helpshowthishelpmessageandexit
-v--versionshowversionandexit
"""
importsys
importcodecs
importlocale
importpsutil
importwin32serviceutil
importtime
fromcollectionsimportOrderedDict
fromdocoptimportdocopt
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"
}
defget_system_encoding():
"""
Theencodingofthedefaultsystemlocalebutfallsbacktothegiven
fallbackencodingiftheencodingisunsupportedbypythonorcould
notbedetermined.Seetickets#10335and#5846
"""
try:
encoding=locale.getdefaultlocale()[1]or'ascii'
codecs.lookup(encoding)
exceptException:
encoding='ascii'
returnencoding
DEFAULT_LOCALE_ENCODING=get_system_encoding()
#try:
#result=result.decode(DEFAULT_LOCALE_ENCODING)
#exceptUnicodeDecodeError:
##UnicodeDecodeError-preventivetreatmentfornon-latinWindows.
#return''
defis_iterable(source):
ifsourceisnotNone:
try:
iter(source)
exceptTypeError:
returnFalse
returnTrue
else:
raiseRuntimeError("argumentcannotbeNone")
defstatus_service(service_name):
try:
result=win32serviceutil.QueryServiceStatus(service_name)[1]
ifresult==START_PENDING:
print"service%sis%s,pleasewait"%(service_name,status_code[result])
time.sleep(2)
returnRUNNING
elifresult==STOP_PENDING:
print"service%sis%s,pleasewait"%(service_name,status_code[result])
time.sleep(2)
returnSTOPPED
else:
returnresultifresultisnotNoneelse0
exceptExceptionase:
ife.message:
raiseRuntimeError(e.message)
elife.args:
#printe.args
args=list()
forargine.args:
ifis_iterable(arg):
args.append(unicode(eval(repr(arg)),'gbk'))
else:
args.append(arg)
print"Error:",args[-1],tuple(args)
raiseRuntimeError
else:
raiseRuntimeError("Uncaughtexception,maybeitisa'AccessDenied'")#willnotreachhere
defstart_service(service_name):
status=status_service(service_name)
ifstatus==STOPPED:
pass
elifstatus==RUNNING:
print"service%salreadystarted"%service_name
returnstatus
try:
print"starting%s"%service_name
win32serviceutil.StartService(service_name)
exceptExceptionase:
ife.message:
raiseRuntimeError(e.message)
elife.args:
#printe.args
args=list()
forargine.args:
ifis_iterable(arg):
args.append(unicode(eval(repr(arg)),'gbk'))
else:
args.append(arg)
print"Error:",args[-1],tuple(args)
raiseRuntimeError
else:
raiseRuntimeError("Uncaughtexception,maybeitisa'AccessDenied'")#willnotreachhere
returnstatus_service(service_name)
defstop_service(service_name):
status=status_service(service_name)
ifstatus==STOPPED:
print"service%salreadystopped"%service_name
returnstatus
elifstatus==RUNNING:
pass
else:
returnstatus
try:
print"stopping%s"%service_name
win32serviceutil.StopService(service_name)
exceptExceptionase:
ife.message:
printe.message
elife.args:
#printe.args
args=list()
forargine.args:
ifis_iterable(arg):
args.append(unicode(eval(repr(arg)),'gbk'))
else:
args.append(arg)
print"Error:",args[-1],tuple(args)
raiseRuntimeError
else:
raiseRuntimeError("Uncaughtexception,maybeitisa'AccessDenied'")#willnotreachhere
returnstatus_service(service_name)
defrestart_service(service_name):
status=status_service(service_name)
ifstatus==START_PENDINGorstatus==RUNNING:
ifstatus==START_PENDING:
time.sleep(2)
stop_service(service_name)
status=status_service(service_name)
ifstatus==STOPPEDorstatus==STOP_PENDING:
ifstatus==STOP_PENDING:
time.sleep(2)
returnstart_service(service_name)
elifstatus==STOPPEDorstatus==STOP_PENDING:
print"service%snotrunning."%service_name
returnstart_service(service_name)
else:
returnstatus_service(service_name)
defdo_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)",
}
ifservice_name==""orservice_action=="":
raiseRuntimeError("service_nameandservice_actioncannotbeempty.")
ifservice_actioninvalid_action:
returneval(maps[service_action])
else:
raiseRuntimeError("badservice_action'%s',validactionis%s"%(service_action,valid_action))
deflist_service():
service_dict=OrderedDict()
forserviceinpsutil.win_service_iter():
service_dict[service.name()]=service.display_name()
returnservice_dict
defis_valid_service_name(service_name):
ifservice_name.lower()in[name.lower()forname,display_nameinlist_service().items()]:
returnTrue
else:
returnFalse
if__name__=='__main__':
SERVICE_ACTION=["start","stop","restart","status"]
arguments=docopt(__doc__,version='1.0.0rc2')
ifarguments['SERVICE_NAME']!=""andarguments['SERVICE_ACTION']!="":
ifarguments['SERVICE_ACTION']inSERVICE_ACTION:
pass
elifarguments['SERVICE_NAME']inSERVICE_ACTION:
tmp=arguments['SERVICE_ACTION']
arguments['SERVICE_ACTION']=arguments['SERVICE_NAME']
arguments['SERVICE_NAME']=tmp
else:
print__doc__
sys.exit(1)
ifis_valid_service_name(arguments['SERVICE_NAME']):
pass
else:
raiseRuntimeError("server'%s'notexist"%arguments['SERVICE_NAME'])
return_code=do_service(arguments['SERVICE_NAME'],arguments['SERVICE_ACTION'])
try:
printstatus_code[return_code]
exceptKeyError:
print"return_codeis%s."%return_code
else:
print__doc__
sys.exit(1)
#TODO(GuodongDing)runacommandasadministratorwithadministrativeprivilege,use'runas'command?
state_command="C:\WINDOWS\System32\sc.exequeryMySQL56"
start_command="C:\WINDOWS\System32\sc.exestartMySQL56"
stop_command="C:\WINDOWS\System32\sc.exestopMySQL56"
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。