溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

通過flask框架寫成http接口調(diào)用Ansible

發(fā)布時(shí)間:2020-07-07 12:11:59 來源:網(wǎng)絡(luò) 閱讀:5870 作者:TtrToby 欄目:開發(fā)技術(shù)
#*******一、flask_ansible.py文件
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import json
from flask import Flask,request
from ansible_api_job import Ansibles

app = 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']) #實(shí)例化Ansible對(duì)象
        res = ansible.shell(dictdata['command'])
        return res
    else:
        return '<h2>Access error</h2>'

@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']) #實(shí)例化Ansible對(duì)象
        res = ansible.copyfile(str(dictdata['srcfile']),str(dictdata['dectdir']))
        return res
    else:
        return '<h2>Access error</h2>'

@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 '<h2>Access error</h2>'
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.runner

class Ansibles(object):
    def __init__(self,hostname):
        self.hostlist = "host.txt"
        self.user = "root"
        self.passwd = "1qaz#EDC"
        self.pattern = "vmserver"

        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= self.hostlist,
            remote_user = self.user,
            remote_pass = self.passwd,
            module_name = 'shell',
            module_args = command,
            pattern = self.pattern,
            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=self.hostlist,
            remote_user=self.user,
            remote_pass=self.passwd,
            module_name='copy',
            module_args='src=%s dest=%s' % (srcfile,dectdir),
            pattern=self.pattern,
            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=self.hostlist,
            remote_user=self.user,
            remote_pass=self.passwd,
            module_name='fetch',
            module_args='src=%s dest=%s flat=yes' % (pullsrcfile, savelocaldir),
            pattern=self.pattern,
            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調(diào)用http接口
#_*_coding:utf-8_*_
import urllib2
import json

#調(diào)用執(zhí)行命令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

#調(diào)用傳送文件到目標(biāo)主機(jī)的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

#調(diào)用從目標(biāo)主機(jī)中拉取文件到本地的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
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI