Repository navigation
Expand file tree
/
Copy pathwin_servermanager.py
More file actions
407 lines (318 loc) · 14.3 KB
/
Copy pathwin_servermanager.py
File metadata and controls
407 lines (318 loc) · 14.3 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# -*- coding: utf-8 -*-
'''
Manage Windows features via the ServerManager powershell module. Can list
available and installed roles/features. Can install and remove roles/features.
:maintainer: Shane Lee <[email protected]>
:platform: Windows Server 2008R2 or greater
:depends: PowerShell module ``ServerManager``
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
try:
from shlex import quote as _cmd_quote # pylint: disable=E0611
except ImportError:
from pipes import quote as _cmd_quote
# Import Salt libs
import salt.utils.json
import salt.utils.platform
import salt.utils.powershell
import salt.utils.versions
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
__virtualname__ = 'win_servermanager'
def __virtual__():
'''
Load only on windows with servermanager module
'''
if not salt.utils.platform.is_windows():
return False
if salt.utils.versions.version_cmp(__grains__['osversion'], '6.1.7600') == -1:
return False, 'Failed to load win_servermanager module: ' \
'Requires Remote Server Administration Tools which ' \
'is only available on Windows 2008 R2 and later.'
if not salt.utils.powershell.module_exists('ServerManager'):
return False, 'Failed to load win_servermanager module: ' \
'ServerManager module not available. ' \
'May need to install Remote Server Administration Tools.'
return __virtualname__
def _pshell_json(cmd, cwd=None):
'''
Execute the desired powershell command and ensure that it returns data
in JSON format and load that into python
'''
cmd = 'Import-Module ServerManager; {0}'.format(cmd)
if 'convertto-json' not in cmd.lower():
cmd = '{0} | ConvertTo-Json'.format(cmd)
log.debug('PowerShell: %s', cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd)
if 'pid' in ret:
del ret['pid']
if ret.get('stderr', ''):
error = ret['stderr'].splitlines()[0]
raise CommandExecutionError(error, info=ret)
if 'retcode' not in ret or ret['retcode'] != 0:
# run_all logs an error to log.error, fail hard back to the user
raise CommandExecutionError(
'Issue executing PowerShell {0}'.format(cmd), info=ret)
# Sometimes Powershell returns an empty string, which isn't valid JSON
if ret['stdout'] == '':
ret['stdout'] = '{}'
try:
ret = salt.utils.json.loads(ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError(
'No JSON results from PowerShell', info=ret)
return ret
def list_available():
'''
List available features to install
Returns:
str: A list of available features as returned by the
``Get-WindowsFeature`` PowerShell command
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_available
'''
cmd = 'Import-Module ServerManager; ' \
'Get-WindowsFeature ' \
'-ErrorAction SilentlyContinue ' \
'-WarningAction SilentlyContinue'
return __salt__['cmd.shell'](cmd, shell='powershell')
def list_installed():
'''
List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.
Returns:
dict: A dictionary of installed features
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_installed
'''
cmd = 'Get-WindowsFeature ' \
'-ErrorAction SilentlyContinue ' \
'-WarningAction SilentlyContinue ' \
'| Select DisplayName,Name,Installed'
features = _pshell_json(cmd)
ret = {}
for entry in features:
if entry['Installed']:
ret[entry['Name']] = entry['DisplayName']
return ret
def install(feature, recurse=False, restart=False, source=None, exclude=None):
r'''
Install a feature
.. note::
Some features require reboot after un/installation, if so until the
server is restarted other features can not be installed!
.. note::
Some features take a long time to complete un/installation, set -t with
a long timeout
Args:
feature (str, list):
The name of the feature(s) to install. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be installed.
recurse (Options[bool]):
Install all sub-features. Default is False
restart (Optional[bool]):
Restarts the computer when installation is complete, if required by
the role/feature installed. Will also trigger a reboot if an item
in ``exclude`` requires a reboot to be properly removed. Default is
False
source (Optional[str]):
Path to the source files if missing from the target system. None
means that the system will use windows update services to find the
required files. Default is None
exclude (Optional[str]):
The name of the feature to exclude when installing the named
feature. This can be a single feature, a string of features in a
comma-delimited list (no spaces), or a list of features.
.. warning::
As there is no exclude option for the ``Add-WindowsFeature``
or ``Install-WindowsFeature`` PowerShell commands the features
named in ``exclude`` will be installed with other sub-features
and will then be removed. **If the feature named in ``exclude``
is not a sub-feature of one of the installed items it will still
be removed.**
Returns:
dict: A dictionary containing the results of the install
CLI Example:
.. code-block:: bash
# Install the Telnet Client passing a single string
salt '*' win_servermanager.install Telnet-Client
# Install the TFTP Client and the SNMP Service passing a comma-delimited
# string. Install all sub-features
salt '*' win_servermanager.install TFTP-Client,SNMP-Service recurse=True
# Install the TFTP Client from d:\side-by-side
salt '*' win_servermanager.install TFTP-Client source=d:\\side-by-side
# Install the XPS Viewer, SNMP Service, and Remote Access passing a
# list. Install all sub-features, but exclude the Web Server
salt '*' win_servermanager.install "['XPS-Viewer', 'SNMP-Service', 'RemoteAccess']" True recurse=True exclude="Web-Server"
'''
# If it is a list of features, make it a comma delimited string
if isinstance(feature, list):
feature = ','.join(feature)
# Use Install-WindowsFeature on Windows 2012 (osversion 6.2) and later
# minions. Default to Add-WindowsFeature for earlier releases of Windows.
# The newer command makes management tools optional so add them for parity
# with old behavior.
command = 'Add-WindowsFeature'
management_tools = ''
if salt.utils.versions.version_cmp(__grains__['osversion'], '6.2') >= 0:
command = 'Install-WindowsFeature'
management_tools = '-IncludeManagementTools'
cmd = '{0} -Name {1} {2} {3} {4} ' \
'-WarningAction SilentlyContinue'\
.format(command, _cmd_quote(feature), management_tools,
'-IncludeAllSubFeature' if recurse else '',
'' if source is None else '-Source {0}'.format(source))
out = _pshell_json(cmd)
# Uninstall items in the exclude list
# The Install-WindowsFeature command doesn't have the concept of an exclude
# list. So you install first, then remove
if exclude is not None:
removed = remove(exclude)
# Results are stored in a list of dictionaries in `FeatureResult`
if out['FeatureResult']:
ret = {'ExitCode': out['ExitCode'],
'RestartNeeded': False,
'Restarted': False,
'Features': {},
'Success': out['Success']}
# FeatureResult is a list of dicts, so each item is a dict
for item in out['FeatureResult']:
ret['Features'][item['Name']] = {
'DisplayName': item['DisplayName'],
'Message': item['Message'],
'RestartNeeded': item['RestartNeeded'],
'SkipReason': item['SkipReason'],
'Success': item['Success']
}
if item['RestartNeeded']:
ret['RestartNeeded'] = True
# Only items that installed are in the list of dictionaries
# Add 'Already installed' for features that aren't in the list of dicts
for item in feature.split(','):
if item not in ret['Features']:
ret['Features'][item] = {'Message': 'Already installed'}
# Some items in the exclude list were removed after installation
# Show what was done, update the dict
if exclude is not None:
# Features is a dict, so it only iterates over the keys
for item in removed['Features']:
if item in ret['Features']:
ret['Features'][item] = {
'Message': 'Removed after installation (exclude)',
'DisplayName': removed['Features'][item]['DisplayName'],
'RestartNeeded': removed['Features'][item]['RestartNeeded'],
'SkipReason': removed['Features'][item]['SkipReason'],
'Success': removed['Features'][item]['Success']
}
# Exclude items might need a restart
if removed['Features'][item]['RestartNeeded']:
ret['RestartNeeded'] = True
# Restart here if needed
if restart:
if ret['RestartNeeded']:
if __salt__['system.restart'](in_seconds=True):
ret['Restarted'] = True
return ret
else:
# If we get here then all features were already installed
ret = {'ExitCode': out['ExitCode'],
'Features': {},
'RestartNeeded': False,
'Restarted': False,
'Success': out['Success']}
for item in feature.split(','):
ret['Features'][item] = {'Message': 'Already installed'}
return ret
def remove(feature, remove_payload=False, restart=False):
r'''
Remove an installed feature
.. note::
Some features require a reboot after installation/uninstallation. If
one of these features are modified, then other features cannot be
installed until the server is restarted. Additionally, some features
take a while to complete installation/uninstallation, so it is a good
idea to use the ``-t`` option to set a longer timeout.
Args:
feature (str, list):
The name of the feature(s) to remove. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be removed.
remove_payload (Optional[bool]):
True will cause the feature to be removed from the side-by-side
store (``%SystemDrive%:\Windows\WinSxS``). Default is False
restart (Optional[bool]):
Restarts the computer when uninstall is complete, if required by the
role/feature removed. Default is False
Returns:
dict: A dictionary containing the results of the uninstall
CLI Example:
.. code-block:: bash
salt -t 600 '*' win_servermanager.remove Telnet-Client
'''
# If it is a list of features, make it a comma delimited string
if isinstance(feature, list):
feature = ','.join(feature)
# Use Uninstall-WindowsFeature on Windows 2012 (osversion 6.2) and later
# minions. Default to Remove-WindowsFeature for earlier releases of Windows.
# The newer command makes management tools optional so add them for parity
# with old behavior.
command = 'Remove-WindowsFeature'
management_tools = ''
_remove_payload = ''
if salt.utils.versions.version_cmp(__grains__['osversion'], '6.2') >= 0:
command = 'Uninstall-WindowsFeature'
management_tools = '-IncludeManagementTools'
# Only available with the `Uninstall-WindowsFeature` command
if remove_payload:
_remove_payload = '-Remove'
cmd = '{0} -Name {1} {2} {3} {4} ' \
'-WarningAction SilentlyContinue'\
.format(command, _cmd_quote(feature), management_tools,
_remove_payload,
'-Restart' if restart else '')
try:
out = _pshell_json(cmd)
except CommandExecutionError as exc:
if 'ArgumentNotValid' in exc.message:
raise CommandExecutionError('Invalid Feature Name', info=exc.info)
raise
# Results are stored in a list of dictionaries in `FeatureResult`
if out['FeatureResult']:
ret = {'ExitCode': out['ExitCode'],
'RestartNeeded': False,
'Restarted': False,
'Features': {},
'Success': out['Success']}
for item in out['FeatureResult']:
ret['Features'][item['Name']] = {
'DisplayName': item['DisplayName'],
'Message': item['Message'],
'RestartNeeded': item['RestartNeeded'],
'SkipReason': item['SkipReason'],
'Success': item['Success']
}
# Only items that installed are in the list of dictionaries
# Add 'Not installed' for features that aren't in the list of dicts
for item in feature.split(','):
if item not in ret['Features']:
ret['Features'][item] = {'Message': 'Not installed'}
return ret
else:
# If we get here then none of the features were installed
ret = {'ExitCode': out['ExitCode'],
'Features': {},
'RestartNeeded': False,
'Restarted': False,
'Success': out['Success']}
for item in feature.split(','):
ret['Features'][item] = {'Message': 'Not installed'}
return ret