Django開発運維舞台裏(五):formviewはsaltと結合して命令を実行します.


リモート実行コマンドは、saltstackというオペレーティングツールを使って、いくつかのシステムコマンドを実行して、直接saltを使って、関連したゲームスクリプトを実行します.saltのモジュール機能を使って、最後に結果をデータベースに保存することができます.とても便利です.
saltstackカスタムmodules:http://lihuipeng.blog.51cto.com/3064864/1396279
saltstack returnの使用:http://lihuipeng.blog.51cto.com/3064864/1403387
saltstack APIの使用:http://docs.saltstack.cn/ref/clients/index.html#localclient
私はここでマルチデータベースを使いました.djangoマルチデータベースの構成参考:http://lihuipeng.blog.51cto.com/3064864/1415141
models.py(このsaltオフィシャルで必要な二つの表)
class QjshsaJids(models.Model):
    _database = 'kaifu'
    id = models.IntegerField(primary_key=True)
    jid = models.CharField(unique=True, max_length=255)
    load = models.TextField()
    class Meta:
        managed = False
        db_table = 'QjshSa_jids'

class QjshsaSaltreturns(models.Model):
    _database = 'kaifu'
    id = models.IntegerField(primary_key=True)
    fun = models.CharField(max_length=50)
    jid = models.CharField(max_length=255)
    result = models.TextField()
    host = models.CharField(max_length=255)
    success = models.CharField(max_length=10)
    full_ret = models.TextField()
    class Meta:
        managed = False
        db_table = 'QjshSa_saltreturns'
forms.py
systemcommand = [
                        ('df -lh','df -lh'),
                        ('free -m','free -m'),
                        ('uptime','uptime'),
                        ('netstat -tunlp','netstat -tunlp'),
                        ('ps aux | grep "daemon"','ps aux | grep "daemon"'),
                        ('crontab -l', 'crontab -l'),
                     ]


class ExecuteSystemForm(forms.Form):
    plat = forms.CharField(required=True,
                           widget=forms.TextInput(attrs={'readonly':'True', 'class':"form-control"}))
    server_id = forms.CharField(required=True,
                                widget=forms.TextInput(attrs={'readonly':'True', 'class':"form-control"}))
    server_name = forms.CharField(required=True,
                                widget=forms.TextInput(attrs={'readonly':'True', 'class':"form-control"}))
    host = forms.CharField(required=True,
                           widget=forms.TextInput(attrs={'readonly':'True', 'class':"form-control"}))
    command = forms.ChoiceField(required=True,
                                choices=systemcommand,
                                widget=forms.Select(attrs={'class':"form-control"}))
いくつかの命令を実行できるように限定しました.安心します.
view.py
class ExecuteSystem(FormView):
    template_name = 'execute_system.jinja.html'
    form_class = ExecuteSystemForm


    def get_initial(self, **kwargs):
        initial = {}
        kaifuid = self.kwargs['pk']
        serverinfo = ServerList.objects.get(kaifu_id=kaifuid)
        initial['plat'] = serverinfo.plat
        initial['server_id'] = serverinfo.server_id
        initial['server_name'] = serverinfo.server_name
        initial['host'] = serverinfo.dx_ip
        return initial

    def form_valid(self, form):
        formdata = form.cleaned_data
        host = formdata['host']
        command = formdata['command']
        saltconnection = salt.client.LocalClient()
        result = saltconnection.cmd(host, 'cmd.run', [command], ret='qjsh_mysql')
        result = result[host]
        messages.success(self.request,'    !')
        return render_to_response(self.template_name,
                                  {'form':form,'kaifuid':self.kwargs['pk'],'result':result},
                                  context_instance=RequestContext(self.request))


    def get_context_data(self, **kwargs):
        context = super(ExecuteSystem,self).get_context_data(**kwargs)
        context['kaifuid'] = self.kwargs['pk']
        return context
ゲットするinitalは初期化formです.
form_validはフォームを検証して実行します.
execute_system.JIJA.
{% from "form_macro.html" import render_field, render_checkbox%}
{% extends "execute_cmd_index.jinja.html" %}
{% set active_page2 = 'executesystem' -%}
{% block content %}
    <div class="row">
        <div class="col-md-6">
			<form class="form-inline" role="form" method="POST">{% csrf_token %}
                <table class="table table-bordered table-hover">
                    <tr>
                        <td>    :</td>
                        <td>{{ form.plat|safe }}</td>
                    </tr>
                    <tr>
                        <td>   ID:</td>
                        <td>{{ form.server_id|safe }}</td>
                    </tr>
                    <tr>
                        <td>     :</td>
                        <td>{{ form.server_name|safe }}</td>
                    </tr>
                    <tr>
                        <td>  IP:</td>
                        <td>{{ form.host|safe }}</td>
                    </tr>
                    <tr>
                        <td>    :</td>
                        <td>
                            <div class="form-group">
                                {{ form.command|safe }}
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2"><center><button type="submit" class="btn btn-info">  </button></center></td>
                    </tr>
                </table>
			</form>
        </div>
    </div>
    {% if result %}
    <hr>
    <div class="row">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">    :</h3>
            </div>
            <div class="panel-body">
                <pre><core>{{result}}</core></pre>
            </div>
        </div>
    </div>
    {% endif %}
{% endblock %}
最後に私が実現した効果:
wKiom1PMzc3xw83eAAFklYkH6s0158.jpg
wKioL1PMzuijHJM2AAIRjGr_jKY071.jpg