-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathclient.py
253 lines (219 loc) · 7.21 KB
/
client.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
import copy
import logging
import os
import random
import salt.config
import salt.syspaths
import salt.utils.args
from salt.exceptions import SaltClientError
log = logging.getLogger(__name__)
class SSHClient:
"""
Create a client object for executing routines via the salt-ssh backend
.. versionadded:: 2015.5.0
"""
def __init__(
self,
c_path=os.path.join(salt.syspaths.CONFIG_DIR, "master"),
mopts=None,
disable_custom_roster=False,
):
if mopts:
self.opts = mopts
else:
if os.path.isdir(c_path):
log.warning(
"%s expects a file path not a directory path(%s) to "
"its 'c_path' keyword argument",
self.__class__.__name__,
c_path,
)
self.opts = salt.config.client_config(c_path)
# Salt API should never offer a custom roster!
self.opts["__disable_custom_roster"] = disable_custom_roster
def sanitize_kwargs(self, kwargs):
roster_vals = [
("host", str),
("ssh_user", str),
("ssh_passwd", str),
("ssh_port", int),
("ssh_sudo", bool),
("ssh_sudo_user", str),
("ssh_priv", str),
("ssh_priv_passwd", str),
("ssh_identities_only", bool),
("ssh_remote_port_forwards", str),
("ssh_options", list),
("roster_file", str),
("rosters", list),
("ignore_host_keys", bool),
("raw_shell", bool),
]
sane_kwargs = {}
for name, kind in roster_vals:
if name not in kwargs:
continue
try:
val = kind(kwargs[name])
except ValueError:
log.warning("Unable to cast kwarg %s", name)
continue
if kind is bool or kind is int:
sane_kwargs[name] = val
elif kind is str:
if val.find("ProxyCommand") != -1:
log.warning("Filter unsafe value for kwarg %s", name)
continue
sane_kwargs[name] = val
elif kind is list:
sane_val = []
for item in val:
# This assumes the values are strings
if item.find("ProxyCommand") != -1:
log.warning("Filter unsafe value for kwarg %s", name)
continue
sane_val.append(item)
sane_kwargs[name] = sane_val
return sane_kwargs
def _prep_ssh(
self, tgt, fun, arg=(), timeout=None, tgt_type="glob", kwarg=None, **kwargs
):
"""
Prepare the arguments
"""
kwargs = self.sanitize_kwargs(kwargs)
opts = copy.deepcopy(self.opts)
opts.update(kwargs)
if timeout:
opts["timeout"] = timeout
arg = salt.utils.args.condition_input(arg, kwarg)
opts["argv"] = [fun] + arg
opts["selected_target_option"] = tgt_type
opts["tgt"] = tgt
opts["arg"] = arg
return salt.client.ssh.SSH(opts)
def cmd_iter(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type="glob",
ret="",
kwarg=None,
**kwargs
):
"""
Execute a single command via the salt-ssh subsystem and return a
generator
.. versionadded:: 2015.5.0
"""
ssh = self._prep_ssh(tgt, fun, arg, timeout, tgt_type, kwarg, **kwargs)
yield from ssh.run_iter(jid=kwargs.get("jid", None))
def cmd(
self, tgt, fun, arg=(), timeout=None, tgt_type="glob", kwarg=None, **kwargs
):
"""
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionadded:: 2015.5.0
"""
ssh = self._prep_ssh(tgt, fun, arg, timeout, tgt_type, kwarg, **kwargs)
final = {}
for ret in ssh.run_iter(jid=kwargs.get("jid", None)):
final.update(ret)
return final
def cmd_sync(self, low):
"""
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
"""
kwargs = copy.deepcopy(low)
for ignore in ["tgt", "fun", "arg", "timeout", "tgt_type", "kwarg"]:
if ignore in kwargs:
del kwargs[ignore]
return self.cmd(
low["tgt"],
low["fun"],
low.get("arg", []),
low.get("timeout"),
low.get("tgt_type"),
low.get("kwarg"),
**kwargs
)
def cmd_async(self, low, timeout=None):
"""
Execute aa salt-ssh asynchronously
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
'kwarg'={}
})
{'silver': {'fun_args': [], 'jid': '20141202152721523072', 'return': True, 'retcode': 0, 'success': True, 'fun': 'test.ping', 'id': 'silver'}}
"""
# TODO Not implemented
raise SaltClientError
def cmd_subset(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type="glob",
ret="",
kwarg=None,
subset=3,
**kwargs
):
"""
Execute a command on a random subset of the targeted systems
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param subset: The number of systems to execute on
.. code-block:: python
>>> import salt.client.ssh.client
>>> sshclient= salt.client.ssh.client.SSHClient()
>>> sshclient.cmd_subset('*', 'test.ping', subset=1)
{'jerry': True}
.. versionadded:: 2017.7.0
"""
minion_ret = self.cmd(tgt, "sys.list_functions", tgt_type=tgt_type, **kwargs)
minions = list(minion_ret)
random.shuffle(minions)
f_tgt = []
for minion in minions:
if fun in minion_ret[minion]["return"]:
f_tgt.append(minion)
if len(f_tgt) >= subset:
break
return self.cmd_iter(
f_tgt, fun, arg, timeout, tgt_type="list", ret=ret, kwarg=kwarg, **kwargs
)
def destroy(self):
"""
API compatibility method with salt.client.LocalClient
"""
def __enter__(self):
"""
API compatibility method with salt.client.LocalClient
"""
return self
def __exit__(self, *args):
"""
API compatibility method with salt.client.LocalClient
"""
self.destroy()