通過flask架構寫成http介面調用Ansible

來源:互聯網
上載者:User

標籤:ansible

#*******一、flask_ansible.py檔案#!/usr/bin/env python#_*_ coding:utf-8 _*_import jsonfrom flask import Flask,requestfrom ansible_api_job import Ansiblesapp = Flask(__name__)@app.route(‘/ansible/command‘, methods=[‘GET‘,‘POST‘])def command():    if request.method == ‘POST‘:        jsondata = request.get_data()        dictdata = json.loads(jsondata)        ansible = Ansibles(dictdata[‘host‘]) #執行個體化Ansible對象        res = ansible.shell(dictdata[‘command‘])        return res    else:        return ‘<h1>Access error</h1>‘@app.route(‘/ansible/copyfile‘, methods=[‘GET‘,‘POST‘])def copyfile():    if request.method == ‘POST‘:        jsondata = request.get_data()        dictdata = json.loads(jsondata)        ansible = Ansibles(dictdata[‘targethost‘]) #執行個體化Ansible對象        res = ansible.copyfile(str(dictdata[‘srcfile‘]),str(dictdata[‘dectdir‘]))        return res    else:        return ‘<h1>Access error</h1>‘@app.route(‘/ansible/pullfile‘,methods=[‘GET‘,‘POST‘])def pullfile():    if request.method == ‘POST‘:        jsondata = request.get_data()        dictdata = json.loads(jsondata)        ansible = Ansibles(dictdata[‘srchost‘])        res = ansible.pull(dictdata[‘pullsrcfile‘], dictdata[‘savelocaldir‘])        return res    else:        return ‘<h1>Access error</h1>‘if __name__ ==‘__main__‘:    app.run(debug=True,host=‘0.0.0.0‘)#************二、ansible_api_job.py檔案#!/user/bin/eng python# -*- coding=utf-8 -*-import ansible.runnerclass Ansibles(object):    def __init__(self,hostname):        self.hostname = hostname        hostlist = self.hostname.split(‘,‘)        hostfile = open(‘host.txt‘, ‘w+‘)        hostfile.writelines(‘[vmserver]‘ + ‘\n‘)        for line in hostlist:            hostfile.writelines(line + ‘\n‘)        hostfile.close()    def shell(self,command):        results = ansible.runner.Runner(            host_list= ‘host.txt‘,            remote_user = ‘root‘,            remote_pass = ‘1qaz#EDC‘,            module_name = ‘shell‘,            module_args = command,            pattern = ‘vmserver‘,            forks = 10            ).run()        for (hostname,result) in results[‘contacted‘].items():            if result[‘stdout‘] == "":                return "HOST:%s, ERROR>>(%s)" % (hostname, result[‘stderr‘])            else:                return "HOST:%s, RESULTS>>(%s)" % (hostname, result[‘stdout‘])    def copyfile(self,srcfile,dectdir):        results = ansible.runner.Runner(            host_list=‘host.txt‘,            remote_user=‘root‘,            remote_pass=‘1qaz#EDC‘,            module_name=‘copy‘,            module_args=‘src=%s dest=%s‘ % (srcfile,dectdir),            pattern=‘vmserver‘,            forks=10        ).run()        for (hostname,result) in results[‘contacted‘].items():            if ‘failed‘ in result:                return "HOST:%s, ERROR>>(%s)" % (hostname,result[‘msg‘])            else:                return "HOST:%s, copy ok" % (hostname)    # 檔案拉取到本地    def pull(self,pullsrcfile,savelocaldir):        pullfileres = ansible.runner.Runner(            host_list=‘host.txt‘,            remote_user=‘root‘,            remote_pass=‘1qaz#EDC‘,            module_name=‘fetch‘,            module_args=‘src=%s dest=%s flat=yes‘ % (pullsrcfile, savelocaldir),            pattern=‘vmserver‘,            forks=10        ).run()        for (hostname,result) in pullfileres[‘contacted‘].items():            if ‘msg‘ in result:                return "HOST:%s ERROR>>(%s)" % (hostname,result[‘msg‘])            else:                return ‘HOST:%s pull ok‘ % (hostname)if __name__ == "__main__":    pass    #*********三、urlib2調用http介面#_*_coding:utf-8_*_import urllib2import json#調用執行命令HTTP介面def ansible_http_post_command(host,command):    url = ‘http://192.168.89.8:5000/ansible/command‘    data = {‘host‘: host, ‘command‘: command}    headers = {‘Content-Type‘: ‘application/json‘}    req = urllib2.Request(url=url, headers=headers, data=json.dumps(data))    response = urllib2.urlopen(req)    return response.read()#res = ansible_http_post_command(‘vm5‘,"uname -a")#print res#調用傳送檔案到目標主機的HTTP介面def ansible_http_post_copyfile(srcfile,targethost,dectdir):    url = ‘http://192.168.89.8:5000/ansible/copyfile‘    data = {‘srcfile‘: srcfile, ‘targethost‘: targethost,‘dectdir‘:dectdir}    headers = {‘Content-Type‘: ‘application/json‘}    req = urllib2.Request(url=url, headers=headers, data=json.dumps(data))    response = urllib2.urlopen(req)    return response.read()res = ansible_http_post_copyfile(‘/tmp/12345.txt‘,‘vm4‘,‘/root/‘)print res#調用從目標主機中拉取檔案到本地的HTTP介面def ansible_http_post_pullsend(srchost,pullsrcfile,savelocaldir):    url = ‘http://192.168.89.8:5000/ansible/pullfile‘    data = {‘srchost‘:srchost,‘pullsrcfile‘:pullsrcfile,‘savelocaldir‘:savelocaldir}    headers = {‘Content-Type‘: ‘application/json‘}    req = urllib2.Request(url=url, headers=headers, data=json.dumps(data))    response = urllib2.urlopen(req)    return response.read()#res = ansible_http_post_pullsend(‘vm2‘,‘/tmp/12345.txt‘,‘/tmp/‘)#print res

本文出自 “FA&IT營運-Q群:223843163” 部落格,請務必保留此出處http://freshair.blog.51cto.com/8272891/1879968

通過flask架構寫成http介面調用Ansible

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.