-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcheck_services_state_winrm.py
340 lines (289 loc) · 10.1 KB
/
check_services_state_winrm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2013:
# Sébastien Pasche, [email protected]
# Mikael Bugnon, [email protected]
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
author = "Sebastien Pasche"
maintainer = "Sebastien Pasche"
version = "0.0.1"
import optparse
import sys
import os
import traceback
from pprint import pprint
try:
import winrm
from winrm.protocol import Protocol
except ImportError:
print "ERROR : this plugin needs the local winrm lib. Please install it"
sys.exit(2)
#Ok try to load our directory to load the plugin utils.
my_dir = os.path.dirname(__file__)
sys.path.insert(0, my_dir)
try:
from winrm_checks import OutputFormatHelpers, PowerShellHelpers
except ImportError:
print "ERROR : this plugin needs the local winrm lib. Please install it"
sys.exit(2)
#DEFAULT LIMITS
#--------------
#https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontrollerstatus(v=vs.110).aspx
WINDOWS_SERVICE_STATUS = {
5: "ContinuePending",
7: "Paused",
6: "PausePending",
4: "Running",
2: "StartPending",
1: "Stopped",
3: "StopPending"
}
DEFAULT_OK = frozenset(
[
"Running"
]
)
START_MODE = frozenset(
[
'Auto'
]
)
AUTO_EXCLUDE_LIST = frozenset(
[
'sppsvc',
'ShellHWDetection',
'BMR Boot Service',
'NetBackup SAN Client Fibre Transport Service',
'clr_optimization',
'Sophos Web Intelligence Update',
'Check_MK_Agent',
'TeamViewer9',
'SysmonLog',
'gupdate',
'swi_update_64',
'swi_service',
'stisvc',
'vimPBSM',
'vimQueryService',
'Citrix Licensing',
'CitrixXenAppCommandsRemoting',
'RemoteRegistry',
'TrustedInstaller'
]
)
MANUAL_OK_EXIT_CODE = frozenset(
[
0,
1077
]
)
# Powershell
# ----------
ps_script = """
#Functions
#---------
#check input data
#----------------
{check_input_json}
#Obtain data
#-----------
$CheckOutputObj = Get-WmiObject -Class Win32_Service
#Format output
$CheckOuputJson = $CheckOutputObj | ConvertTo-Json
$CheckOuputJsonBytes = [System.Text.Encoding]::UTF8.GetBytes($CheckOuputJson)
$CheckOuputJsonBytesBase64 = [System.Convert]::ToBase64String($CheckOuputJsonBytes)
Write-Host $CheckOuputJsonBytesBase64
"""
# OPT parsing
# -----------
parser = optparse.OptionParser(
"%prog [options]", version="%prog " + version)
parser.add_option('-H', '--hostname',
dest="hostname",
help='Hostname to connect to')
parser.add_option('-p', '--port',
dest="port", type="int", default=5986,
help='WinRM HTTP port to connect to. Default : HTTPS - 5986')
parser.add_option('-s', '--http-scheme',
dest="scheme", default="https",
help='WinRM HTTP scheme to connect to. Default : https://')
parser.add_option('-U', '--user',
dest="user", default="shinken",
help='remote use to use. By default shinken.')
parser.add_option('-P', '--password',
dest="password",
help='Password. By default will use void')
parser.add_option('--debug',
dest="debug", default=False, action="store_true",
help='Enable debug')
parser.add_option('--manual-error-warning',
dest="manual_error_warning", default=False, action="store_true",
help='Warning if manual service have a non 0 exit code')
parser.add_option('--manual-error-critical',
dest="manual_error_critical", default=False, action="store_true",
help='Critical if manual service have a non 0 exit code')
parser.add_option('--manual-started-warning',
dest="manual_warning", default=False, action="store_true",
help='Warning if service started manualy')
parser.add_option('--auto-exclude-list',
dest="auto_exclude_list", default='',
help='Service name to exclude from automatic but not running service list to check. '
'Define service list as a space delimited list. Ex: "service_a service_b"')
parser.add_option('--auto-include-list',
dest="auto_include_list", default='',
help='Service name to include into automatic but not running service list to check. '
'Define service list as a space delimited list. Ex: "service_d service_e"')
if __name__ == '__main__':
# Ok first job : parse args
opts, args = parser.parse_args()
if args:
parser.error("Does not accept any argument.")
# connection parameters
port = opts.port
hostname = opts.hostname or ''
scheme = opts.scheme
user = opts.user
password = opts.password
debug = opts.debug
#manual service check options
manual_error_warning = opts.manual_error_warning
manual_error_critical = opts.manual_error_critical
manual_warning = opts.manual_warning
#automatic services list
auto_exclude_list = opts.auto_exclude_list.split(' ')
auto_include_list = opts.auto_include_list.split(' ')
try:
# Connect to the remote host
client = winrm.Session(
'{s}://{h}:{p}'.format(
s=scheme,
h=hostname,
p=port
),
auth=(
user,
password
)
)
# Fill script data
data = {
}
#prepare the script
executable_ps_script = PowerShellHelpers.generate_ps(
ps_script,
data
)
if debug:
print("Script to execute")
print("-----------------")
print(executable_ps_script)
#execute the scripte
services_state = PowerShellHelpers.ececute_powershell(
client,
executable_ps_script,
debug
)
if debug:
print("check output")
print("------------")
pprint(services_state)
messages = []
#check logic
status = 'OK'
service_message = "{mode} {name} current state is {state}"
#manual services check_logic
#---------------------------
manual_services_list = [
service for service in services_state if service['StartMode'] == 'Manual'
]
manual_services_running_list = [
service for service in manual_services_list if service['State'] in DEFAULT_OK
]
manual_services_error_list = [
service for service in manual_services_list if service['ExitCode'] not in MANUAL_OK_EXIT_CODE
]
if manual_error_warning and len(manual_services_running_list) >= 1:
status = 'Warning'
for service in manual_services_running_list:
messages.append(service_message.format(
mode='Manual',
name=service['Name'],
state=['running']
))
if (manual_error_warning or manual_error_critical) and len(manual_services_error_list) >= 1:
for service in manual_services_error_list:
messages.append(service_message.format(
mode='Manual',
name=service['Name'],
state='ExitCode {e}'.format(e=service['ExitCode'])
))
if manual_error_warning:
status = 'Warning'
if manual_error_critical:
status = 'Critical'
#automatic services check logic
#------------------------------
auto_exclude_list = AUTO_EXCLUDE_LIST.union(
auto_include_list
).difference(
auto_exclude_list
)
if debug:
print("Automatic service exclusion list")
print("--------------------------------")
pprint(auto_exclude_list)
auto_not_started_services_list = [service for service in services_state if (
service['StartMode'] == 'Auto' and
service['Name'] not in auto_exclude_list and
service['State'] not in DEFAULT_OK
)]
if len(auto_not_started_services_list) >= 1:
status = 'Critical'
for service in auto_not_started_services_list:
messages.append(service_message.format(
mode='Auto',
name=service['Name'],
state='not running'
))
#formating output
if len(messages) > 0:
message = ','.join(messages)
else:
message = 'Everything fine'
output = OutputFormatHelpers.check_output_string(
status,
message,
None
)
print(output)
except Exception as e:
if debug:
print(e)
the_type, value, tb = sys.exc_info()
traceback.print_tb(tb)
print("Error: {m}".format(m=e))
sys.exit(2)
finally:
if status == "Critical":
sys.exit(2)
if status == "Warning":
sys.exit(1)
sys.exit(0)