├── .gitattributes
├── .vscode
└── settings.json
├── Commands.txt
├── db.sqlite3
├── manage.py
├── mlproject
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ ├── settings.cpython-37.pyc
│ ├── urls.cpython-37.pyc
│ └── wsgi.cpython-37.pyc
├── settings.py
├── urls.py
└── wsgi.py
├── myapp
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ └── views.cpython-37.pyc
├── admin.py
├── apps.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
├── readme.md
├── static
├── css
│ ├── animate.min.css
│ ├── bootstrap.css
│ ├── bootstrap.css.map
│ ├── bootstrap.min.css
│ ├── bootstrap.min.css.map
│ ├── custom.css
│ ├── font-awesome.min.css
│ ├── loaders.css
│ ├── nivo-lightbox.css
│ ├── nivo_themes
│ │ ├── .DS_Store
│ │ └── default
│ │ │ ├── close.png
│ │ │ ├── close@2x.png
│ │ │ ├── default.css
│ │ │ ├── loading.gif
│ │ │ ├── loading@2x.gif
│ │ │ ├── next.png
│ │ │ ├── next@2x.png
│ │ │ ├── prev.png
│ │ │ └── prev@2x.png
│ ├── scroll.css
│ └── swiper.min.css
├── dataset
│ ├── Decision_Tree_Friday-WorkingHours-Morning.pcap_ISCX.model
│ ├── file.txt
│ └── readme.md
├── image
│ ├── background
│ │ ├── 1.jpg
│ │ ├── 2.jpg
│ │ ├── 3.jpg
│ │ ├── 4.jpg
│ │ ├── 5.jpg
│ │ ├── 6.jpg
│ │ ├── 7.jpg
│ │ ├── 8.jpg
│ │ └── 9.jpg
│ ├── bar
│ │ ├── ACK Flag Count.jpg
│ │ ├── Fwd Packet Length Mean.jpg
│ │ ├── Fwd Packet Length Std.jpg
│ │ ├── PSH Flag Count.jpg
│ │ ├── Packet Length Variance.jpg
│ │ └── URG Flag Count.jpg
│ ├── gallery
│ │ ├── 1.png
│ │ ├── 2.png
│ │ ├── 3.jpg
│ │ ├── 4.png
│ │ ├── 5.png
│ │ └── 6.png
│ ├── heatmap
│ │ ├── 1.jpg
│ │ ├── 10.jpg
│ │ ├── 11.jpg
│ │ ├── 12.jpg
│ │ ├── 13.jpg
│ │ ├── 14.jpg
│ │ ├── 15.jpg
│ │ ├── 2.jpg
│ │ ├── 3.jpg
│ │ ├── 4.jpg
│ │ ├── 5.jpg
│ │ ├── 6.jpg
│ │ ├── 7.jpg
│ │ ├── 8.jpg
│ │ └── 9.jpg
│ ├── logo
│ │ └── 1.png
│ ├── navigation
│ │ └── 1.jpg
│ ├── side
│ │ ├── 1.jpg
│ │ └── 2.jpg
│ ├── slide
│ │ ├── 1.jpg
│ │ ├── 2.jpg
│ │ └── 3.jpg
│ ├── tip
│ │ ├── 1.png
│ │ ├── 2.jpg
│ │ └── 3.jpg
│ └── video
│ │ └── IDS and IPS.mp4
└── js
│ ├── bootstrap.js
│ ├── bootstrap.min.js
│ ├── core.js
│ ├── isotope.min.js
│ ├── jquery.min.js
│ ├── nivo-lightbox.min.js
│ ├── particles.js
│ ├── scroll.js
│ ├── scrollPosStyler.js
│ ├── sketch.js
│ ├── swiper.min.js
│ └── wow.min.js
└── template
├── DataSet
└── index.html
├── Prediction
└── index.html
├── Visualization
└── index.html
└── index.html
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pkl filter=lfs diff=lfs merge=lfs -text
2 | *.csv filter=lfs diff=lfs merge=lfs -text
3 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.pythonPath": "E:\\Program Files\\Anaconda\\envs\\ml\\python.exe"
3 | }
--------------------------------------------------------------------------------
/Commands.txt:
--------------------------------------------------------------------------------
1 | 1. activate conda environment using 'activate ml'
2 |
3 | 2. go to that folder where you want to create project
4 |
5 | 3. create new project using this command 'django-admin startproject mlproject'
6 |
7 | 4. to run server use command 'python manage.py runserver'
8 |
9 | 5. run command to create an app using command 'python manage.py startapp myapp'
10 |
11 | 6. structure of an app
12 | a. __init__.py : tells python that your events app is package
13 | b. admin.py : is where you register your apps models with sjango admin application
14 | c. apps.py : is a configuration file common to all django apps
15 | d. models.py : is where the models for your app are located
16 | e. tests.py : contains test procedures that will be run when testing your app
17 | f. views.py : views for your app are located
18 |
19 | 7. in mlproject folder add urls in urls.py as
20 | 'from myapp.views import hello
21 | from myapp.views import login
22 | urlpatterns = [
23 | path('admin/', admin.site.urls),
24 | url(r'^hello/$',hello),
25 | url(r'^login/$',login),
26 | ]'
27 |
28 | 8. in myapp folder add function in app(views.py) and that function can be called in project(urls.py)
29 |
30 | 9. create new directory named template and static
31 |
32 | 10. now add these lines in project(setting.py)
33 | 'a. TEMPLATE_DIR = os.path.join(BASE_DIR,"template")
34 | b. STATIC_DIR = os.path.join(BASE_DIR,"static")'
35 | after BASE_DIR in project(setting.py)
36 |
37 | 11. replace this in project(setting.py) in template section ''DIRS': [TEMPLATE_DIR,],'
38 | where firsty was ''DIRS': [],'
39 |
40 | 12. replace this in project(setting.py) in static section 'STATIC_URL = '/static/'
41 | STATICFILES_DIRS=[
42 | STATIC_DIR,
43 | ]'
44 | where firstly was 'STATIC_URL = '/static/''
45 | 13. create 'index.html' file in template folder
46 |
47 | 14. add this code in template(index.html)
48 | '
49 |
50 |
51 |
52 | First App
53 |
54 |
55 |
Hello this is index.html
56 | {{insert_me}}
57 |
58 | '
59 |
60 | 15. add this code in app(views.py)
61 | 'from django.shortcuts import render
62 | from django.http import HttpResponse
63 |
64 | def index(request):
65 | my_dict={'insert_me':"Hello i am from views.py"}
66 | return render(request,'index.html',context=my_dict)'
67 |
68 | 16. add new url in project(urls.py) as 'url(r'^index/$',index),'
69 |
70 | 17. to link css files and images we have to use this syntax '"{%static '_source_' %}"'
71 |
72 | 18. to link one page to another we have to use this syntax '"{% url '_function_name_' %}"'
73 |
74 | 19. to run the project, you have to run command 'python manage.py runsever' in command prompt
75 |
--------------------------------------------------------------------------------
/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/db.sqlite3
--------------------------------------------------------------------------------
/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mlproject.settings')
9 | try:
10 | from django.core.management import execute_from_command_line
11 | except ImportError as exc:
12 | raise ImportError(
13 | "Couldn't import Django. Are you sure it's installed and "
14 | "available on your PYTHONPATH environment variable? Did you "
15 | "forget to activate a virtual environment?"
16 | ) from exc
17 | execute_from_command_line(sys.argv)
18 |
19 |
20 | if __name__ == '__main__':
21 | main()
22 |
--------------------------------------------------------------------------------
/mlproject/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/mlproject/__init__.py
--------------------------------------------------------------------------------
/mlproject/__pycache__/__init__.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/mlproject/__pycache__/__init__.cpython-37.pyc
--------------------------------------------------------------------------------
/mlproject/__pycache__/settings.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/mlproject/__pycache__/settings.cpython-37.pyc
--------------------------------------------------------------------------------
/mlproject/__pycache__/urls.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/mlproject/__pycache__/urls.cpython-37.pyc
--------------------------------------------------------------------------------
/mlproject/__pycache__/wsgi.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/mlproject/__pycache__/wsgi.cpython-37.pyc
--------------------------------------------------------------------------------
/mlproject/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for mlproject project.
3 |
4 | Generated by 'django-admin startproject' using Django 2.2.3.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/2.2/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/2.2/ref/settings/
11 | """
12 |
13 | import os
14 |
15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17 | TEMPLATE_DIR = os.path.join(BASE_DIR,"template")
18 | STATIC_DIR = os.path.join(BASE_DIR,"static")
19 |
20 |
21 | # Quick-start development settings - unsuitable for production
22 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
23 |
24 | # SECURITY WARNING: keep the secret key used in production secret!
25 | SECRET_KEY = '#1d%+ke3j6#q0kj!u-ja@l3j+=q7i181hy5k@5!fds&t)c%+m7'
26 |
27 | # SECURITY WARNING: don't run with debug turned on in production!
28 | DEBUG = True
29 |
30 | ALLOWED_HOSTS = []
31 |
32 |
33 | # Application definition
34 |
35 | INSTALLED_APPS = [
36 | 'django.contrib.admin',
37 | 'django.contrib.auth',
38 | 'django.contrib.contenttypes',
39 | 'django.contrib.sessions',
40 | 'django.contrib.messages',
41 | 'django.contrib.staticfiles',
42 | ]
43 |
44 | MIDDLEWARE = [
45 | 'django.middleware.security.SecurityMiddleware',
46 | 'django.contrib.sessions.middleware.SessionMiddleware',
47 | 'django.middleware.common.CommonMiddleware',
48 | 'django.middleware.csrf.CsrfViewMiddleware',
49 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
50 | 'django.contrib.messages.middleware.MessageMiddleware',
51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
52 | ]
53 |
54 | ROOT_URLCONF = 'mlproject.urls'
55 |
56 | TEMPLATES = [
57 | {
58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
59 | 'DIRS': [TEMPLATE_DIR,],
60 | 'APP_DIRS': True,
61 | 'OPTIONS': {
62 | 'context_processors': [
63 | 'django.template.context_processors.debug',
64 | 'django.template.context_processors.request',
65 | 'django.contrib.auth.context_processors.auth',
66 | 'django.contrib.messages.context_processors.messages',
67 | ],
68 | },
69 | },
70 | ]
71 |
72 | WSGI_APPLICATION = 'mlproject.wsgi.application'
73 |
74 |
75 | # Database
76 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases
77 |
78 | DATABASES = {
79 | 'default': {
80 | 'ENGINE': 'django.db.backends.sqlite3',
81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
82 | }
83 | }
84 |
85 |
86 | # Password validation
87 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
88 |
89 | AUTH_PASSWORD_VALIDATORS = [
90 | {
91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
92 | },
93 | {
94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
95 | },
96 | {
97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
98 | },
99 | {
100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
101 | },
102 | ]
103 |
104 |
105 | # Internationalization
106 | # https://docs.djangoproject.com/en/2.2/topics/i18n/
107 |
108 | LANGUAGE_CODE = 'en-us'
109 |
110 | TIME_ZONE = 'UTC'
111 |
112 | USE_I18N = True
113 |
114 | USE_L10N = True
115 |
116 | USE_TZ = True
117 |
118 | EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
119 | EMAIL_HOST = 'smtp.gmail.com'
120 | EMAIL_USE_TLS=True
121 | EMAIL_PORT = 587
122 | EMAIL_HOST_USER='your_mail'
123 | EMAIL_HOST_PASSWORD='your_password'
124 |
125 | # Static files (CSS, JavaScript, Images)
126 | # https://docs.djangoproject.com/en/2.2/howto/static-files/
127 |
128 | STATIC_URL = '/static/'
129 | STATICFILES_DIRS=[
130 | STATIC_DIR,
131 | ]
132 |
--------------------------------------------------------------------------------
/mlproject/urls.py:
--------------------------------------------------------------------------------
1 | """mlproject URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/2.2/topics/http/urls/
5 | Examples:
6 | Function views
7 | 1. Add an import: from my_app import views
8 | 2. Add a URL to urlpatterns: path('', views.home, name='home')
9 | Class-based views
10 | 1. Add an import: from other_app.views import Home
11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12 | Including another URLconf
13 | 1. Import the include() function: from django.urls import include, path
14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 | """
16 | from django.contrib import admin
17 | from django.urls import path
18 | from django.conf.urls import url
19 | from myapp import views
20 |
21 | from myapp.views import index
22 | from myapp.views import dataset
23 | from myapp.views import visualization
24 | from myapp.views import prediction
25 | from myapp.views import gallery
26 | from myapp.views import contact
27 | from myapp.views import form
28 |
29 | urlpatterns = [
30 | path('admin/', admin.site.urls),
31 | url(r'^index/$',index,name='index'),
32 | url(r'^dataset/$',dataset,name='dataset'),
33 | url(r'^visualization/$',visualization,name='visualization'),
34 | url(r'^prediction/$',prediction,name='prediction'),
35 | url(r'^gallery/$',gallery,name='gallery'),
36 | url(r'^contact/$',contact,name='contact'),
37 | url(r'^form/$',form),
38 | url(r'^new/$',views.new,name='new'),
39 | url(r'^new1/$',views.new1,name='new1'),
40 | ]
--------------------------------------------------------------------------------
/mlproject/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for mlproject project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mlproject.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/myapp/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/myapp/__init__.py
--------------------------------------------------------------------------------
/myapp/__pycache__/__init__.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/myapp/__pycache__/__init__.cpython-37.pyc
--------------------------------------------------------------------------------
/myapp/__pycache__/views.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/myapp/__pycache__/views.cpython-37.pyc
--------------------------------------------------------------------------------
/myapp/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | # Register your models here.
4 |
--------------------------------------------------------------------------------
/myapp/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class MyappConfig(AppConfig):
5 | name = 'myapp'
6 |
--------------------------------------------------------------------------------
/myapp/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/namishkhanna/web_attack_detection_using_machine_learning/4054309dcb3206120452558c75e08eaccc90c7fa/myapp/migrations/__init__.py
--------------------------------------------------------------------------------
/myapp/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | # Create your models here.
4 |
--------------------------------------------------------------------------------
/myapp/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/myapp/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 | from django.http import HttpResponse
3 | import pandas as pd
4 | import matplotlib.pyplot as plt
5 | import io
6 | from PIL import Image, ImageDraw
7 | import PIL, PIL.Image
8 | from io import BytesIO
9 | import base64
10 | import random
11 | import pickle
12 | from bs4 import BeautifulSoup as bsu
13 | from sklearn.ensemble import RandomForestRegressor
14 | import numpy as np
15 | from django.core.mail import send_mail
16 | from django.conf import settings
17 |
18 |
19 | # Importing Dataset
20 |
21 | global data,col_names, group_by,ran_state_values, model, encoded_data
22 | data = pd.read_pickle('./static/dataset/Friday-WorkingHours-Morning.pcap_ISCX.pkl')
23 | data.columns = data.columns.str.lstrip()
24 | col_names = list(data.columns)
25 | group_by = data.groupby('Label')
26 | with open('./static/dataset/Decision_Tree_Friday-WorkingHours-Morning.pcap_ISCX.model','rb') as f:
27 | model = pickle.load(f)
28 | with open('./static/dataset/Friday-WorkingHours-Morning.pcap_ISCX_encoded.pkl','rb') as f:
29 | encoded_data = pickle.load(f)
30 | with open('./static/dataset/file.txt','rb') as f:
31 | ran_state_values = pickle.load(f)
32 | ran_state_values = list(ran_state_values)
33 |
34 |
35 | # Create your views here.
36 |
37 | def index(request):
38 | if request.method =="GET":
39 | return render(request,'index.html')
40 | elif request.method =="POST":
41 | name = request.POST.get("name")
42 | phone = request.POST.get("phone")
43 | email =[request.POST.get("email")]
44 | print(name,phone,email)
45 | feedback = request.POST.get("feedback")
46 | subject = 'Thanks to Contact Us'
47 | message = f' Greetings : {name} ,\n It is pleasure to hear from you. Our technical team would reach you soon. Happy Security.'
48 | email_from = settings.EMAIL_HOST_USER
49 | send_mail(subject,message,email_from,email)
50 | our_email = ['your_mail']
51 | send_mail('Someone Contacted',f'Contacted Person ,\n Name : {name}\n Phone : {phone}\n Message is : {feedback}',email_from,our_email)
52 | return render(request,'index.html')
53 |
54 | def dataset(request):
55 | return render(request,'./DataSet/index.html')
56 |
57 | def visualization(request):
58 | global data,col_names,group_by
59 | if request.method =="GET":
60 | col_name = col_names[-1]
61 | data.columns = data.columns.str.lstrip()
62 | table=group_by[col_name].describe()
63 | col_name=(list(col_name.split('/')))[0]
64 | data1 = table.copy()
65 |
66 | data1.drop('count',axis=1,inplace=True)
67 | if data[col_name].dtype !='object':
68 | data1.drop('max',axis=1,inplace=True)
69 | data1.drop('75%',axis=1,inplace=True)
70 | bar=data1.plot.bar()
71 | plt.ylabel('Values')
72 | plt.xlabel(col_name)
73 | locs, labels = plt.yticks()
74 | plt.setp(labels,rotation=45)
75 | locs, labels = plt.xticks()
76 | plt.setp(labels,rotation=45)
77 | plt.legend(bbox_to_anchor=(0, 1.05), loc='center left', ncol=7)
78 | figure=bar.get_figure()
79 | figure.set_size_inches((8,8))
80 |
81 | table = pd.DataFrame(table)
82 | table = table.to_html(table_id='vt1')
83 |
84 | buf = io.BytesIO()
85 | plt.savefig(buf,format='png')
86 | figure.savefig(f'{col_name}.png')
87 | plt.close(figure)
88 | image = Image.open(f'{col_name}.png')
89 | draw = ImageDraw.Draw(image)
90 | image.save(buf,'PNG')
91 | content_type = 'image/png'
92 | buffercontent = buf.getvalue()
93 | graphic = base64.b64encode(buffercontent)
94 | image_ = graphic.decode('utf-8')
95 | values_to_return = {'tab':table,'cols':col_names,'img':image_}
96 | return render(request,'./Visualization/index.html',context=values_to_return)
97 | if request.method =="POST":
98 | col_name = request.POST.get("col_name")
99 | data.columns = data.columns.str.lstrip()
100 | table=group_by[col_name].describe()
101 | col_name=(list(col_name.split('/')))[0]
102 | data1 = table.copy()
103 |
104 | data1.drop('count',axis=1,inplace=True)
105 | if data[col_name].dtype !='object':
106 | data1.drop('max',axis=1,inplace=True)
107 | data1.drop('75%',axis=1,inplace=True)
108 | bar=data1.plot.bar()
109 | plt.ylabel('Values')
110 | plt.xlabel(col_name)
111 | locs, labels = plt.yticks()
112 | plt.setp(labels,rotation=45)
113 | locs, labels = plt.xticks()
114 | plt.setp(labels,rotation=45)
115 | plt.legend(bbox_to_anchor=(0, 1.05), loc='center left', ncol=7)
116 | figure=bar.get_figure()
117 | figure.set_size_inches((8,8))
118 |
119 | table = pd.DataFrame(table)
120 | table = table.to_html(table_id='vt1')
121 |
122 | buf = io.BytesIO()
123 | plt.savefig(buf,format='png')
124 | figure.savefig(f'{col_name}.png')
125 | plt.close(figure)
126 | image = Image.open(f'{col_name}.png')
127 | draw = ImageDraw.Draw(image)
128 | image.save(buf,'PNG')
129 | content_type = 'image/png'
130 | buffercontent = buf.getvalue()
131 | graphic = base64.b64encode(buffercontent)
132 | image_ = graphic.decode('utf-8')
133 | values_to_return = {'tab':table,'cols':col_names,'img':image_}
134 | return render(request,'./Visualization/index.html',context=values_to_return)
135 |
136 | def prediction(request):
137 | if request.method == "GET":
138 |
139 | quote1='The'
140 | quote2='will be'
141 | j=0 # this variable is used for indexing
142 | ran_state = random.choice(ran_state_values) # this helps for one bot case to come
143 | to_predict = data.sample(n=5,random_state=ran_state) # choosing any five rows randomly
144 | list_of_index = list(to_predict.index) # index values will later help to find the same row
145 | to_predict = to_predict.to_html(table_id='pt') # converting to html code
146 | to_predict = to_predict.replace('class="dataframe"','class="table table-striped table-responsive"') # replacing with bootstrap class
147 | to_predict_html = bsu(to_predict,'html.parser') # using beautifulSoup
148 | val = list_of_index[0] # initially providing the first index value to check box as value
149 |
150 | for i in (to_predict_html.findAll('th')): # finding all the index colums whose values are related to those in list_of_index
151 | try:
152 | if (i.string) == str(val):
153 | check_box_tag=f'
'
154 | i.replaceWith(bsu(check_box_tag,'html.parser')) # replacing index number with text box with same value
155 | j+=1 # updating the index value of the list
156 | val = list_of_index[j]
157 |
158 | except Exception as e:
159 | pass
160 |
161 | to_predict = to_predict_html.prettify() # finally converting to html using beautifulSoup
162 | values_to_return = {'tab':to_predict,'quote1':quote1,'quote2':quote2}
163 | return render(request,'./Prediction/index.html',context=values_to_return) # returning the dict containing the html code
164 | if request.method =="POST":
165 |
166 | quote1='This'
167 | quote2='has been'
168 | j=0 # this variable is used for indexing
169 | ran_state = random.choice(ran_state_values) # this helps for one bot case to come
170 | to_predict = data.sample(n=5,random_state=ran_state) # choosing any five rows randomly
171 | list_of_index = list(to_predict.index) # index values will later help to find the same row
172 | to_predict = to_predict.to_html(table_id='pt') # converting to html code
173 | to_predict = to_predict.replace('class="dataframe"','class="table table-striped table-responsive"') # replacing with bootstrap class
174 | to_predict_html = bsu(to_predict,'html.parser') # using beautifulSoup
175 | val = list_of_index[0] # initially providing the first index value to check box as value
176 |
177 | for i in (to_predict_html.findAll('th')): # finding all the index colums whose values are related to those in list_of_index
178 | try:
179 | if (i.string) == str(val):
180 | check_box_tag=f'
'
181 | i.replaceWith(bsu(check_box_tag,'html.parser')) # replacing index number with text box with same value
182 | j+=1 # updating the index value of the list
183 | val = list_of_index[j]
184 |
185 | except Exception as e:
186 | pass
187 |
188 | to_predict = to_predict_html.prettify()
189 |
190 |
191 |
192 | col_num = request.POST.get("checkbox") # getting the index value of the row
193 | col_num = int(col_num)
194 | col_to_pred = encoded_data.iloc[col_num] # encoded data is used for the prediction (encoded with label encoder)
195 | col_to_display = data.iloc[col_num] # and the column to display is taken form the simple data
196 | right_value = col_to_pred.pop(' Label') # last column is poped from the values to predict
197 | if right_value.astype(int) == 0:
198 | right_values = 'Right value was: BENIGN' # the output is manupulated accordingly
199 | elif right_value.astype(int) == 1:
200 | right_values = 'Right value was: BOT'
201 |
202 | y_pred = model.predict([col_to_pred])
203 | y_pred = list(y_pred.astype(int))
204 | y_pred = int(y_pred[0])
205 | print(type(y_pred))
206 | if y_pred == 0:
207 | y_pred = 'Predicted value is: BENIGN'
208 | elif y_pred ==1:
209 | y_pred = 'Predicted value is: BOT'
210 |
211 | col_to_display = pd.DataFrame(col_to_display)
212 | col_to_display = col_to_display.transpose() # the horizontal dataframe is converted into vertical for better display
213 | col_to_display = col_to_display.to_html(table_id='pt')
214 | col_to_display = col_to_display.replace('class="dataframe"','class="table table-striped table-responsive"') # adding bootstrap class
215 | values_to_return = {'y_pred':y_pred,'right_value':right_values,'tab1':col_to_display,'tab':to_predict,'quote1':quote1,'quote2':quote2} # returning a dict
216 | return render(request,'./Prediction/index.html',context=values_to_return)
217 |
218 | def gallery(request):
219 | return render(request,'index.html')
220 |
221 | def contact(request):
222 | return render(request,'index.html')
223 |
224 | def form(request):
225 | return render(request,'form.html')
226 |
227 | def new(request):
228 | k=request.POST.get("drop1")
229 | return HttpResponse(k)
230 |
231 | def new1(request):
232 | k=request.POST.get("exampleName")
233 | return HttpResponse(k)
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # Web Attack Detection Using Machine Learning :-
2 | This is a Web Attack Detection Website made using HTML, CSS, Django and Machine Learning Algorithm.
3 |
4 | # Note:
5 | Download Dataset in "/static/dataset/" Folder, Instructions given in that Directory.
6 |
7 | # How to Create Project in Django :-
8 | 1. activate conda environment using 'activate ml'
9 |
10 | 2. go to that folder where you want to create project
11 |
12 | 3. create new project using this command 'django-admin startproject mlproject'
13 |
14 | 4. to run server use command 'python manage.py runserver'
15 |
16 | 5. run command to create an app using command 'python manage.py startapp myapp'
17 |
18 | 6. structure of an app
19 | a. __init__.py : tells python that your events app is package
20 | b. admin.py : is where you register your apps models with sjango admin application
21 | c. apps.py : is a configuration file common to all django apps
22 | d. models.py : is where the models for your app are located
23 | e. tests.py : contains test procedures that will be run when testing your app
24 | f. views.py : views for your app are located
25 |
26 | 7. in mlproject folder add urls in urls.py as
27 | 'from myapp.views import hello
28 | from myapp.views import login
29 | urlpatterns = [
30 | path('admin/', admin.site.urls),
31 | url(r'^hello/$',hello),
32 | url(r'^login/$',login),
33 | ]'
34 |
35 | 8. in myapp folder add function in app(views.py) and that function can be called in project(urls.py)
36 |
37 | 9. create new directory named template and static
38 |
39 | 10. now add these lines in project(setting.py)
40 | 'a. TEMPLATE_DIR = os.path.join(BASE_DIR,"template")
41 | b. STATIC_DIR = os.path.join(BASE_DIR,"static")'
42 | after BASE_DIR in project(setting.py)
43 |
44 | 11. replace this in project(setting.py) in template section ''DIRS': [TEMPLATE_DIR,],'
45 | where firsty was ''DIRS': [],'
46 |
47 | 12. replace this in project(setting.py) in static section 'STATIC_URL = '/static/'
48 | STATICFILES_DIRS=[
49 | STATIC_DIR,
50 | ]'
51 | where firstly was 'STATIC_URL = '/static/''
52 | 13. create 'index.html' file in template folder
53 |
54 | 14. add this code in template(index.html)
55 | '
56 |
57 |
58 |
59 | First App
60 |
61 |
62 |