如何以Django形式使用逗号分隔的IP地址?

时间:2019-07-15 12:43:09

标签: python html django

我必须创建一个表单,该表单可以从用户那里获取多个IP地址(逗号分隔),运行所需的命令(用户输入)并将其显示在网页上。

我不知道该怎么办。

当前代码可以使用一个IP地址,运行命令并成功在网页上显示结果!!

表格.py

from django import forms

class CmdForm(forms.Form):
        ip_address = forms.CharField(label='Enter IP address:')
        command = forms.CharField(label='Command to execute:')

Views.py

from django.shortcuts import render
from first_app.forms import CmdForm
from django.http import HttpResponse
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
# Create your views here.

def index(request):
    my_dict = {'insert_me': ""}
    return render(request,'first_app/index.html',context=my_dict)

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', '')
            devices = {
            'device_type':'cisco_ios',
            'ip':ipInsert,
            'username':'mee',
            'password':'12345',
            'secret':'12345',
            }
            cmd = request.POST.get('command', '')
            try:
                netconnect = ConnectHandler(**devices)
            except (AuthenticationException):
                re = 'Authentication failed.! please try again {}'.format(ipInsert)
                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(ipInsert)
                print(re)
                return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                pass
            except (NetMikoTimeoutException):
                re = 'TimeOut to device {}'.format(ipInsert)
                print(re)
                return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                pass
            except (EOFError):
                print ("End of file while attempting device " + ipInsert)
                return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                pass
            except Exception as unknown_error:
                print ('Some other error: ' + str(unknown_error))
                return render(request,'first_app/forms.html', {'form': form, 'reprinting':re})
                pass

            getIP = netconnect.send_command(ipInsert)
            output = netconnect.send_command(cmd)
            now = time.strftime("%Y_%m_%d__%H_%M_%S")
            file = sys.stdout
            file = open("C:/Users/karti/OneDrive/Desktop/frontend/ "+now +".txt", mode='w+')
            file.write("IP address is\n"+ ipInsert)
            file.write("\n\nCommand Executed: \n"+ cmd)
            file.write("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            file.write("\n\nOutput of Executed Command: \n\n\n"+output)
            file.close

            return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP, 'date_time':now})
        else:
            form = CmdForm()
        return render(request,'first_app/forms.html', {'form': form})
    else:
        return render(request,'first_app/forms.html', {})

forms.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>FORMS</title>
    </head>
  <body>
    <h1> IP address form </h1>

<br><br>
<form method="POST"> {% csrf_token %}
{{ form }}
<br><br>
<input type="submit" value="Run command!" />
<br>

{% if request.POST %}
<pre>{{ reprinting }}</pre>
{% endif %}

<br>

<p>Current date and time is : {{ date_time }} </p>
{% if request.POST %}
<p>Command output:</p>
<pre>{{ output }}</pre>
{% endif %}



  </body>
</html>

用于单个ip:-工作流程为forms.py从用户获取单个IP 地址和** command *,然后将该IP&命令传递到views.py上进行处理[请参阅代码在views.py]中,forms.html用于用户界面。

要求是:-现在用户必须能够提供多个IP地址(使用逗号分隔),并在该IP的设备上运行命令。

希望您能得到我想要说的话! thnx寻求帮助

1 个答案:

答案 0 :(得分:0)

您可以使用普通的forms.CharField(),然后用ip_addresses.split(',')分割结果字符串,split方法将返回IP地址列表。