Skip to content

Commit 8157bef

Browse files
committed
Possible solution for connecting via docker-ansible and adding level of information when running ansible
1 parent 784287e commit 8157bef

10 files changed

Lines changed: 133 additions & 14 deletions

File tree

WebApi/backend/DAL/DAO/apiDAO.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ def getAllApi():
88
def getApi(id):
99
return ApiKey.objects.get(id=int(id))
1010

11+
def searchApi(key):
12+
try:
13+
return ApiKey.objects.get(key=key)
14+
except:
15+
return False
16+
1117
def createKey(title):
1218
credential = ApiKey(
1319
title=title,

WebApi/backend/integrations/ansible.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def __init__(self):
99
self.ciscoPlaybook = 'backend/integrations/communs/cisco/playbook.yml'
1010
self.ansibleHost = 'backend/integrations/communs/ansible/hosts.yml'
1111
self.ansiblePlaybook = 'backend/integrations/communs/ansible/playbook.yml'
12-
self.ansibleCFG = 'backend/integrations/communs/ansible/ansible.cfg'
12+
self.ansibleCFG = 'ansible_cfg=backend/integrations/communs/ansible/ansible.cfg'
1313

1414
def write_ansible_host(self, string, switch, password, username):
1515
user_str = f" ansible_user: {username}\n"
@@ -61,9 +61,16 @@ def write_ansible_playbook(self, string, switch):
6161
except:
6262
return False
6363

64-
def run_ansible(self):
64+
def run_ansible(self, ansible_level):
6565
try:
66-
command = ['ansible-playbook', self.ansiblePlaybook, '-i', self.ansibleHost]
66+
if int(ansible_level) == 0:
67+
command = ['ansible-playbook', self.ansiblePlaybook, '-i', self.ansibleHost, '-e', self.ansibleCFG]
68+
elif int(ansible_level) == 1:
69+
command = ['ansible-playbook', self.ansiblePlaybook, '-i', self.ansibleHost, '-e', self.ansibleCFG, '-v']
70+
elif int(ansible_level) == 2:
71+
command = ['ansible-playbook', self.ansiblePlaybook, '-i', self.ansibleHost, '-e', self.ansibleCFG, '-vvv']
72+
else:
73+
command = ['ansible-playbook', self.ansiblePlaybook, '-i', self.ansibleHost, '-e', self.ansibleCFG, '-vvvvv']
6774
output = subprocess.check_output(command, stderr=subprocess.STDOUT, universal_newlines=True)
6875
self.clear_data()
6976
return output

WebApi/backend/urls.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,6 @@
1818
path('user/<int:pk>/edit/', UpdateUserView.as_view(), name='userEdit'),
1919
path('user/<int:pk>/delete/', DeleteUserView.as_view(), name='userDelete'),
2020
path('api/', ApiPageView.as_view(), name='apiKey'),
21+
path('api/v1/', ApiResponseView.as_view(), name='apiResponse'),
2122
path('api/key/<int:pk>/delete/', ApiDeleteView.as_view(), name='keyDelete'),
2223
]

WebApi/backend/views/ansible.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
from django.shortcuts import render
33
from django.contrib.auth.mixins import LoginRequiredMixin
44
from django.views.generic import TemplateView
5-
from backend.views.utils import AdminRequired
65
from backend.DAL.DAO.logDAO import *
76
from backend.DAL.DAO.deviceDAO import *
87
from backend.integrations.ansible import *
98

10-
class AnsibleView(AdminRequired, TemplateView):
9+
class AnsibleView(LoginRequiredMixin, TemplateView):
1110
template_name = 'ansible.html'
1211
ansible = AnsibleSwitchConnector()
1312

@@ -17,27 +16,28 @@ def get_context_data(self, **kwargs):
1716
context['credentials'] = credentials
1817
return context
1918

20-
def execute_command(self, playbook, host, switch, username, password):
19+
def execute_command(self, playbook, host, switch, username, password, ansible_level):
2120
# Adicionar verificações de segurança aqui
2221
try:
2322
self.ansible.write_ansible_playbook(playbook, str(switch))
2423
self.ansible.write_ansible_host(host, switch = str(switch), username = username, password = password)
25-
output = self.ansible.run_ansible()
24+
output = self.ansible.run_ansible(ansible_level)
2625
return output
2726
except:
2827
return "Error when trying to run ansible"
2928

3029
def post(self, request ,*args, **kwargs):
3130
playbook = request.POST.get('playbook')
31+
ansible_level = request.POST.get('ansible_level')
3232
host = request.POST.get('host')
3333
switch = request.POST.get('switch')
3434
username = request.POST.get('username')
3535
password = request.POST.get('password')
3636
if request.POST.get('credential') == "none":
37-
output = self.execute_command(playbook, host, switch, username, password)
37+
output = self.execute_command(playbook, host, switch, username, password, ansible_level)
3838
else:
3939
credential = getDeviceCredential(request.POST.get('credential'))
40-
output = self.execute_command(playbook, host, switch, credential.username, credential.password)
40+
output = self.execute_command(playbook, host, switch, credential.username, credential.password, ansible_level)
4141
createLog(
4242
user=f"{request.user}",
4343
date=datetime.now().strftime("%d-%m-%Y"),

WebApi/backend/views/api.py

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1+
from rest_framework.views import APIView
2+
from rest_framework.response import Response
13
from django.shortcuts import render
24
from django.views.generic import TemplateView, UpdateView, DeleteView
35
from django.urls import reverse_lazy
46
from backend.views.utils import AdminRequired
57
from backend.DAL.DAO.apiDAO import *
8+
from backend.DAL.DAO.logDAO import *
69
from backend.DAL.models.api import ApiKey
10+
from backend.integrations.ansible import *
11+
12+
713

814
class ApiPageView(AdminRequired, TemplateView):
915
template_name = 'api.html'
@@ -20,6 +26,15 @@ def post(self, request ,*args, **kwargs):
2026
title = request.POST.get('title'),
2127
)
2228
result = "The key have been successfully upgraded."
29+
createLog(
30+
user=f"{request.user}",
31+
date=datetime.now().strftime("%d-%m-%Y"),
32+
hour=datetime.now().strftime("%H:%M:%S"),
33+
switch="Unused function",
34+
playbook="Unused function",
35+
host="Unused function",
36+
output="The user generated an API access key.",
37+
)
2338
return self.render_to_response(self.get_context_data(result = result))
2439

2540
class ApiDeleteView(AdminRequired, DeleteView):
@@ -31,4 +46,28 @@ def get_context_data(self, **kwargs):
3146
context = super().get_context_data(**kwargs)
3247
context['settings'] = 1
3348
context['page'] = "Delete Key"
34-
return context
49+
return context
50+
51+
52+
class ApiResponseView(APIView):
53+
54+
def execute_command(self, playbook, host, switch, username, password):
55+
# Adicionar verificações de segurança aqui
56+
try:
57+
self.ansible.write_ansible_playbook(string = playbook, switch = str(switch))
58+
self.ansible.write_ansible_host(string = host, switch = str(switch), username = username, password = password)
59+
output = self.ansible.run_ansible()
60+
return output
61+
except:
62+
return "Error when trying to run ansible"
63+
64+
def post(self, request, format=None):
65+
data = request.data
66+
key = searchApi(data['key'])
67+
if key == False:
68+
return Response("Key not found, access denied")
69+
try:
70+
output = execute_command(playbook = data['command'], host = data['host'], switch = data['switch'], username = data['username'], password = data['password'])
71+
return Response(output)
72+
except:
73+
return Response("Please verify the variables used, remembering that the following fields are required: key, command, host, switch, username, password.")

WebApi/backend/views/user.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from django.urls import reverse_lazy
77
from django.db.models import Q
88
from backend.views.utils import AdminRequired
9+
from backend.DAL.DAO.logDAO import *
910

1011

1112
class UserPageView(AdminRequired, TemplateView):
@@ -37,9 +38,27 @@ def post(self, request ,*args, **kwargs):
3738
if form.is_valid():
3839
user = form.save()
3940
result = "Success in creating user"
41+
createLog(
42+
user=f"{request.user}",
43+
date=datetime.now().strftime("%d-%m-%Y"),
44+
hour=datetime.now().strftime("%H:%M:%S"),
45+
switch="Unused function",
46+
playbook="Unused function",
47+
host="Unused function",
48+
output="A new user has been created",
49+
)
4050
return render(request, self.template_name, {'result': result})
4151
else:
4252
result = "Error in creating user"
53+
createLog(
54+
user=f"{request.user}",
55+
date=datetime.now().strftime("%d-%m-%Y"),
56+
hour=datetime.now().strftime("%H:%M:%S"),
57+
switch="Unused function",
58+
playbook="Unused function",
59+
host="Unused function",
60+
output="Attempted to generate a new user, but an error occurred.",
61+
)
4362
return render(request, self.template_name, {'result': result})
4463

4564

WebApi/backend/views/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ def test_func(self):
88
return user.is_staff # Verificando
99

1010
def handle_no_permission(self):
11-
return HttpResponseForbidden('ACCESS FORBIDDEN! ONLY ADMINISTRATORS CAN ACCESS THIS PAGE.')
11+
return HttpResponseForbidden('ACCESS FORBIDDEN! ONLY ADMINISTRATORS CAN ACCESS THIS PAGE.')

WebApi/core/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
'allauth',
4646
'allauth.account',
4747
'backend.apps.BackendConfig',
48+
'rest_framework',
4849
]
4950

5051
MIDDLEWARE = [

WebApi/frontend/templates/ansible.html

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,17 @@ <h1>Ansible Configuration</h1>
1818
{% endfor %}
1919
</select>
2020
</div>
21+
22+
<div class="form-group">
23+
<label for="exampleFormControlInput1">Ansible information level</label>
24+
<select class="custom-select" style="width: 100%;" id="ansible_level" name="ansible_level">
25+
<option value="0" selected>Standard</option>
26+
<option value="1">Basic</option>
27+
<option value="2">Intermediary</option>
28+
<option value="3">Advanced</option>
29+
</select>
30+
</div>
31+
2132
<div class="form-group">
2233
<label for="exampleFormControlInput1">Switch SSH Username</label>
2334
<input class="form-control" type="text" name="username" placeholder="Username" id="username">

WebApi/frontend/templates/api.html

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
{% if settings == 0 %}
88
<h1>Manage Api</h1>
9-
9+
<hr>
1010
<form method="post">
1111
{% csrf_token %}
12-
<label class="form-label">Generate Key</label>
12+
<h3 class="form-label">Create Key</h3>
1313
<div class="input-group">
1414
<div class="form-outline">
1515
<input type="search" class="form-control" placeholder="Key Title" name="title">
@@ -24,7 +24,7 @@ <h1>Manage Api</h1>
2424

2525

2626

27-
27+
<h4 style="margin-top: 30px;margin-bottom: 15px;">List of generated keys</h4>
2828
<div class="col-md-12">
2929
<div class="panel panel-default">
3030
<div class="panel-heading">
@@ -73,11 +73,46 @@ <h1>Manage Api</h1>
7373
</div>
7474
</div>
7575
</div>
76+
<hr>
77+
<h1 style="margin-top: 30px;margin-bottom: 15px;">Examples of <span style="color: #4723D9">API requests</span></h1>
78+
<h3>Python</h3>
79+
<pre>
80+
<code>
81+
import requests
82+
83+
def run_request():
84+
url = 'http://127.0.0.1:8000/api/v1/'
85+
data = {
86+
'key': 'testekeypass',
87+
'switch': 'huawei'
88+
'host': '10.0.0.0'
89+
'username': 'testeuser',
90+
'password': 'testepass',
91+
'command': 'display vlan',
92+
}
93+
94+
response = requests.post(url, data=data)
95+
96+
if response.status_code == 200:
97+
# Successful request, handle the response here
98+
result = response.json()
99+
print(result)
100+
else:
101+
# Error
102+
print('Error:', response.status_code)
103+
104+
if __name__ == '__main__':
105+
run_request()
106+
</code>
107+
</pre>
76108
{% else %}
77109
<p>Are you sure you want to delete "{{ object }}"?</p>
110+
<form method="POST">
111+
{% csrf_token %}
78112
<div class="text-center">
79113
<button type="submit" class="btn btn-danger px-5 mb-5 w-100">Confirm</button>
80114
</div>
115+
</form>
81116
{% endif %}
82117

83118
<style>

0 commit comments

Comments
 (0)