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()

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

華為手機如何實現雙微信登入?隨著社群媒體的興起,微信已成為人們日常生活中不可或缺的溝通工具之一。然而,許多人可能會遇到一個問題:在同一部手機上同時登入多個微信帳號。對於華為手機用戶來說,實現雙微信登入並不困難,本文將介紹華為手機如何實現雙微信登入的方法。首先,華為手機自帶的EMUI系統提供了一個很方便的功能-應用程式雙開。透過應用程式雙開功能,用戶可以在手機上同

程式語言PHP是一種用於Web開發的強大工具,能夠支援多種不同的程式設計邏輯和演算法。其中,實作斐波那契數列是一個常見且經典的程式設計問題。在這篇文章中,將介紹如何使用PHP程式語言來實作斐波那契數列的方法,並附上具體的程式碼範例。斐波那契數列是一個數學上的序列,其定義如下:數列的第一個和第二個元素為1,從第三個元素開始,每個元素的值等於前兩個元素的和。數列的前幾元

身為一名程式設計師,對於能夠簡化程式設計體驗的工具,我感到非常興奮。借助人工智慧工具的幫助,我們可以產生演示程式碼,並根據需求進行必要的修改。在VisualStudioCode中新引入的Copilot工具讓我們能夠創建具有自然語言聊天互動的AI生成程式碼。透過解釋功能,我們可以更好地理解現有程式碼的含義。如何使用Copilot產生程式碼?要開始,我們首先需要取得最新的PowerPlatformTools擴充。要實現這一點,你需要進入擴充頁面,搜尋“PowerPlatformTool”,然後點擊Install按鈕

小組件是Win11系統的新增功能,預設是開啟狀態,但是難免會出現有部分用戶不太使用到小組件,看著佔位置,因此想要禁用小組件的情況,那麼應該如何操作呢?下面小編就教大家操作方法,大家可以去試試看。什麼是小組件?小元件是小卡片,用於在Windows桌面上顯示你最喜愛的應用程式和服務中的動態內容。它們顯示在小組件板上,你可以在其中發現、固定、取消固定、排列、調整大小和自訂小組件以反映你的興趣。小組件板經過最佳化,可根據使用情況顯示相關小組件和個人化內容。從工作列的左角開啟小組件板,可在其中看到即時天氣

LSOF(ListOpenFiles)是一個命令列工具,主要用於監控類似Linux/Unix作業系統的系統資源。透過LSOF命令,使用者可以獲得有關係統中活動檔案以及正在存取這些檔案的進程的詳細資訊。 LSOF能夠幫助使用者識別目前佔用檔案資源的進程,從而更好地管理系統資源和排除可能的問題。 LSOF的功能強大且靈活,可以幫助系統管理員快速定位檔案相關的問題,例如檔案洩漏、未關閉的檔案描述符等。透過LSOF命令LSOF命令列工具允許系統管理員和開發人員:確定目前正在使用特定檔案或連接埠的進程,在連接埠衝突的情

Linuxldconfig指令詳解一、概述在Linux系統中,ldconfig是一個用來設定共享函式庫的指令。它用於更新共享庫的連結和快取,並使系統能夠正確載入動態連結共享庫。 ldconfig的主要作用是尋找動態連結庫並建立符號連結以供程式使用。本文將深入探討ldconfig指令的用法和工作原理,以及透過具體的程式碼範例來幫助讀者更好地理解ldconfig的功能

Linux重啟服務的正確方式是什麼?在使用Linux系統時,經常會遇到需要重新啟動某個服務的情況,但是有時我們可能會在重新啟動服務時遇到一些問題,例如服務沒有真正停止或啟動等情況。因此,掌握正確的重啟服務的方式是非常重要的。在Linux中,通常可以使用systemctl指令來管理系統服務。 systemctl指令是systemd系統管理員的一部分

如何在華為手機上實現微信分身功能隨著社群軟體的普及和人們對隱私安全的日益重視,微信分身功能逐漸成為人們關注的焦點。微信分身功能可以幫助使用者在同一台手機上同時登入多個微信帳號,方便管理和使用。在華為手機上實現微信分身功能並不困難,只需要按照以下步驟操作即可。第一步:確保手機系統版本和微信版本符合要求首先,確保你的華為手機系統版本已更新至最新版本,以及微信App
