配置DJANGO工程在WEB前端操作SALT-API并返回数据

接上一遍的salt-api的部署,这次完成django部份,实现从web执行salt-stack命令

urls.py加入

url(r'^saltapicmd/', views.saltapicmd,name='saltapicmd'),

views.py加入

import saltapi
def saltapicmd(request):
    if request.method=="POST":
        hostnames=request.POST.get("hostnames")
        commands=request.POST.get("commands")
        try:
            sapi=saltapi.SaltAPI(url="https://192.168.156.72:8000/",username="saltuser",password="yourpassowrd")
            #return render(request,"saltapirun.html",{"login_err":sapi.token})
            salt_client = hostnames
            salt_method = 'cmd.run'
            salt_params = commands
            reinfos=sapi.salt_command(salt_client,salt_method,salt_params)
            return render(request,"saltapirun.html",{"login_err":reinfos})
        except Exception:
            return render(request,"saltapirun.html",{"login_err":"error"})

    else:
        return render(request,"saltapirun.html")

 

saltapi.py的内容:

# -*- coding: utf-8 -*-

import urllib2,urllib
import time

import requests


try:
    import json
except ImportError:
    import simplejson as json

try:
    import cookielib
except:
    import http.cookiejar as cookielib


import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    
    pass
else:
    
    ssl._create_default_https_context = _create_unverified_https_context


from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class SaltAPI(object):
    #__token_id = ''
    # def __init__(self,url,username,password):
    #     self.__url = url.rstrip('/')
    #     self.__user = username
    #     self.__password = password

    def __init__(self, url,username,password):
        self.url = url
        self.username = username
        self.password = password
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
            "Content-type": "application/json"
            # "Content-type": "application/x-yaml"
        }
        self.params = {'client': 'local', 'fun': '', 'tgt': ''}
        # self.params = {'client': 'local', 'fun': '', 'tgt': '', 'arg': ''}
        self.login_url = self.url + "login"
        self.login_params = {'username': self.username, 'password': self.password, 'eauth': 'pam'}
        self.token = self.get_data(self.login_url, self.login_params)['token']
        self.__token_id=self.token
        self.headers['X-Auth-Token'] = self.token

    def get_data(self, url, params):
        send_data = json.dumps(params)
        request = requests.post(url, data=send_data, headers=self.headers, verify=False)
        # response = request.text
        # response = eval(response)     
        # print response
        # print request
        # print type(request)
        response = request.json()
        result = dict(response)
        # print result
        return result['return'][0]

    def salt_command(self, tgt, method, arg=None):
        
        if arg:
            params = {'client': 'local', 'fun': method, 'tgt': tgt, 'arg': arg}
        else:
            params = {'client': 'local', 'fun': method, 'tgt': tgt}
        #print '命令参数: ', params
        result = self.get_data(self.url, params)
        return result

 

saltapirun.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="loginForm" action="{% url 'saltapicmd' %}" method="POST"> {% csrf_token %}
主机名&组名:<input type="text" class="form-control" name="hostnames" placeholder="主机名&组名"></br>
    执行命令<input  style="width:300px" type="text" class="form-control" name="commands" placeholder="运行命令"></br>
<button class="btn btn-success btn-block" type="submit">
                     <b>确定执行</b>
                  </button>

<h4 style="color: red"><b>{{ login_err }}</b></h4>
    </form>
</body>
</html>

 

运行界面:

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页