Network Automation Using Django to Create VLAN

Assume that you already know how to create project on django
And you already entering virtual environment
*we are using python 3.7 on my windows 7 os
Create Apps
Python manage.py startapp vlan

Setting.py




Install the vlan apps


Save settings.py

Create folder templates, vlan, and index.html


Go to main apps and change add the code of urls.py bellow




Create urls.py on vlan app folder


Using coding below


Create forms.py on vlan apps




Edit the views.py this is the important code is placed on views.py

from django.shortcuts import render
# Create your views here.
from .forms import VlanForm
import getpass
import sys
import telnetlib

def index(request):
      vlan_form = VlanForm()
      context = {
            'Title' : 'VLAN',
            'Header' : 'Configure VLAN',
            'vlan_form' : vlan_form,
      }
     
      if request.method == 'POST':

            VLAN = context['vlan'] = request.POST['vlan']
            NAME = context['name'] = request.POST['name']
            HOST = context['host'] = request.POST['host']

            tn = telnetlib.Telnet(HOST)
            #user
            tn.write(b"cisco\n")
            #pass
            tn.write(b"cisco\n")

            tn.write(b"en\n")
            tn.write(b"cisco\n")
            tn.write(b"term len 0\n")
            tn.write(b"conf t\n")

            vlancmd = "vlan " + VLAN
            tn.write(vlancmd.encode('ascii') + b"\n")
            namecmd ="name " + NAME
            tn.write(namecmd.encode('ascii') + b"\n")

            tn.write(b"exit\n")
            tn.write(b"exit\n")
            tn.write(b"exit\n")

            context ['result'] = tn.read_all().decode('ascii')

      return render(request, 'vlan/index.html', context)

Go to the template -> vlan -> index.html that you already created before now use this code
<!DOCTYPE html>
<html>
<head>
       <title>{{Title}}</title>
</head>
<body>
<h1>{{Header}}</h1>
<a href="/">Home</a>
<a href="/contact/">Backup</a>
<a href="/vlan">VLAN</a>

<form method="POST">
       {% csrf_token %}
       <table>
              {{vlan_form.as_table}}
       </table>
       <button type="submit">Send Command</button>
</form>
      
       <table>
              <h3>CONFIG SHOW</h3>
<textarea rows="20" cols="80" name="conf" form="conf" id="conf">{{result}}</textarea>
       </table>
</body>
</html>