Ansible api使用

ansible 1.9.6

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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# -*- coding: utf-8 -*-
from tempfile import NamedTemporaryFile
import os.path
from ansible.inventory.group import Group
from ansible.inventory.host import Host
from ansible.inventory import Inventory
from ansible.runner import Runner
from ansible.playbook import PlayBook
from ansible import callbacks
from ansible import utils
import ansible.constants as C
from passlib.hash import sha512_crypt
from django.template.loader import get_template
from django.template import Context
API_DIR = os.path.dirname(os.path.abspath(__file__))
ANSIBLE_DIR = os.path.join(API_DIR, 'playbooks')
C.HOST_KEY_CHECKING = False
class AnsibleError(StandardError):
"""
the base AnsibleError which contains error(required),
data(optional) and message(optional).
存储所有Ansible 异常对象
"""
def __init__(self, error, data='', message=''):
super(AnsibleError, self).__init__(message)
self.error = error
self.data = data
self.message = message
class CommandValueError(AnsibleError):
"""
indicate the input value has error or invalid.
the data specifies the error field of input form.
输入不合法 异常对象
"""
def __init__(self, field, message=''):
super(CommandValueError, self).__init__('value:invalid', field, message)
class MyInventory(Inventory):
"""
this is my ansible inventory object.
"""
def __init__(self, resource):
"""
resource的数据格式是一个列表字典,比如
{
"group1": {
"hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...],
"vars": {"var1": value1, "var2": value2, ...}
}
}
如果你只传入1个列表,这默认该列表内的所有主机属于my_group组,比如
[{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...]
"""
self.resource = resource
self.inventory = Inventory(host_list=[])
self.gen_inventory()
def my_add_group(self, hosts, groupname, groupvars=None):
"""
add hosts to a group
"""
my_group = Group(name=groupname)
# if group variables exists, add them to group
if groupvars:
for key, value in groupvars.iteritems():
my_group.set_variable(key, value)
# add hosts to group
for host in hosts:
# set connection variables
hostname = host.get("hostname")
hostip = host.get('ip', hostname)
hostport = host.get("port")
username = host.get("username")
password = host.get("password")
ssh_key = host.get("ssh_key")
my_host = Host(name=hostname, port=hostport)
my_host.set_variable('ansible_ssh_host', hostip)
my_host.set_variable('ansible_ssh_port', hostport)
my_host.set_variable('ansible_ssh_user', username)
my_host.set_variable('ansible_ssh_pass', password)
my_host.set_variable('ansible_ssh_private_key_file', ssh_key)
# set other variables
for key, value in host.iteritems():
if key not in ["hostname", "port", "username", "password"]:
my_host.set_variable(key, value)
# add to group
my_group.add_host(my_host)
self.inventory.add_group(my_group)
def gen_inventory(self):
"""
add hosts to inventory.
"""
if isinstance(self.resource, list):
self.my_add_group(self.resource, 'default_group')
elif isinstance(self.resource, dict):
for groupname, hosts_and_vars in self.resource.iteritems():
self.my_add_group(hosts_and_vars.get("hosts"), groupname, hosts_and_vars.get("vars"))
class MyRunner(MyInventory):
"""
This is a General object for parallel execute modules.
"""
def __init__(self, *args, **kwargs):
super(MyRunner, self).__init__(*args, **kwargs)
self.results_raw = {}
def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*',
become=False, become_method='sudo', become_user='root', become_pass='', transport='paramiko'):
"""
run module from andible ad-hoc.
module_name: ansible module_name
module_args: ansible module args
"""
hoc = Runner(module_name=module_name,
module_args=module_args,
timeout=timeout,
inventory=self.inventory,
pattern=pattern,
forks=forks,
become=become,
become_method=become_method,
become_user=become_user,
become_pass=become_pass,
transport=transport
)
self.results_raw = hoc.run()
# logger.debug(self.results_raw)
return self.results_raw
@property
def results(self):
"""
{'failed': {'localhost': ''}, 'ok': {'jumpserver': ''}}
"""
result = {'failed': {}, 'ok': {}}
dark = self.results_raw.get('dark')
contacted = self.results_raw.get('contacted')
if dark:
for host, info in dark.items():
result['failed'][host] = info.get('msg')
if contacted:
for host, info in contacted.items():
if info.get('invocation').get('module_name') in ['raw', 'shell', 'command', 'script']:
if info.get('rc') == 0:
result['ok'][host] = info.get('stdout') + info.get('stderr')
else:
result['failed'][host] = info.get('stdout') + info.get('stderr')
else:
if info.get('failed'):
result['failed'][host] = info.get('msg')
else:
result['ok'][host] = info.get('changed')
return result
class Command(MyInventory):
"""
this is a command object for parallel execute command.
"""
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
self.results_raw = {}
def run(self, command, module_name="command", timeout=10, forks=10, pattern=''):
"""
run command from andible ad-hoc.
command : 必须是一个需要执行的命令字符串, 比如
'uname -a'
"""
data = {}
if module_name not in ["raw", "command", "shell"]:
raise CommandValueError("module_name",
"module_name must be of the 'raw, command, shell'")
hoc = Runner(module_name=module_name,
module_args=command,
timeout=timeout,
inventory=self.inventory,
pattern=pattern,
forks=forks,
)
self.results_raw = hoc.run()
@property
def result(self):
result = {}
for k, v in self.results_raw.items():
if k == 'dark':
for host, info in v.items():
result[host] = {'dark': info.get('msg')}
elif k == 'contacted':
for host, info in v.items():
result[host] = {}
if info.get('stdout'):
result[host]['stdout'] = info.get('stdout')
elif info.get('stderr'):
result[host]['stderr'] = info.get('stderr')
return result
@property
def state(self):
result = {}
if self.stdout:
result['ok'] = self.stdout
if self.stderr:
result['err'] = self.stderr
if self.dark:
result['dark'] = self.dark
return result
@property
def exec_time(self):
"""
get the command execute time.
"""
result = {}
all = self.results_raw.get("contacted")
for key, value in all.iteritems():
result[key] = {
"start": value.get("start"),
"end" : value.get("end"),
"delta": value.get("delta"),}
return result
@property
def stdout(self):
"""
get the comamnd standard output.
"""
result = {}
all = self.results_raw.get("contacted")
for key, value in all.iteritems():
result[key] = value.get("stdout")
return result
@property
def stderr(self):
"""
get the command standard error.
"""
result = {}
all = self.results_raw.get("contacted")
for key, value in all.iteritems():
if value.get("stderr") or value.get("warnings"):
result[key] = {
"stderr": value.get("stderr"),
"warnings": value.get("warnings"),}
return result
@property
def dark(self):
"""
get the dark results.
"""
return self.results_raw.get("dark")
class MyTask(MyRunner):
"""
this is a tasks object for include the common command.
"""
def __init__(self, *args, **kwargs):
super(MyTask, self).__init__(*args, **kwargs)
def push_key(self, user, key_path):
"""
push the ssh authorized key to target.
"""
module_args = 'user="%s" key="{{ lookup("file", "%s") }}" state=present' % (user, key_path)
self.run("authorized_key", module_args, become=True)
return self.results
def push_multi_key(self, **user_info):
"""
push multi key
:param user_info:
:return:
"""
ret_failed = []
ret_success = []
for user, key_path in user_info.iteritems():
ret = self.push_key(user, key_path)
if ret.get("status") == "ok":
ret_success.append(ret)
if ret.get("status") == "failed":
ret_failed.append(ret)
if ret_failed:
return {"status": "failed", "msg": ret_failed}
else:
return {"status": "success", "msg": ret_success}
def del_key(self, user, key_path):
"""
push the ssh authorized key to target.
"""
module_args = 'user="%s" key="{{ lookup("file", "%s") }}" state="absent"' % (user, key_path)
self.run("authorized_key", module_args, become=True)
return self.results
def add_user(self, username, password=''):
"""
add a host user.
"""
if password:
encrypt_pass = sha512_crypt.encrypt(password)
module_args = 'name=%s shell=/bin/bash password=%s' % (username, encrypt_pass)
else:
module_args = 'name=%s shell=/bin/bash' % username
self.run("user", module_args, become=True)
return self.results
def add_multi_user(self, **user_info):
"""
add multi user
:param user_info: keyword args
{username: password}
:return:
"""
ret_success = []
ret_failed = []
for user, password in user_info.iteritems():
ret = self.add_user(user, password)
if ret.get("status") == "ok":
ret_success.append(ret)
if ret.get("status") == "failed":
ret_failed.append(ret)
if ret_failed:
return {"status": "failed", "msg": ret_failed}
else:
return {"status": "success", "msg": ret_success}
def del_user(self, username):
"""
delete a host user.
"""
module_args = 'name=%s state=absent remove=yes move_home=yes force=yes' % username
self.run("user", module_args, become=True)
return self.results
def del_user_sudo(self, username):
"""
delete a role sudo item
:param username:
:return:
"""
module_args = "sed -i 's/^%s.*//' /etc/sudoers" % username
self.run("command", module_args, become=True)
return self.results
@staticmethod
def gen_sudo_script(role_list, sudo_list):
# receive role_list = [role1, role2] sudo_list = [sudo1, sudo2]
# return sudo_alias={'NETWORK': '/sbin/ifconfig, /ls'} sudo_user={'user1': ['NETWORK', 'SYSTEM']}
sudo_alias = {}
sudo_user = {}
for sudo in sudo_list:
sudo_alias[sudo.name] = sudo.commands
for role in role_list:
sudo_user[role.name] = ','.join(sudo_alias.keys())
sudo_j2 = get_template('jperm/role_sudo.j2')
sudo_content = sudo_j2.render(Context({"sudo_alias": sudo_alias, "sudo_user": sudo_user}))
sudo_file = NamedTemporaryFile(delete=False)
sudo_file.write(sudo_content)
sudo_file.close()
return sudo_file.name
def push_sudo_file(self, role_list, sudo_list):
"""
use template to render pushed sudoers file
:return:
"""
module_args1 = self.gen_sudo_script(role_list, sudo_list)
self.run("script", module_args1, become=True)
return self.results
class CustomAggregateStats(callbacks.AggregateStats):
"""
Holds stats about per-host activity during playbook runs.
"""
def __init__(self):
super(CustomAggregateStats, self).__init__()
self.results = []
def compute(self, runner_results, setup=False, poll=False,
ignore_errors=False):
"""
Walk through all results and increment stats.
"""
super(CustomAggregateStats, self).compute(runner_results, setup, poll,
ignore_errors)
self.results.append(runner_results)
def summarize(self, host):
"""
Return information about a particular host
"""
summarized_info = super(CustomAggregateStats, self).summarize(host)
# Adding the info I need
summarized_info['result'] = self.results
return summarized_info
class MyPlaybook(MyInventory):
"""
this is my playbook object for execute playbook.
"""
def __init__(self, *args, **kwargs):
super(MyPlaybook, self).__init__(*args, **kwargs)
def run(self, playbook_relational_path, extra_vars=None):
"""
run ansible playbook,
only surport relational path.
"""
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
playbook_path = os.path.join(ANSIBLE_DIR, playbook_relational_path)
pb = PlayBook(
playbook=playbook_path,
stats=stats,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
inventory=self.inventory,
extra_vars=extra_vars,
check=False)
self.results = pb.run()
@property
def raw_results(self):
"""
get the raw results after playbook run.
"""
return self.results
class App(MyPlaybook):
"""
this is a app object for inclue the common playbook.
"""
def __init__(self, *args, **kwargs):
super(App, self).__init__(*args, **kwargs)
if __name__ == "__main__":
# resource = {
# "group1": {
# "hosts": [{"hostname": "127.0.0.1", "port": "22", "username": "root", "password": "xxx"},],
# "vars" : {"var1": "value1", "var2": "value2"},
# },
# }
resource = [{"hostname": "127.0.0.1", "port": "22", "username": "yumaojun", "password": "yusky0902",
# "ansible_become": "yes",
# "ansible_become_method": "sudo",
# # "ansible_become_user": "root",
# "ansible_become_pass": "yusky0902",
}]
cmd = Command(resource)
print cmd.run('ls')
# resource = [{"hostname": "192.168.10.148", "port": "22", "username": "root", "password": "xxx"}]
# task = Tasks(resource)
# print task.get_host_info()
# playbook = MyPlaybook(resource)
# playbook.run('test.yml')
# print playbook.raw_results
# task = Tasks(resource)
# print task.add_user('test', 'mypass')
# print task.del_user('test')
# print task.push_key('root', '/root/.ssh/id_rsa.pub')
# print task.del_key('root', '/root/.ssh/id_rsa.pub')
# task = Tasks(resource)
# print task.add_init_users()
# print task.del_init_users()

ansible 2.2.0

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
# _*_ encode:utf-8 _*_
import os
import sys
import logging
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.inventory.group import Group
from ansible.inventory.host import Host
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.plugins.callback import CallbackBase
logs = logging.basicConfig()
class ResultsCollector(CallbackBase):
def __init__(self, *args, **kwargs):
super(ResultsCollector, self).__init__(*args, **kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {}
def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result
def v2_runner_on_ok(self, result, *args, **kwargs):
self.host_ok[result._host.get_name()] = result
def v2_runner_on_failed(self, result, *args, **kwargs):
self.host_failed[result._host.get_name()] = result
class MyInventory(Inventory):
"""
this is my ansible inventory object.
"""
def __init__(self, resource, loader, variable_manager):
"""
resource的数据格式是一个列表字典,比如
{
"group1": {
"hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...],
"vars": {"var1": value1, "var2": value2, ...}
}
}
如果你只传入1个列表,这默认该列表内的所有主机属于my_group组,比如
[{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...]
"""
self.resource = resource
self.inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=[])
self.gen_inventory()
def my_add_group(self, hosts, groupname, groupvars=None):
"""
add hosts to a group
"""
my_group = Group(name=groupname)
# if group variables exists, add them to group
if groupvars:
for key, value in groupvars.iteritems():
my_group.set_variable(key, value)
# add hosts to group
for host in hosts:
# set connection variables
hostname = host.get("hostname")
hostip = host.get('ip', hostname)
hostport = host.get("port")
username = host.get("username")
password = host.get("password")
ssh_key = host.get("ssh_key")
my_host = Host(name=hostname, port=hostport)
my_host.set_variable('ansible_ssh_host', hostip)
my_host.set_variable('ansible_ssh_port', hostport)
my_host.set_variable('ansible_ssh_user', username)
my_host.set_variable('ansible_ssh_pass', password)
my_host.set_variable('ansible_ssh_private_key_file', ssh_key)
# set other variables
for key, value in host.iteritems():
if key not in ["hostname", "port", "username", "password"]:
my_host.set_variable(key, value)
# add to group
my_group.add_host(my_host)
self.inventory.add_group(my_group)
def gen_inventory(self):
"""
add hosts to inventory.
"""
if isinstance(self.resource, list):
self.my_add_group(self.resource, 'default_group')
elif isinstance(self.resource, dict):
for groupname, hosts_and_vars in self.resource.iteritems():
self.my_add_group(hosts_and_vars.get("hosts"), groupname, hosts_and_vars.get("vars"))
class AnsibleAPI(object):
"""
This is a General object for parallel execute modules.
"""
def __init__(self, resource, *args, **kwargs):
self.resource = resource
self.inventory = None
self.variable_manager = None
self.loader = None
self.options = None
self.passwords = None
self.callback = None
self.__initializeData()
self.results_raw = {}
def __initializeData(self):
"""
初始化ansible
"""
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'timeout', 'remote_user',
'ask_pass', 'private_key_file', 'ssh_common_args', 'ssh_extra_args',
'sftp_extra_args',
'scp_extra_args', 'become', 'become_method', 'become_user', 'ask_value_pass',
'verbosity',
'check', 'listhosts', 'listtasks', 'listtags', 'syntax'])
# initialize needed objects
self.variable_manager = VariableManager()
self.loader = DataLoader()
self.options = Options(connection='smart', module_path='/usr/share/ansible', forks=100, timeout=10,
remote_user='root', ask_pass=False, private_key_file=None, ssh_common_args=None,
ssh_extra_args=None,
sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
become_user='root', ask_value_pass=False, verbosity=None, check=False, listhosts=False,
listtasks=False, listtags=False, syntax=False)
self.passwords = dict(sshpass=None, becomepass=None)
self.inventory = MyInventory(self.resource, self.loader, self.variable_manager).inventory
self.variable_manager.set_inventory(self.inventory)
def run(self, host_list, module_name, module_args):
"""
run module from andible ad-hoc.
module_name: ansible module_name
module_args: ansible module args
"""
# create play with tasks
play_source = dict(
name="Ansible Play",
hosts=host_list,
gather_facts='no',
tasks=[dict(action=dict(module=module_name, args=module_args))]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
# actually run it
tqm = None
self.callback = ResultsCollector()
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
)
tqm._stdout_callback = self.callback
tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
def run_playbook(self, host_list, role_name, role_uuid, temp_param):
"""
run ansible palybook
"""
try:
self.callback = ResultsCollector()
filenames = ['' + '/handlers/ansible/v1_0/sudoers.yml'] # playbook的路径
template_file = '' # 模板文件的路径
if not os.path.exists(template_file):
sys.exit()
extra_vars = {} # 额外的参数 sudoers.yml以及模板中的参数,它对应ansible-playbook test.yml --extra-vars "host='aa' name='cc' "
host_list_str = ','.join([item for item in host_list])
extra_vars['host_list'] = host_list_str
extra_vars['username'] = role_name
extra_vars['template_dir'] = template_file
extra_vars['command_list'] = temp_param.get('cmdList')
extra_vars['role_uuid'] = 'role-%s' % role_uuid
self.variable_manager.extra_vars = extra_vars
# actually run it
executor = PlaybookExecutor(
playbooks=filenames, inventory=self.inventory, variable_manager=self.variable_manager,
loader=self.loader,
options=self.options, passwords=self.passwords,
)
executor._tqm._stdout_callback = self.callback
executor.run()
except Exception as e:
logs.error("error:", e.message)
def get_result(self):
self.results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
for host, result in self.callback.host_ok.items():
self.results_raw['success'][host] = result._result
for host, result in self.callback.host_failed.items():
self.results_raw['failed'][host] = result._result.get('msg') or result._result
for host, result in self.callback.host_unreachable.items():
self.results_raw['unreachable'][host] = result._result['msg']
return self.results_raw
################################################
调用
################################################
import json
from ansible_api import AnsibleAPI
class AnsiInterface(AnsibleAPI):
def __init__(self, resource, *args, **kwargs):
super(AnsiInterface, self).__init__(resource, *args, **kwargs)
@staticmethod
def deal_result(info):
host_ips = info.get('success').keys()
info['success'] = host_ips
error_ips = info.get('failed')
error_msg = {}
for key, value in error_ips.items():
temp = {}
temp[key] = value.get('stderr')
error_msg.update(temp)
info['failed'] = error_msg
return json.dumps(info)
def copy_file(self, host_list, src=None, dest=None):
"""
copy file
"""
module_args = "src=%s dest=%s"%(src, dest)
self.run(host_list, 'copy', module_args)
result = self.get_result()
return self.deal_result(result)
def exec_command(self, host_list, cmds):
"""
commands
"""
self.run(host_list, 'command', cmds)
result = self.get_result()
return self.deal_result(result)
def exec_script(self, host_list, path):
"""
在远程主机执行shell命令或者.sh脚本
"""
self.run(host_list, 'shell', path)
result = self.get_result()
return self.deal_result(result)
if __name__ == "__main__":
resource = [{"hostname": "172.20.3.18", "port": "22", "username": "root", "password": "password", "ip": '172.20.3.18'},
{"hostname": "172.20.3.31", "port": "22", "username": "root", "password": "password", "ip": '172.20.3.31'}]
interface = AnsiInterface(resource)
print "copy: ", interface.copy_file(['172.20.3.18', '172.20.3.31'], src='/Users/majing/test1.py', dest='/opt')
print "commands: ", interface.exec_command(['172.20.3.18', '172.20.3.31'], 'hostname')
print "shell: ", interface.exec_script(['172.20.3.18', '172.20.3.31'], 'chdir=/home ls')
print "shell: ", interface.exec_script(['172.20.3.18', '172.20.3.31'], 'sh /opt/test.sh')

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器