首页 数据库 mysql教程 ansible api实现命令异步执行

ansible api实现命令异步执行

Jun 07, 2016 pm 04:39 PM
ansible api 代码 命令 实现 异步 执行

代码也可以在这里查看https://github.com/ivonlee/ansible/blob/master/ansible_api_async_run.py

tornado上实现ansible api异步执行,方便php写的运维后台调用,当然php后台还是要做一个类似于队列的东西,将任务存在redis或者mongodb里面,然后有个php进程持续监听任务队列。

相关mysql视频教程推荐:《mysql教程

下面的脚本运行后,可以用类似POSTMAN工具进行post数据测试,如果你的平台本来就是python的,那更方便了,自己写个简陋的web界面,直接执行了,不用tornado做web容器了。

mongodb里面的表信息,ansible_task是收到的任务,ansible_job里面有任务执行结果

上代码,python比较搓,求大牛带我

import tornado.ioloop
from tornado.options import define, options
import tornado.web
import ansible.runner
from ansible.inventory import Inventory
import simplejson
import hashlib
from pymongo import MongoClient
from bson.objectid import ObjectId
import os
import sys
import time
from psutil import Process
import datetime
from threading import Thread
define("key", default='d41d8cd98f00b204e9800998ecf8427e')
mongoinfo = {"host": "127.0.0.1", "port": "27017", "user":
    "ops", "password": "ops", "dbname": "ansible_log"}
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
WORKER_TIMEOUT = 5 * 60
NUMBER_OF_TASK_PER_PAGE = 25
ANSIBLE_FORKS = 30
ANSIBLE_INVENTORY = '/etc/ansible/hosts'
def getmd5(str):
    m = hashlib.md5()
    m.update(str)
    return m.hexdigest()
def ConnMongoDB():
    global mongoinfo
    dbhost = mongoinfo['host']
    dbport = mongoinfo['port']
    dbuser = mongoinfo['user']
    dbpwd = mongoinfo['password']
    dbname = mongoinfo['dbname']
    uri = 'mongodb://%s:%s@%s/%s' % (dbuser, dbpwd, dbhost, dbname)
    return uri
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
class CommandHandler(tornado.web.RequestHandler):
    def post(self):
        data = simplejson.loads(self.request.body) 
        badcmd = ['reboot','rm','kill','pkill','shutdown','half','mv','dd','mkfs','>','wget']
        type = data['type']
        cmd = data['cmd']
        host = data['host']
        print host
        sign = data['sign']
        isudo = data['sudo']
        cmdinfo = cmd.split(" ",1)
        print type,host,options.key
        hotkey = type+host+options.key
        print hotkey
        result = getmd5(hotkey)
        print result
        if sign != result:
            self.write("Sign is Error")
        else:
          if cmdinfo[0] in badcmd:
            self.write("This is Danger Shell")
          else:
            if "," in host:
               inventory = host.split(",")
               for host in inventory:
                   runner = ansible.runner.Runner(
                     module_name=type,
                     module_args=cmd,
                     pattern=host,
                     sudo = isudo,
                     forks=ANSIBLE_FORKS
                   )
                   result = runner.run()
                   now = datetime.datetime.now()
                   true = 'True'
                   result['time'] = now.strftime(TIME_FORMAT)
                   result['type'] = 'ad-hoc'
                   result['sudo'] = isudo
                   result['cmd'] = cmd
                   result['inventory'] = host
                   self.write(result)
                   uri = ConnMongoDB()
                   client = MongoClient(uri, safe=False)
                   db = client.ansible_log
                   db.ad_hoc.insert(result)
            else:
               runner = ansible.runner.Runner(
                     module_name=type,
                     module_args=cmd,
                     pattern=host,
                     sudo = isudo,
                     forks=ANSIBLE_FORKS
               )
               result = runner.run()
               now = datetime.datetime.now()
               true = 'True'
               result['time'] = now.strftime(TIME_FORMAT)
               result['type'] = 'ad-hoc'
               result['sudo'] = isudo
               result['cmd'] = cmd
               result['inventory'] = inventory
               self.write(result)
               uri = ConnMongoDB()
               client = MongoClient(uri, safe=False)
               db = client.ansible_log
               db.ad_hoc.insert(result)
class AsyncTaskHandler(tornado.web.RequestHandler):
    def post(self):
        data = simplejson.loads(self.request.body)
        badcmd = ['reboot', 'rm', 'kill', 'pkill',
                  'shutdown', 'half', 'mv', 'dd', 'mkfs', '>', 'wget']
        type = data['type']
        cmd = data['cmd']
        inventory = data['host']
        sign = data['sign']
        isudo = data['sudo']
        cmdinfo = cmd.split(" ", 1)
        print type, inventory, options.key
        hotkey = type + inventory + options.key
        print hotkey
        result = getmd5(hotkey)
        print result
        now = datetime.datetime.now()
        taskinfo = {}
        taskinfo['mode'] = type
        taskinfo['cmd'] = cmd
        taskinfo['inventory'] = inventory
        taskinfo['type'] = 'async ad-hoc'
        taskinfo['start'] = now.strftime(TIME_FORMAT)
        taskinfo['sudo'] = isudo
        uri = ConnMongoDB()
        client = MongoClient(uri, safe=False)
        db = client.ansible_log
        id=db.ansible_task.insert(taskinfo)
        mongoid={"_id":ObjectId(id)}
        print id
        if sign != result:
            self.write("Sign is Error")
        else:
            if cmdinfo[0] in badcmd:
                self.write("This is Danger Shell")
            else:
                runner = ansible.runner.Runner(
                    module_name=type,
                    module_args=cmd,
                    pattern=inventory,
                    sudo = isudo,
                    forks=ANSIBLE_FORKS
                )
                _, res = runner.run_async(time_limit = WORKER_TIMEOUT)
                now = time.time()
                while True:
                  if res.completed or time.time() - now > WORKER_TIMEOUT:
                      break
                  results = res.poll()
                  results = results.get('contacted')
                  if results:
                     for result in results.items():
                       jobinfo = {}
                       data = result[1]
                       print data
                       inventory = result[0]
                       jobinfo['inventory']=inventory
                       jobinfo['job_id']=data['ansible_job_id']
                       jobinfo['cmd']=data['cmd']
                       jobinfo['task_id']=id
                       uri = ConnMongoDB()
                       client = MongoClient(uri, safe=False)
                       db = client.ansible_log
                       id2 = db.ansible_job.insert(jobinfo)
                       mongoid2 = {"_id":ObjectId(id2)}
                       if data['rc'] == 0 :
                         thisinfo2 = db.ansible_job.find_one(mongoid2)
                         thisinfo2['rc']=data['rc']
                         thisinfo2['stdout']=data['stdout']
                         thisinfo2['stderr']=data['stderr']
                         db.ansible_job.save(thisinfo2)
                         thisinfo = db.ansible_task.find_one(mongoid)
                         thisinfo['end'] = data['end'] 
                         thisinfo['rc'] = data['rc']
                         db.ansible_task.save(thisinfo)
                       elif data['rc'] == 1 :
                         thisinfo2 = db.ansible_job.find_one(mongoid2)
                         thisinfo2['rc']=data['rc']
                         thisinfo2['stderr']=data['stderr']
                         db.ansible_job.save(thisinfo2)
                         thisinfo = db.ansible_task.find_one(mongoid)
                         thisinfo['rc'] = data['rc']
                         db.ansible_task.save(thisinfo)
                       else:
                         thisinfo2 = db.ansible_job.find_one(mongoid2)
                         thisinfo2['rc']=data['rc']
                         thisinfo2['stderr']=data['msg']
                         db.ansible_job.save(thisinfo2)
                         thisinfo = db.ansible_task.find_one(mongoid)
                         thisinfo['rc'] = data['rc']
                         db.ansible_task.save(thisinfo)
                time.sleep(2)
class GetGroupHandler(tornado.web.RequestHandler):
    def get(self):
        i = Inventory()
        groups = i.list_groups()
        self.write('\n'.join(groups))
application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/asynctask", AsyncTaskHandler),
    (r"/command", CommandHandler),
    (r"/getgroup", GetGroupHandler),
])
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
登录后复制

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

华为手机如何实现双微信登录? 华为手机如何实现双微信登录? Mar 24, 2024 am 11:27 AM

华为手机如何实现双微信登录?随着社交媒体的兴起,微信已经成为人们日常生活中不可或缺的沟通工具之一。然而,许多人可能会遇到一个问题:在同一部手机上同时登录多个微信账号。对于华为手机用户来说,实现双微信登录并不困难,本文将介绍华为手机如何实现双微信登录的方法。首先,华为手机自带的EMUI系统提供了一个很便利的功能——应用双开。通过应用双开功能,用户可以在手机上同

PHP编程指南:实现斐波那契数列的方法 PHP编程指南:实现斐波那契数列的方法 Mar 20, 2024 pm 04:54 PM

编程语言PHP是一种用于Web开发的强大工具,能够支持多种不同的编程逻辑和算法。其中,实现斐波那契数列是一个常见且经典的编程问题。在这篇文章中,将介绍如何使用PHP编程语言来实现斐波那契数列的方法,并附上具体的代码示例。斐波那契数列是一个数学上的序列,其定义如下:数列的第一个和第二个元素为1,从第三个元素开始,每个元素的值等于前两个元素的和。数列的前几个元

如何在华为手机上实现微信分身功能 如何在华为手机上实现微信分身功能 Mar 24, 2024 pm 06:03 PM

如何在华为手机上实现微信分身功能随着社交软件的普及和人们对隐私安全的日益重视,微信分身功能逐渐成为人们关注的焦点。微信分身功能可以帮助用户在同一台手机上同时登录多个微信账号,方便管理和使用。在华为手机上实现微信分身功能并不困难,只需要按照以下步骤操作即可。第一步:确保手机系统版本和微信版本符合要求首先,确保你的华为手机系统版本已更新到最新版本,以及微信App

Linux 重启服务的正确方式是什么? Linux 重启服务的正确方式是什么? Mar 15, 2024 am 09:09 AM

Linux重启服务的正确方式是什么?在使用Linux系统时,经常会遇到需要重启某个服务的情况,但是有时候我们可能会在重启服务时遇到一些问题,比如服务没有真正停止或启动等情况。因此,掌握正确的重启服务的方式是非常重要的。在Linux中,通常可以使用systemctl命令来管理系统服务。systemctl命令是systemd系统管理器的一部分

如何使用LSOF实时监控端口 如何使用LSOF实时监控端口 Mar 20, 2024 pm 02:07 PM

LSOF(ListOpenFiles)是一个命令行工具,主要用于监控类似Linux/Unix操作系统的系统资源。通过LSOF命令,用户可以获取有关系统中活动文件以及正在访问这些文件的进程的详细信息。LSOF能够帮助用户识别当前占用文件资源的进程,从而更好地管理系统资源和排除可能的问题。LSOF的功能强大且灵活,可以帮助系统管理员快速定位文件相关的问题,如文件泄漏、未关闭的文件描述符等。通过LSOF命令LSOF命令行工具允许系统管理员和开发人员:确定当前正在使用特定文件或端口的进程,在端口冲突的情

Linux ldconfig命令详解 Linux ldconfig命令详解 Mar 14, 2024 pm 12:18 PM

Linuxldconfig命令详解一、概述在Linux系统中,ldconfig是一个用于配置共享库的命令。它用于更新共享库的链接和缓存,并使系统能够正确加载动态链接共享库。ldconfig的主要作用是查找动态链接库并创建符号链接以供程序使用。本文将深入探讨ldconfig命令的用法和工作原理,以及通过具体的代码示例来帮助读者更好地理解ldconfig的功能

掌握Golang如何实现游戏开发的可能性 掌握Golang如何实现游戏开发的可能性 Mar 16, 2024 pm 12:57 PM

在当今的软件开发领域中,Golang(Go语言)作为一种高效、简洁、并发性强的编程语言,越来越受到开发者的青睐。其丰富的标准库和高效的并发特性使它成为游戏开发领域的一个备受关注的选择。本文将探讨如何利用Golang来实现游戏开发,并通过具体的代码示例来展示其强大的可能性。1.Golang在游戏开发中的优势作为一种静态类型语言,Golang在构建大型游戏系统

win11小组件怎么删除? 一条命令卸载 Windows11小组件功能技巧 win11小组件怎么删除? 一条命令卸载 Windows11小组件功能技巧 Apr 11, 2024 pm 05:19 PM

小组件是Win11系统的新增功能,默认是开启状态,但是难免会出现有部分用户不太使用到小组件,看着占位置,因此想要禁用小组件的情况,那么应该如何操作呢?下面小编就教给大家操作方法,大家可以去尝试看看。什么是小组件?小组件是小卡片,用于在Windows桌面上显示你最喜爱的应用和服务中的动态内容。它们显示在小组件板上,你可以在其中发现、固定、取消固定、排列、调整大小和自定义小组件以反映你的兴趣。小组件板经过优化,可根据使用情况显示相关小组件和个性化内容。从任务栏的左角打开小组件板,可在其中看到实时天气

See all articles