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

ansible api实现命令异步执行

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

代码也可以在这里查看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
mysql:blob和其他无-SQL存储,有什么区别?mysql:blob和其他无-SQL存储,有什么区别?May 13, 2025 am 12:14 AM

mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而alenosqloptionslikemongodb,redis和calablesolutionsoluntionsoluntionsoluntionsolundortionsolunsolunsstructureddata.blobobobsimplobissimplobisslowderperformandperformanceperformancewithlararengelitiate;

mySQL添加用户:语法,选项和安全性最佳实践mySQL添加用户:语法,选项和安全性最佳实践May 13, 2025 am 12:12 AM

toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

MySQL:如何避免字符串数据类型常见错误?MySQL:如何避免字符串数据类型常见错误?May 13, 2025 am 12:09 AM

toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingsefectery.1)usecharforfixed lengengters lengengtings,varchar forbariaible lengength,varchariable length,andtext/blobforlabforlargerdata.2 seterters seterters seterters seterters

mySQL:字符串数据类型和枚举?mySQL:字符串数据类型和枚举?May 13, 2025 am 12:05 AM

mysqloffersechar,varchar,text,and denumforstringdata.usecharforfixed Lengttrings,varcharerforvariable长度,文本forlarger文本,andenumforenforcingDataAntegrityWithaEtofValues。

mysql blob:如何优化斑点请求mysql blob:如何优化斑点请求May 13, 2025 am 12:03 AM

优化MySQLBLOB请求可以通过以下策略:1.减少BLOB查询频率,使用独立请求或延迟加载;2.选择合适的BLOB类型(如TINYBLOB);3.将BLOB数据分离到单独表中;4.在应用层压缩BLOB数据;5.对BLOB元数据建立索引。这些方法结合实际应用中的监控、缓存和数据分片,可以有效提升性能。

将用户添加到MySQL:完整的教程将用户添加到MySQL:完整的教程May 12, 2025 am 12:14 AM

掌握添加MySQL用户的方法对于数据库管理员和开发者至关重要,因为它确保数据库的安全性和访问控制。1)使用CREATEUSER命令创建新用户,2)通过GRANT命令分配权限,3)使用FLUSHPRIVILEGES确保权限生效,4)定期审计和清理用户账户以维护性能和安全。

掌握mySQL字符串数据类型:varchar vs.文本与char掌握mySQL字符串数据类型:varchar vs.文本与charMay 12, 2025 am 12:12 AM

chosecharforfixed-lengthdata,varcharforvariable-lengthdata,andtextforlargetextfield.1)chariseffity forconsistent-lengthdatalikecodes.2)varcharsuitsvariable-lengthdatalikenames,ballancingflexibilitibility andperformance.3)

MySQL:字符串数据类型和索引:最佳实践MySQL:字符串数据类型和索引:最佳实践May 12, 2025 am 12:11 AM

在MySQL中处理字符串数据类型和索引的最佳实践包括:1)选择合适的字符串类型,如CHAR用于固定长度,VARCHAR用于可变长度,TEXT用于大文本;2)谨慎索引,避免过度索引,针对常用查询创建索引;3)使用前缀索引和全文索引优化长字符串搜索;4)定期监控和优化索引,保持索引小巧高效。通过这些方法,可以在读取和写入性能之间取得平衡,提升数据库效率。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。