Python第42天 salt-api实际应用

文章目录

2019-1-24 10:52:14

salt-api应用

  • send_salt_api.py
    • 用于与minion客户端进行交互
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import requests
import json
try:
    import cookielib
except:
    import http.cookiejar as cookielib
# 使用urllib2请求https出错,做的设置
import ssl
context = ssl._create_unverified_context()
# 使用requests请求https出现警告,做的设置
# from requests.packages.urllib3.exceptions import *
# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
requests.packages.urllib3.disable_warnings()
'''需要自行修改'''
salt_api = "https://192.168.127.78:8888/"
username = "saltapi"
password = "password"
class SaltApi(object):
    def __init__(self, url):
        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"
        }
        self.params = {'client': 'local', 'fun': '', 'tgt': ''}
        self.login_url = salt_api + "login"
        self.login_params = {'username': self.username, 'password': self.password, 'eauth': 'pam'}
        # print('------->',self.login_params)
        self.token = self.get_data(self.login_url, self.login_params)['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.json()
        result = dict(response)
        return result['return'][0]

    def salt_command(self, tgt, method, arg=None):
        """远程执行命令,相当于salt 'client1' cmd.run 'free -m'"""
        if arg:
            params = {'client': 'local', 'fun': method, 'tgt': tgt, 'arg': arg,}
        else:
            params = {'client': 'local', 'fun': method, 'tgt': tgt}
        result = self.get_data(self.url, params)
        return result

#自调用
def main():
    salt = SaltApi(salt_api)
    salt_client = '*'
    salt_test = 'grains.items'
    result = salt.salt_command(salt_client, salt_test)
    return result

if __name__ == '__main__':
    main()

  • views.py
    • 调用send_salt_api进行与前端交互
from django.shortcuts import render, redirect, HttpResponse
from salt.parsing import ResApi
from django.views import View
from utils import send_salt_api
from utils import form_class
from host import models
import json


class apilist(View):
    dic_li = send_salt_api.main()
    def get(self, request):
        # print(request.GET.get('name'))
        if '1' == request.GET.get('name'):
            res = ResApi().parsing(self.dic_li)
            for k, v in res.items():
                dic = {}
                hostname = k
                ipaddress = v[0]
                system = v[1]
                mem = v[2]
                obj = models.HostList.objects.filter(ipaddress=ipaddress).first()
                if obj:
                    continue
                else:
                    models.HostList.objects.create(hostname=hostname, ipaddress=ipaddress, system=system, mem=mem)
            return redirect('/hostpage/')
        else:
            res = ResApi().parsing(self.dic_li)
            return render(request, 'apipage.html', locals())

    def post(self, request):
        cmd = request.POST.get('cmd')
        client = request.POST.get('client')
        # print(cmd,client)
        api = send_salt_api.SaltApi
        api_url = send_salt_api.salt_api
        salt = api(api_url)
        salt_client = client
        salt_test = 'test.ping'
        salt_method = 'cmd.run'
        salt_params = cmd
        result = salt.salt_command(salt_client, salt_method, salt_params)[client]
        # print(result['python'])
        # result1 = salt.salt_command(salt_client, salt_test)
        return render(request,'apipage.html',locals())
        res = ResApi().parsing(self.dic_li)
        for k, v in res.items():
            dic = {}
            hostname = k
            ipaddress = v[0]
            system = v[1]
            mem = v[2]
            obj = models.HostList.objects.filter(ipaddress=ipaddress).first()
            if obj:
                continue
            else:
                models.HostList.objects.create(hostname=hostname, ipaddress=ipaddress, system=system, mem=mem)
        return redirect('/hostpage/')
  • apipage.html
    • 接收后台传递的数据
    • 通过post传递命令至后台,并将后台数据进行展示
{% extends "base.html" %}
{% block title %}SaltApi管理{% endblock %}
{% block hostpage %}
<div class="bs-example " data-example-id="hoverable-table">
    <h1 align="center">SaltApi管理</h1>
    <hr>
        <div>
             <form method="post">
                 <input name="cmd" placeholder="命令"/>
                 <input name="client" placeholder="minion_id"/>
                 <input type="submit" class="btn btn-primary btn-ll" value="命令提交"></input>
                 <pre style="width: 80%;height: 580px">{{ result }}</pre>
             </form>
        </div>
</div>
{% endblock %}

给TA打赏
共{{data.count}}人
人已打赏
开发

Python第52天 发布系统表设计

2023-9-11 18:33:23

开发

Python第15天 模块的使用

2023-9-11 18:33:25

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索