検索

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でビューを使用することの限界は何ですか?MySQLでビューを使用することの限界は何ですか?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)supportallsqloperations、制限、dataManipulationswithjoinsorubqueries.2)それらは、特にパフォーマンス、特にパルフェクソルラージャターセット

MySQLデータベースのセキュリティ:ユーザーの追加と特権の付与MySQLデータベースのセキュリティ:ユーザーの追加と特権の付与May 14, 2025 am 12:09 AM

reperusermanmanagementInmysqliscialforenhancingsecurationsinginuring databaseaperation.1)usecreateusertoaddusers、指定connectionsourcewith@'localhost'or@'% '。

MySQLで使用できるトリガーの数にどのような要因がありますか?MySQLで使用できるトリガーの数にどのような要因がありますか?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers、しかしpracticalfactorsdeTerminetheireffectiveuse:1)serverconufigurationStriggermanagement; 2)complentiggersincreaseSystemload;

mysql:Blobを保管しても安全ですか?mysql:Blobを保管しても安全ですか?May 14, 2025 am 12:07 AM

はい、それはssafetostoreblobdatainmysql、butonsiderheSeCactors:1)Storagespace:blobscanconsumesificantspace.2)パフォーマンス:パフォーマンス:大規模なドゥエットブロブスメイズ階下3)backupandrecized recized recized recize

MySQL:PHP Webインターフェイスを介してユーザーを追加しますMySQL:PHP Webインターフェイスを介してユーザーを追加しますMay 14, 2025 am 12:04 AM

PHP Webインターフェイスを介してMySQLユーザーを追加すると、MySQLI拡張機能を使用できます。手順は次のとおりです。1。MySQLデータベースに接続し、MySQLI拡張機能を使用します。 2。ユーザーを作成し、CreateUserステートメントを使用し、パスワード()関数を使用してパスワードを暗号化します。 3. SQLインジェクションを防ぎ、MySQLI_REAL_ESCAPE_STRING()関数を使用してユーザー入力を処理します。 4.新しいユーザーに権限を割り当て、助成金ステートメントを使用します。

MySQL:BLOBおよびその他のNO-SQLストレージ、違いは何ですか?MySQL:BLOBおよびその他のNO-SQLストレージ、違いは何ですか?May 13, 2025 am 12:14 AM

mysql'sblobissuitable forstoringbinarydatawithinarationaldatabase、whileenosqloptionslikemongodb、redis、andcassandraofferferulesions forunstructureddata.blobissimplerbutcanslowdowdowd withwithdata

MySQLユーザーの追加:構文、オプション、セキュリティのベストプラクティスMySQLユーザーの追加:構文、オプション、セキュリティのベストプラクティスMay 13, 2025 am 12:12 AM

toaddauserinmysql、使用:createuser'username '@' host'identifidedby'password '; here'showtodoitsely:1)chosehostcarefilytoconを選択しますTrolaccess.2)setResourcelimitslikemax_queries_per_hour.3)usestrong、uniquasswords.4)endforcessl/tlsconnectionswith

MySQL:文字列データ型の一般的な間違いを回避する方法MySQL:文字列データ型の一般的な間違いを回避する方法May 13, 2025 am 12:09 AM

toavoidcommonMonmistakeswithStringDatatypesinmysql、undultingStringTypenuste、choosetherightType、andManageEncodingandCollat​​ionsEttingtingive.1)U​​secharforfixed-LengthStrings、Varcharforaible Length、AndText/Blobforlardata.2)setCurrectCherts

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!