代码也可以在这里查看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()

提到API开发,你可能会想到DjangoRESTFramework,Flask,FastAPI,没错,它们完全可以用来编写API,不过,今天分享的这个框架可以让你更快把现有的函数转化为API,它就是Sanic。Sanic简介Sanic[1],是Python3.7+Web服务器和Web框架,旨在提高性能。它允许使用Python3.5中添加的async/await语法,这可以有效避免阻塞从而达到提升响应速度的目的。Sanic致力于提供一种简单且快速,集创建和启动于一体的方法

机器人也能干咖啡师的活了!比如让它把奶泡和咖啡搅拌均匀,效果是这样的:然后上点难度,做杯拿铁,再用搅拌棒做个图案,也是轻松拿下:这些是在已被ICLR 2023接收为Spotlight的一项研究基础上做到的,他们推出了提出流体操控新基准FluidLab以及多材料可微物理引擎FluidEngine。研究团队成员分别来自CMU、达特茅斯学院、哥伦比亚大学、MIT、MIT-IBM Watson AI Lab、马萨诸塞大学阿默斯特分校。在FluidLab的加持下,未来机器人处理更多复杂场景下的流体工作也都

本篇文章给大家带来了关于API的相关知识,其中主要介绍了设计API需要注意哪些地方?怎么设计一个优雅的API接口,感兴趣的朋友,下面一起来看一下吧,希望对大家有帮助。

Ansible工作原理从上面的图上可以了解到:管理端支持local、ssh、zeromq三种方式连接被管理端,默认使用基于ssh的连接,这部分对应上面架构图中的连接模块;可以按应用类型等方式进行HostInventory(主机清单)分类,管理节点通过各类模块实现相应的操作,单个模块,单条命令的批量执行,我们可以称之为ad-hoc;管理节点可以通过playbooks实现多个task的集合实现一类功能,如web服务的安装部署、数据库服务器的批量备份等。playbooks我们可以简单的理解为,系统通过

当您的WindowsPC出现网络问题时,问题出在哪里并不总是很明显。很容易想象您的ISP有问题。然而,Windows笔记本电脑上的网络并不总是顺畅的,Windows11中的许多东西可能会突然导致Wi-Fi网络中断。随机消失的Wi-Fi网络是Windows笔记本电脑上报告最多的问题之一。网络问题的原因各不相同,也可能因Microsoft的驱动程序或Windows而发生。Windows是大多数情况下的问题,建议使用内置的网络故障排除程序。在Windows11

收到项目反馈,客户在使用我们提供的工具部署产品时遇到了困难,在主机添加步骤上遇到了问题,导致实施团队无法继续推进工作,因此向我们寻求帮助。环境信息:kylin10架构:arm初见端倪在系统部署过程中,针对主机的批量操作,我们开发时采用了ansible剧本。最近遇到了执行过程卡顿的问题,初步怀疑是ansible执行时出现了阻塞。为了验证这一点,我已经发送了一条命令给现场进行测试。localhost$date2024年02月19日星期17:30:41CSTlocalhost$ansibleall-i

Ansible是一种开源的自动化配置管理和部署工具,可以帮助管理员在多台服务器上自动执行任务。在Ansible中,Playbook是用于描述自动化任务的YAML文件。使用变量(variables)是Playbook功能的一个重要部分,它可以让你的Playbook更灵活、可重用和易于维护。以下是AnsiblePlaybook中变量的一些基本用法:定义变量:可以在Playbook、inventory文件、vars文件或者使用-e参数在命令行中定义变量。例子:在Playbook中定义变量:----na

Linux作为一种强大的操作系统,其远程管理工具被广泛应用于服务器管理、网络监控等方面。在日常工作中,我们经常需要使用一些专门的工具来远程管理Linux服务器。本文将介绍五款实用的Linux远程管理工具,并提供具体的代码示例来演示它们的用法。1.SSHSSH(SecureShell)是一种加密网络协议,用于安全地远程登录和执行命令。通过SSH,用户可以在


Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

AI Hentai Generator
Menjana ai hentai secara percuma.

Artikel Panas

Alat panas

DVWA
Damn Vulnerable Web App (DVWA) ialah aplikasi web PHP/MySQL yang sangat terdedah. Matlamat utamanya adalah untuk menjadi bantuan bagi profesional keselamatan untuk menguji kemahiran dan alatan mereka dalam persekitaran undang-undang, untuk membantu pembangun web lebih memahami proses mengamankan aplikasi web, dan untuk membantu guru/pelajar mengajar/belajar dalam persekitaran bilik darjah Aplikasi web keselamatan. Matlamat DVWA adalah untuk mempraktikkan beberapa kelemahan web yang paling biasa melalui antara muka yang mudah dan mudah, dengan pelbagai tahap kesukaran. Sila ambil perhatian bahawa perisian ini

PhpStorm versi Mac
Alat pembangunan bersepadu PHP profesional terkini (2018.2.1).

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

MinGW - GNU Minimalis untuk Windows
Projek ini dalam proses untuk dipindahkan ke osdn.net/projects/mingw, anda boleh terus mengikuti kami di sana. MinGW: Port Windows asli bagi GNU Compiler Collection (GCC), perpustakaan import yang boleh diedarkan secara bebas dan fail pengepala untuk membina aplikasi Windows asli termasuk sambungan kepada masa jalan MSVC untuk menyokong fungsi C99. Semua perisian MinGW boleh dijalankan pada platform Windows 64-bit.

ZendStudio 13.5.1 Mac
Persekitaran pembangunan bersepadu PHP yang berkuasa
