#!/usr/bin/env python
# -*- coding: utf8 -*-
# @Author: huangmanyao
from ansible import constants
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
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
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import VariableManager
import json
import IPy class ModelResultsCollector(CallbackBase):
''' 重构执行结果 '''
def __init__(self, *args, **kwargs):
super(ModelResultsCollector, 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 PlayBookResultsCollector(CallbackBase):
CALLBACK_VERSION = 2.0 def __init__(self, *args, **kwargs):
super(PlayBookResultsCollector, self).__init__(*args, **kwargs)
self.task_ok = {}
self.task_skipped = {}
self.task_failed = {}
self.task_status = {}
self.task_unreachable = {} def v2_runner_on_ok(self, result, *args, **kwargs):
self.task_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs):
self.task_failed[result._host.get_name()] = result def v2_runner_on_unreachable(self, result):
self.task_unreachable[result._host.get_name()] = result def v2_runner_on_skipped(self, result):
self.task_ok[result._host.get_name()] = result def v2_playbook_on_stats(self, stats):
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
self.task_status[h] = {
"ok": t['ok'],
"changed": t['changed'],
"unreachable": t['unreachable'],
"skipped": t['skipped'],
"failed": t['failures']
} class ANSRunner(object):
"""
This is a General object for parallel execute modules.
""" def __init__(self, ips=None, *args, **kwargs):
self.ips = ips
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 is_ip(self,address):
try:
IPy.IP(address)
return True
except Exception as e:
return False def list_to_str(self,ips):
ipsstr = ','.join(ips)
if len(ips) == 1:
ipsstr += ','
return ipsstr def list_ip_check(self,ips):
ipslist = ips
ipslist_len = len(ips)
if ipslist_len > 1:
for ip in ipslist:
if not self.is_ip(ip):
ipslist.remove(ip)
return ipslist def ips_cov_str(self):
if not self.ips:
self.ips = "127.0.0.1" if isinstance(self.ips,list):
self.ips = self.list_ip_check(self.ips)
self.ips = self.list_to_str(self.ips) elif isinstance(self.ips,str):
ipslist = self.ips.split(',')
ipslist = self.list_ip_check(ipslist)
self.ips = self.list_to_str(ipslist) 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', 'diff']) self.options = Options(connection='smart', module_path=None, 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, diff=True) self.loader = DataLoader()
self.ips_cov_str()
self.inventory = InventoryManager(loader=self.loader, sources='%s'%(self.ips))
self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory) def run_model(self, module_name, module_args):
"""
run module from andible ad-hoc.
module_name: ansible module_name
module_args: ansible module args
"""
self.ips_cov_str() play_source = dict(
name="Ansible Play",
hosts=self.ips,
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)
tqm = None
self.callback = ModelResultsCollector()
import traceback
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback="minimal",
)
tqm._stdout_callback = self.callback
constants.HOST_KEY_CHECKING = False # 关闭第一次使用ansible连接客户端是输入命令
tqm.run(play)
except Exception as err:
print(traceback.print_exc())
finally:
if tqm is not None:
tqm.cleanup() def run_playbook(self, playbook_path, extra_vars=None):
"""
运行playbook
"""
try:
self.callback = PlayBookResultsCollector()
if extra_vars:
self.variable_manager.extra_vars = extra_vars
executor = PlaybookExecutor(
playbooks=[playbook_path], inventory=self.inventory, variable_manager=self.variable_manager,
loader=self.loader,
options=self.options, passwords=self.passwords,
)
executor._tqm._stdout_callback = self.callback
constants.HOST_KEY_CHECKING = False # 关闭第一次使用ansible连接客户端是输入命令
executor.run()
except Exception as err:
return False def get_model_result(self):
self.results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
for host, result in self.callback.host_ok.items():
hostvisiable = host.replace('.', '_')
self.results_raw['success'][hostvisiable] = result._result for host, result in self.callback.host_failed.items():
hostvisiable = host.replace('.', '_')
self.results_raw['failed'][hostvisiable] = result._result for host, result in self.callback.host_unreachable.items():
hostvisiable = host.replace('.', '_')
self.results_raw['unreachable'][hostvisiable] = result._result return self.results_raw def get_playbook_result(self):
self.results_raw = {'skipped': {}, 'failed': {}, 'ok': {}, "status": {}, 'unreachable': {}, "changed": {}}
for host, result in self.callback.task_ok.items():
self.results_raw['ok'][host] = result._result for host, result in self.callback.task_failed.items():
self.results_raw['failed'][host] = result._result for host, result in self.callback.task_status.items():
self.results_raw['status'][host] = result for host, result in self.callback.task_skipped.items():
self.results_raw['skipped'][host] = result._result for host, result in self.callback.task_unreachable.items():
self.results_raw['unreachable'][host] = result._result
return self.results_raw
if __name__ == '__main__':
a="192.168.111.137,127.0.0.1"
rbt = ANSRunner(a)
# rbt.run_playbook(playbook_path='test.yml')
# result = json.dumps(rbt.get_playbook_result(),indent=4)
# rbt.run_model('shell','uptime')
# rbt.run_model('shell','/app/tmp/startproxy.sh')
# rbt.run_model('script','/app/fusionwork_scripts/os_script/add_host.sh')
rbt.run_model('shell', 'cat /etc/hostname')
# rbt.run_model('copy', 'src=/app/fusionwork_scripts/os_script/openresty.tgz dest=/home/mwopr/')
result = json.dumps(rbt.get_model_result(),indent=4)
print(result)
 

Python中ansible的使用的更多相关文章

  1. Python调用ansible API系列(一)获取资产信息

    你想让ansible工作首先就需要设置资产信息,那么我们如何通过使用Python调取Ansible的API来获取资产信息呢? 要提前准备一个hosts文件 获取组或者主机 #!/usr/bin/env ...

  2. Python 中的 10 个常见安全漏洞,以及如何避免(上)

    简评:编写安全代码很困难,当你学习一个编程语言.模块或框架时,你会学习其使用方法. 在考虑安全性时,你需要考虑如何避免被滥用,Python 也不例外,即使在标准库中,也存在用于编写应用的不良实践.然而 ...

  3. Linux中ansible批量管理软件部署及剧本编写

    服务器版本信息: Centos6.9 [root@db02 ~]# uname -a Linux db02 2.6.32-696.el6.x86_64 #1 SMP Tue Mar 21 19:29: ...

  4. python中对 函数 闭包 的理解

    最近学到 函数 闭包的时候,似懂非懂.迷迷糊糊的样子,很是头疼,今天就特意查了下关于闭包的知识,现将我自己的理解分享如下! 一.python 闭包定义 首先,关于闭包,百度百科是这样解释的: 闭包是指 ...

  5. Python+Django+ansible playbook自动化运维项目实战☝☝☝

    Python+Django+ansible playbook自动化运维项目实战☝☝☝  一.入门引导 DevOPSDevOps(英文Development和Operations的组合)是一组过程.方法 ...

  6. [转]Python中的str与unicode处理方法

    早上被python的编码搞得抓耳挠腮,在搜资料的时候感觉这篇博文很不错,所以收藏在此. python2.x中处理中文,是一件头疼的事情.网上写这方面的文章,测次不齐,而且都会有点错误,所以在这里打算自 ...

  7. python中的Ellipsis

    ...在python中居然是个常量 print(...) # Ellipsis 看别人怎么装逼 https://www.keakon.net/2014/12/05/Python%E8%A3%85%E9 ...

  8. python中的默认参数

    https://eastlakeside.gitbooks.io/interpy-zh/content/Mutation/ 看下面的代码 def add_to(num, target=[]): tar ...

  9. Python中的类、对象、继承

    类 Python中,类的命名使用帕斯卡命名方式,即首字母大写. Python中定义类的方式如下: class 类名([父类名[,父类名[,...]]]): pass 省略父类名表示该类直接继承自obj ...

随机推荐

  1. 虚拟DOM Vitural DOM Tree

      提起Virtual DOM,总是给人一种高深莫测的感觉,大家都知道它比DOM快.那么Virtual DOM到底是何方神圣呢?在深入理解Virtual DOM之前,先让我们回顾一下DOM. 一.什么 ...

  2. MSSQL系列 (二):表相关操作、列操作、(唯一、主键、默认、检查、外键、非空)约束、临时表

    1.创建表 --创建学生班级表 create table StuClass ( ClassId int primary key, --班级ID 主键约束 ClassName nvarchar(30) ...

  3. abp vnext 开发快速入门 3 实现权限控制

    上篇讲了abp vnext 实现了简单的增加操作的例子.删除更新查询基本类似,这里就不讲了,接下来说下如何实现角色权限控制. 再说之前,先说下如果想更加透彻的理解abp vnext的权限控制,最好是先 ...

  4. 关于node-sass安装失败问题

    在进行Vue开发中npm run dev报错,按照提示尝试进行npm以及cnpm安装均失败 解决办法:npm uninstall node-sass卸载模块 指定淘宝镜像源安装 npm i node- ...

  5. Python过滤掉numpy.array中非nan数据实例

    代码 需要先导入pandas arr的数据类型为一维的np.array import pandas as pd arr[~pd.isnull(arr)] 补充知识:python numpy.mean( ...

  6. ubuntu安装 jdk

    首先查一下当前JDK的版本 ,一般是系统自带Jdk$ java -version 然后根据版本8安装完整版的OpenJDK $ sudo apt-get install openjdk-8-jdk 如 ...

  7. laravel 验证码使用示例

    一.去https://packagist.org/网站搜索验证码的代码依赖,关键词:captcha 地址:https://packagist.org/packages/mews/captcha 二.环 ...

  8. http与https的简单比较

    一.概念 1.HTTP:是互联网上应用最为广泛的一种网络协议,是一个客户端和服务器端请求和应答的标准(TCP),用于从WWW服务器传输超文本到本地浏览器的传输协议,它可以使浏览器更加高效,使网络传输减 ...

  9. Fortify Audit Workbench Cookie Security: Cookie not Sent Over SSL

    Abstract 所创建的 cookie 的 secure 标记没有设置为 true. Explanation 现今的 Web 浏览器支持每个 cookie 的 secure 标记. 如果设置了该标记 ...

  10. UltraISO制作系统安装盘

    转载自: 原文链接 本文介绍使用UltraISO(软碟通)制作U盘启动来安装Win10系统,会装win10,其他的系统也大同小异,适用于当原系统损坏.崩溃.升级异常导致系统不能开机时重装,相对比< ...