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으로 문의하세요.

인기 기사
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌

인기 기사
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제
Gmail 이메일의 로그인 입구는 어디에 있나요?
7286
9


자바 튜토리얼
1622
14


Cakephp 튜토리얼
1342
46


라라벨 튜토리얼
1259
25


PHP 튜토리얼
1206
29



Huawei 휴대폰에서 이중 WeChat 로그인을 구현하는 방법은 무엇입니까?

Golang이 어떻게 게임 개발 가능성을 가능하게 하는지 마스터하세요

칭화대학교와 Zhipu AI 오픈 소스 GLM-4: 자연어 처리의 새로운 혁명 시작
