Mystery
Mystery

Reputation: 81

how can i take the comma separated ip addresses in django form?

i have to create a form which can take mutiple IP addresses (comma separated) from user, run the desired command (input from user) and display it on the web page.

i could not figure out how can i do it.

Currently the code is able to take single IP address, run command and display the result on web page, successfully.!

forms .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>

for single ip:- The workflow is forms.py takes in the Single IP address and **command* from user then that IP& command is passed onto views.py for processing [refer to code in views.py] and forms.html is used for User Interface.

Requirement is:- now the user must be able to give multiple IP addresses (separating them using commas) and runs the command on the devices of that IP.

Hope u get what i m trying to tell.! thnx for the help

Upvotes: 1

Views: 844

Answers (1)

lorenzo
lorenzo

Reputation: 622

You can use a normal forms.CharField(), then split the result string with ip_addresses.split(','), the split method will return the list of ip addresses.

Upvotes: 1

Related Questions