上次迭代结果覆盖(在 Web 上)以前的输出



参考上一个问题,这是我所做的一些调整,并进一步添加了一些功能。

在上一个问题中,循环是迭代多个 IP 和单个命令,但现在我希望循环迭代多个 IP 和多个命令,为此我又添加了一个 for 循环。

与在代码中一样,写入文件时一切正常,但在 HttpResponse 中,上次输出的结果覆盖了以前的输出

views.py

    from django.shortcuts import render
    from first_app.forms import CmdForm
    from django.http import HttpResponse, HttpResponseRedirect
    import netmiko
    from netmiko import ConnectHandler
    from netmiko.ssh_exception import NetMikoTimeoutException
    from paramiko.ssh_exception import SSHException
    from netmiko.ssh_exception import AuthenticationException
    import datetime, time, sys
    from django.urls import reverse
    # Create your views here.
    def form_name_view(request):
        if request.method == "POST":
            form = CmdForm(request.POST)
            if form.is_valid():
                from netmiko import ConnectHandler
                ipInsert = request.POST.get('ip_address', '')   #taking multiple IPS
                ipIns = ipInsert.split(',')                     #splitting IPs CSVs
                cmd = request.POST.get('command', '')       #tking multiple Commands
                cmdlist = cmd.split(',')                    #splitting commands
                for ipIn in ipIns:                          #for eqch in IP in IP list
                    for cmdSingle in cmdlist:               #for eah command in Command list
                        devices = {
                        'device_type':'cisco_ios',
                        'ip':ipIn,
                        'username':'mee',
                        'password':'12345',
                        'secret':'12345',
                        }
                        try:
                            netconnect = ConnectHandler(**devices)      
                        except (AuthenticationException):
                            re = 'Authentication failed.! please try again {}'.format(ipIn)
                            print(re)
                            return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                            pass
                        except (SSHException):
                            re = 'SSH issue. Are you sure SSH is enabled? {}'.format(ipIn)
                            print(re)
                            return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                            pass
                        except (NetMikoTimeoutException):
                            re = 'TimeOut to device {}'.format(ipIn)
                            print(re)
                            return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                            pass
                        except (EOFError):
                            re = 'End of file while attempting device {}'.format(ipIn)
                            print(re)
                            return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                            pass
                        except Exception as unknown_error:
                            re = 'Some other error {}' .format(unknown_error)
                            print(re)
                            return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                            pass
                        output = netconnect.send_command(cmdSingle)         #sending command to router
                        now = time.strftime("%Y_%m_%d__%H_%M_%S")           #print command on web
                        file = sys.stdout                                   #standard output in txt file
                        file = open("C:/Users/OneDrive/Desktop/frontend/ "+now+"__"+ipIn +".txt", mode='a+')  #open and append file
                        file.write("IP address isn"+ ipIn)                        # write IP address to file
                        file.write("nnCommand Executed: n"+ cmdSingle)           #write command to file
                        file.write("nn~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                        file.write("nnOutput of Executed Command: nnn"+output)         #writing output to file
                        file.close
                return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':ipIn,     
                                                                        'date_time':now, 'ipList':ipIns,
                                                                        'cmdlist':cmdlist,'cmdSingle':cmdSingle})       #http response on web
            else:
                form = CmdForm()
                return render(request,'first_app/forms.html', {'form': form})
        else:
            return render(request,'first_app/forms.html', {})

形式.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>FORMS</title>
    <style>
    table, th, td {
      style=width:100%;
      max-height:100px;
      border: 1px solid black;
    }
    #lengthy{
      max-height:50px;
      overflow-y: scroll;
            height:50px;
    }
    </style>
    </head>
  <body>
    <h1> Run Commands </h1>
<form method="POST"> {% csrf_token %}
{% for field in form %}
   <div class="fieldWrapper">
       {{ field.errors }} <br>
       {{ field.label_tag }} <br/>
       {{ field }}
   </div>
   {% endfor %}
<br><br>
<input type="submit" value="Click Here to run Commands" />
<br>
{% if request.POST %}
<pre>{{ reprinting }}</pre>
{% endif %}
<br>
{% if request.POST %}
{% csrf_token %}
  <table>
    <tr>
      <th>Current date and time</th>
      <th>IP address </th>
      <th>Command Executed </th>
      <th>Output</th>
    </tr>

  {% for getIP in ipList %}
    {% for cmdSingle in cmdlist %}
      <tr>
        <td style="width:20%"> {{ date_time }} </td>
        <td style="width:15%"><pre> {{ getIP }} </pre></td>
        <td style="width:20%"><pre> {{ cmdSingle }} </pre></td>
        <td id="lengthy" style="width:90%"><pre>{{ output }}</pre></td>
      </tr>
      {% endfor %}
  {% endfor %}
  </table>

{% endif %}

</form>
  </body>
</html>

谢谢你的帮助。!

我认为您应该构建列表列表并在模板中显示输出。喜欢这个:

 def form_name_view(request):
    if request.method == "POST":
        form = CmdForm(request.POST)
        if form.is_valid():
            # rest of the code
            output_list = list()
            for ipIn in ipIns:                        
                for cmdSingle in cmdlist: 
                    # try catch block
                    output = netconnect.send_command(cmdSingle)
                    output_list.append([ipIn, cmdSingle, output])  # appending ip, cmd and output as a list to output list
                    # rest of the code
            return render(request,'first_app/forms.html', {'form': form, 'output_list':output_list, 'date_time':now})

然后在模板中渲染它:

{% for getIP, cmdSingle, output in output_list %}
  <tr>
    <td style="width:20%"> {{ date_time }} </td>
    <td style="width:15%"><pre> {{ getIP }} </pre></td>
    <td style="width:20%"><pre> {{ cmdSingle }} </pre></td>
    <td id="lengthy" style="width:90%"><pre>{{ output }}</pre></td>
  </tr>
{% endfor %}

最新更新