netbox-toolkit-plugin 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. netbox_toolkit_plugin-0.1.0/LICENSE +200 -0
  2. netbox_toolkit_plugin-0.1.0/PKG-INFO +76 -0
  3. netbox_toolkit_plugin-0.1.0/README.md +55 -0
  4. netbox_toolkit_plugin-0.1.0/netbox_toolkit/__init__.py +30 -0
  5. netbox_toolkit_plugin-0.1.0/netbox_toolkit/admin.py +16 -0
  6. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/__init__.py +0 -0
  7. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/mixins.py +54 -0
  8. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/schemas.py +234 -0
  9. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/serializers.py +158 -0
  10. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/urls.py +10 -0
  11. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/views/__init__.py +10 -0
  12. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/views/command_logs.py +170 -0
  13. netbox_toolkit_plugin-0.1.0/netbox_toolkit/api/views/commands.py +267 -0
  14. netbox_toolkit_plugin-0.1.0/netbox_toolkit/config.py +159 -0
  15. netbox_toolkit_plugin-0.1.0/netbox_toolkit/connectors/__init__.py +15 -0
  16. netbox_toolkit_plugin-0.1.0/netbox_toolkit/connectors/base.py +97 -0
  17. netbox_toolkit_plugin-0.1.0/netbox_toolkit/connectors/factory.py +301 -0
  18. netbox_toolkit_plugin-0.1.0/netbox_toolkit/connectors/netmiko_connector.py +443 -0
  19. netbox_toolkit_plugin-0.1.0/netbox_toolkit/connectors/scrapli_connector.py +486 -0
  20. netbox_toolkit_plugin-0.1.0/netbox_toolkit/exceptions.py +36 -0
  21. netbox_toolkit_plugin-0.1.0/netbox_toolkit/filtersets.py +85 -0
  22. netbox_toolkit_plugin-0.1.0/netbox_toolkit/forms.py +31 -0
  23. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/0001_initial.py +54 -0
  24. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/0002_alter_command_options_alter_command_unique_together_and_more.py +66 -0
  25. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/0003_permission_system_update.py +48 -0
  26. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/0004_remove_django_permissions.py +77 -0
  27. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/0005_alter_command_options_and_more.py +25 -0
  28. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/0006_commandlog_parsed_data_commandlog_parsing_success_and_more.py +28 -0
  29. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/0007_alter_commandlog_parsing_template.py +18 -0
  30. netbox_toolkit_plugin-0.1.0/netbox_toolkit/migrations/__init__.py +0 -0
  31. netbox_toolkit_plugin-0.1.0/netbox_toolkit/models.py +89 -0
  32. netbox_toolkit_plugin-0.1.0/netbox_toolkit/navigation.py +30 -0
  33. netbox_toolkit_plugin-0.1.0/netbox_toolkit/search.py +21 -0
  34. netbox_toolkit_plugin-0.1.0/netbox_toolkit/services/__init__.py +7 -0
  35. netbox_toolkit_plugin-0.1.0/netbox_toolkit/services/command_service.py +357 -0
  36. netbox_toolkit_plugin-0.1.0/netbox_toolkit/services/device_service.py +87 -0
  37. netbox_toolkit_plugin-0.1.0/netbox_toolkit/services/rate_limiting_service.py +228 -0
  38. netbox_toolkit_plugin-0.1.0/netbox_toolkit/static/netbox_toolkit/css/toolkit.css +143 -0
  39. netbox_toolkit_plugin-0.1.0/netbox_toolkit/static/netbox_toolkit/js/toolkit.js +657 -0
  40. netbox_toolkit_plugin-0.1.0/netbox_toolkit/tables.py +37 -0
  41. netbox_toolkit_plugin-0.1.0/netbox_toolkit/templates/netbox_toolkit/command.html +108 -0
  42. netbox_toolkit_plugin-0.1.0/netbox_toolkit/templates/netbox_toolkit/command_edit.html +10 -0
  43. netbox_toolkit_plugin-0.1.0/netbox_toolkit/templates/netbox_toolkit/command_list.html +12 -0
  44. netbox_toolkit_plugin-0.1.0/netbox_toolkit/templates/netbox_toolkit/commandlog.html +170 -0
  45. netbox_toolkit_plugin-0.1.0/netbox_toolkit/templates/netbox_toolkit/commandlog_list.html +4 -0
  46. netbox_toolkit_plugin-0.1.0/netbox_toolkit/templates/netbox_toolkit/device_toolkit.html +536 -0
  47. netbox_toolkit_plugin-0.1.0/netbox_toolkit/urls.py +22 -0
  48. netbox_toolkit_plugin-0.1.0/netbox_toolkit/utils/__init__.py +1 -0
  49. netbox_toolkit_plugin-0.1.0/netbox_toolkit/utils/connection.py +125 -0
  50. netbox_toolkit_plugin-0.1.0/netbox_toolkit/utils/error_parser.py +428 -0
  51. netbox_toolkit_plugin-0.1.0/netbox_toolkit/utils/logging.py +58 -0
  52. netbox_toolkit_plugin-0.1.0/netbox_toolkit/utils/network.py +157 -0
  53. netbox_toolkit_plugin-0.1.0/netbox_toolkit/views.py +385 -0
  54. netbox_toolkit_plugin-0.1.0/netbox_toolkit_plugin.egg-info/PKG-INFO +76 -0
  55. netbox_toolkit_plugin-0.1.0/netbox_toolkit_plugin.egg-info/SOURCES.txt +59 -0
  56. netbox_toolkit_plugin-0.1.0/netbox_toolkit_plugin.egg-info/dependency_links.txt +1 -0
  57. netbox_toolkit_plugin-0.1.0/netbox_toolkit_plugin.egg-info/entry_points.txt +2 -0
  58. netbox_toolkit_plugin-0.1.0/netbox_toolkit_plugin.egg-info/requires.txt +4 -0
  59. netbox_toolkit_plugin-0.1.0/netbox_toolkit_plugin.egg-info/top_level.txt +1 -0
  60. netbox_toolkit_plugin-0.1.0/pyproject.toml +40 -0
  61. netbox_toolkit_plugin-0.1.0/setup.cfg +4 -0
@@ -0,0 +1,200 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity granting the License.
13
+
14
+ "Legal Entity" shall mean the union of the acting entity and all
15
+ other entities that control, are controlled by, or are under common
16
+ control with that entity. For purposes of control, an entity is
17
+ "controlled by" another entity if the other entity directly or
18
+ indirectly possesses the power to direct the conduct of such entity,
19
+ whether by contract or otherwise.
20
+
21
+ "You" (or "Your") shall mean an individual or Legal Entity
22
+ exercising permissions granted by this License.
23
+
24
+ "Source" form shall mean the preferred form for making modifications,
25
+ including but not limited to software source code, documentation
26
+ source, and configuration files.
27
+
28
+ "Object" form shall mean any form resulting from mechanical
29
+ transformation or translation of a Source form, including but
30
+ not limited to compiled object code, generated documentation,
31
+ and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or
34
+ Object form, made available under the License, as indicated by a
35
+ copyright notice that is included in or attached to the work
36
+ (which shall not include a modification of which You are not the author).
37
+
38
+ "Derivative Works" shall mean any work, whether in Source or Object
39
+ form, that is based upon (or derived from) the Work and for which the
40
+ editorial revisions, annotations, elaborations, or other modifications
41
+ represent, as a whole, an original work of authorship. For the purposes
42
+ of this License, Derivative Works shall not include works that remain
43
+ separable from, or merely link (or bind by name) to the interfaces of,
44
+ the Work and derivative works thereof.
45
+
46
+ "Contribution" shall mean any work of authorship, including
47
+ the original version of the Work and any modifications or additions
48
+ to that Work or Derivative Works thereof, that is intentionally
49
+ submitted to Licensor for inclusion in the Work by the copyright owner
50
+ or by an individual or Legal Entity authorized to submit on behalf of
51
+ the copyright owner. For the purposes of this definition, "submitted"
52
+ means any form of electronic, verbal, or written communication sent
53
+ to the Licensor or its representatives, including but not limited to
54
+ communication on electronic mailing lists, source code control
55
+ systems, and issue tracking systems that are managed by, or on behalf
56
+ of, the Licensor for the purpose of discussing and improving the Work,
57
+ but excluding communication that is conspicuously marked or otherwise
58
+ designated in writing by the copyright owner as "Not a Contribution."
59
+
60
+ "Contributor" shall mean Licensor and any individual or Legal Entity
61
+ on behalf of whom a Contribution has been received by Licensor and
62
+ subsequently incorporated within the Work.
63
+
64
+ 2. Grant of Copyright License. Subject to the terms and conditions of
65
+ this License, each Contributor hereby grants to You a perpetual,
66
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
67
+ copyright license to use, reproduce, modify, distribute, sublicense,
68
+ and/or sell copies of the Work, and to permit persons to whom the
69
+ Work is furnished to do so, subject to the following conditions:
70
+
71
+ The above copyright notice and this permission notice shall be
72
+ included in all copies or substantial portions of the Work.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, trademark, patent,
103
+ attribution and other notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright notice to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Support. You may choose to offer, and to
167
+ charge a fee for, warranty, support, indemnity or other liability
168
+ obligations and/or rights consistent with this License. However, in
169
+ accepting such obligations, You may act only on Your own behalf and on
170
+ Your sole responsibility, not on behalf of any other Contributor, and
171
+ only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ such Contributor by reason of your accepting any such warranty or support.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ APPENDIX: How to apply the Apache License to your work.
178
+
179
+ To apply the Apache License to your work, attach the following
180
+ boilerplate notice, with the fields enclosed by brackets "[]"
181
+ replaced with your own identifying information. (Don't include
182
+ the brackets!) The text should be enclosed in the appropriate
183
+ comment syntax for the file format. We also recommend that a
184
+ file or class name and description of purpose be included on the
185
+ same page as the copyright notice for easier identification within
186
+ third-party archives.
187
+
188
+ Copyright [yyyy] [name of copyright owner]
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: netbox-toolkit-plugin
3
+ Version: 0.1.0
4
+ Summary: NetBox plugin for running pre-defined commands on network devices
5
+ Author: Andy Norwood
6
+ Classifier: Development Status :: 3 - Alpha
7
+ Classifier: Intended Audience :: System Administrators
8
+ Classifier: Natural Language :: English
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Requires-Python: >=3.10.0
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: scrapli>=2023.1.30
17
+ Requires-Dist: scrapli-netconf>=2023.1.30
18
+ Requires-Dist: scrapli-community>=2023.1.30
19
+ Requires-Dist: netmiko>=4.0.0
20
+ Dynamic: license-file
21
+
22
+ # NetBox Command Toolkit Plugin
23
+
24
+ > ⚠️ **EARLY DEVELOPMENT WARNING** ⚠️
25
+ > This plugin is in very early development and not recommended for production use. There will be bugs and possible incomplete functionality. Use at your own risk! If you do, give some feedback in [Discussions](https://github.com/bonzo81/netbox-toolkit-plugin/discussions)
26
+
27
+ A NetBox plugin that allows you to run commands on network devices directly from the device page.
28
+
29
+
30
+
31
+ ### 📋 Feature Overview
32
+ - **🔧 Command Creation**: Define platform-specific commands (show/config types)
33
+ - **🔐 Command Permissions**: Granular access control using NetBox's permission system
34
+ - **⚡ Command Execution**: Run commands directly from device pages via "Toolkit" tab
35
+ - **📄 Raw Output**: View complete, unfiltered command responses
36
+ - **🔍 Parsed Output**: Automatic JSON parsing using textFSM templates
37
+ - **📊 Command Logs**: Complete execution history with timestamps
38
+ - **🐛 Debug Logging**: Optional detailed logging for troubleshooting
39
+
40
+
41
+ ### Built with:
42
+ - Scrapli for device connections
43
+ - Netmiko as a fallback for problematic devices
44
+ - TextFSM for structured data parsing
45
+
46
+ ### Created with:
47
+ - VSCode
48
+ - Copilot
49
+ - RooCode
50
+
51
+ > This project is a work in progress and in early development. It is not recommended for production use. Feedback and contributions are welcome!
52
+
53
+ ## 📚 Essential Guides
54
+
55
+ #### 🚀 Getting Started
56
+ - [📦 Installation](./docs/user/installation.md) - Install the plugin in your NetBox environment
57
+ - [⚙️ Configuration](./docs/user/configuration.md) - Configure plugin settings and options
58
+
59
+ #### 📋 Command Management
60
+ - [📋 Command Creation](./docs/user/command-creation.md) - Create platform-specific commands
61
+ - [🔐 Permissions Setup](./docs/user/PERMISSIONS_SETUP_GUIDE.md) - Configure granular access control
62
+ - [📝 Permission Examples](./docs/user/permission-examples.md) - Example permission configuration
63
+
64
+ #### 🔧 Troubleshooting
65
+ - [🐛 Debug Logging](./docs/user/debug-logging.md) - Enable detailed logging for debugging
66
+
67
+
68
+ ## Contributing
69
+
70
+ **🚀 Want to Contribute?** Start with the [Contributor Guide](./docs/contributing.md) for a fast overview of the codebase.
71
+
72
+
73
+ ## Future ideas:
74
+ - Enhance API to allow execution of commands and return either parsed or raw data.
75
+ - Enable variable use in the command creation and execution, based on device attributes.
76
+
@@ -0,0 +1,55 @@
1
+ # NetBox Command Toolkit Plugin
2
+
3
+ > ⚠️ **EARLY DEVELOPMENT WARNING** ⚠️
4
+ > This plugin is in very early development and not recommended for production use. There will be bugs and possible incomplete functionality. Use at your own risk! If you do, give some feedback in [Discussions](https://github.com/bonzo81/netbox-toolkit-plugin/discussions)
5
+
6
+ A NetBox plugin that allows you to run commands on network devices directly from the device page.
7
+
8
+
9
+
10
+ ### 📋 Feature Overview
11
+ - **🔧 Command Creation**: Define platform-specific commands (show/config types)
12
+ - **🔐 Command Permissions**: Granular access control using NetBox's permission system
13
+ - **⚡ Command Execution**: Run commands directly from device pages via "Toolkit" tab
14
+ - **📄 Raw Output**: View complete, unfiltered command responses
15
+ - **🔍 Parsed Output**: Automatic JSON parsing using textFSM templates
16
+ - **📊 Command Logs**: Complete execution history with timestamps
17
+ - **🐛 Debug Logging**: Optional detailed logging for troubleshooting
18
+
19
+
20
+ ### Built with:
21
+ - Scrapli for device connections
22
+ - Netmiko as a fallback for problematic devices
23
+ - TextFSM for structured data parsing
24
+
25
+ ### Created with:
26
+ - VSCode
27
+ - Copilot
28
+ - RooCode
29
+
30
+ > This project is a work in progress and in early development. It is not recommended for production use. Feedback and contributions are welcome!
31
+
32
+ ## 📚 Essential Guides
33
+
34
+ #### 🚀 Getting Started
35
+ - [📦 Installation](./docs/user/installation.md) - Install the plugin in your NetBox environment
36
+ - [⚙️ Configuration](./docs/user/configuration.md) - Configure plugin settings and options
37
+
38
+ #### 📋 Command Management
39
+ - [📋 Command Creation](./docs/user/command-creation.md) - Create platform-specific commands
40
+ - [🔐 Permissions Setup](./docs/user/PERMISSIONS_SETUP_GUIDE.md) - Configure granular access control
41
+ - [📝 Permission Examples](./docs/user/permission-examples.md) - Example permission configuration
42
+
43
+ #### 🔧 Troubleshooting
44
+ - [🐛 Debug Logging](./docs/user/debug-logging.md) - Enable detailed logging for debugging
45
+
46
+
47
+ ## Contributing
48
+
49
+ **🚀 Want to Contribute?** Start with the [Contributor Guide](./docs/contributing.md) for a fast overview of the codebase.
50
+
51
+
52
+ ## Future ideas:
53
+ - Enhance API to allow execution of commands and return either parsed or raw data.
54
+ - Enable variable use in the command creation and execution, based on device attributes.
55
+
@@ -0,0 +1,30 @@
1
+ from netbox.plugins import PluginConfig
2
+
3
+ class ToolkitConfig(PluginConfig):
4
+ name = 'netbox_toolkit_plugin'
5
+ verbose_name = 'Netbox Command Toolkit Plugin'
6
+ description = 'NetBox plugin for running pre-defined commands on network devices'
7
+ version = '0.1.0'
8
+ author = 'Andy Norwood'
9
+ base_url = 'toolkit'
10
+
11
+ # Database migrations
12
+ required_settings = []
13
+
14
+ # Default plugin settings
15
+ default_settings = {
16
+ 'rate_limiting_enabled': True,
17
+ 'device_command_limit': 10,
18
+ 'time_window_minutes': 5,
19
+ 'bypass_users': [],
20
+ 'bypass_groups': [],
21
+ 'debug_logging': False, # Enable debug logging for this plugin
22
+ }
23
+
24
+ # Middleware
25
+ middleware = []
26
+
27
+ # Django apps to load when plugin is activated
28
+ django_apps = []
29
+
30
+ config = ToolkitConfig
@@ -0,0 +1,16 @@
1
+ from django.contrib import admin
2
+ from netbox.admin import NetBoxModelAdmin
3
+ from .models import Command, CommandLog
4
+
5
+ @admin.register(Command)
6
+ class CommandAdmin(NetBoxModelAdmin):
7
+ list_display = ('name', 'platform', 'command_type', 'description')
8
+ list_filter = ('platform', 'command_type')
9
+ search_fields = ('name', 'command', 'description')
10
+
11
+ @admin.register(CommandLog)
12
+ class CommandLogAdmin(NetBoxModelAdmin):
13
+ list_display = ('command', 'device', 'username', 'execution_time')
14
+ list_filter = ('command', 'device', 'username', 'execution_time')
15
+ search_fields = ('command__name', 'device__name', 'username', 'output')
16
+ readonly_fields = ('output', 'execution_time')
@@ -0,0 +1,54 @@
1
+ """
2
+ Common mixins and utilities for NetBox Toolkit API views
3
+ """
4
+ from rest_framework.response import Response
5
+ from django.contrib.contenttypes.models import ContentType
6
+ from users.models import ObjectPermission
7
+
8
+
9
+ class APIResponseMixin:
10
+ """Mixin to add consistent API response headers"""
11
+
12
+ def finalize_response(self, request, response, *args, **kwargs):
13
+ """Add custom headers to all responses"""
14
+ response = super().finalize_response(request, response, *args, **kwargs)
15
+
16
+ # Add API version header
17
+ response['X-NetBox-Toolkit-API-Version'] = '1.0'
18
+
19
+ return response
20
+
21
+
22
+ class PermissionCheckMixin:
23
+ """Mixin for NetBox ObjectPermission checking"""
24
+
25
+ def _user_has_action_permission(self, user, obj, action):
26
+ """Check if user has permission for a specific action on an object using NetBox's ObjectPermission system"""
27
+ # Get content type for the object
28
+ content_type = ContentType.objects.get_for_model(obj)
29
+
30
+ # Check if user has any ObjectPermissions with the required action
31
+ user_permissions = ObjectPermission.objects.filter(
32
+ object_types__in=[content_type],
33
+ actions__contains=[action],
34
+ enabled=True
35
+ )
36
+
37
+ # Check if user is assigned to any groups with this permission
38
+ user_groups = user.groups.all()
39
+ for permission in user_permissions:
40
+ # Check if permission applies to user or user's groups
41
+ if (permission.users.filter(id=user.id).exists() or
42
+ permission.groups.filter(id__in=user_groups.values_list('id', flat=True)).exists()):
43
+
44
+ # If there are constraints, evaluate them
45
+ if permission.constraints:
46
+ # Create a queryset with the constraints and check if the object matches
47
+ queryset = content_type.model_class().objects.filter(**permission.constraints)
48
+ if queryset.filter(id=obj.id).exists():
49
+ return True
50
+ else:
51
+ # No constraints means permission applies to all objects of this type
52
+ return True
53
+
54
+ return False
@@ -0,0 +1,234 @@
1
+ """
2
+ OpenAPI schema definitions for NetBox Toolkit API
3
+ """
4
+ from drf_spectacular.utils import extend_schema, OpenApiResponse
5
+
6
+
7
+ # Command ViewSet Schemas
8
+ COMMAND_LIST_SCHEMA = extend_schema(
9
+ summary="List commands",
10
+ description="Retrieve a list of all commands available in the system.",
11
+ tags=["Commands"]
12
+ )
13
+
14
+ COMMAND_RETRIEVE_SCHEMA = extend_schema(
15
+ summary="Retrieve command",
16
+ description="Retrieve details of a specific command.",
17
+ tags=["Commands"]
18
+ )
19
+
20
+ COMMAND_CREATE_SCHEMA = extend_schema(
21
+ summary="Create command",
22
+ description="Create a new command.",
23
+ tags=["Commands"]
24
+ )
25
+
26
+ COMMAND_UPDATE_SCHEMA = extend_schema(
27
+ summary="Update command",
28
+ description="Update an existing command.",
29
+ tags=["Commands"]
30
+ )
31
+
32
+ COMMAND_PARTIAL_UPDATE_SCHEMA = extend_schema(
33
+ summary="Partial update command",
34
+ description="Partially update an existing command.",
35
+ tags=["Commands"]
36
+ )
37
+
38
+ COMMAND_DESTROY_SCHEMA = extend_schema(
39
+ summary="Delete command",
40
+ description="Delete a command.",
41
+ tags=["Commands"]
42
+ )
43
+
44
+ COMMAND_EXECUTE_SCHEMA = extend_schema(
45
+ summary="Execute command on device",
46
+ description="Execute a specific command on a target device with authentication credentials.",
47
+ tags=["Commands"],
48
+ responses={
49
+ 200: OpenApiResponse(
50
+ description="Command executed successfully",
51
+ examples=[
52
+ {
53
+ "success": True,
54
+ "output": "interface status output...",
55
+ "error_message": None,
56
+ "execution_time": 1.23,
57
+ "command": {
58
+ "id": 1,
59
+ "name": "show interfaces",
60
+ "command_type": "show"
61
+ },
62
+ "device": {
63
+ "id": 1,
64
+ "name": "switch01.example.com"
65
+ },
66
+ "syntax_error": {
67
+ "detected": False
68
+ },
69
+ "parsed_output": {
70
+ "success": True,
71
+ "method": "textfsm",
72
+ "data": [{"interface": "GigabitEthernet1/0/1", "status": "up"}]
73
+ }
74
+ }
75
+ ]
76
+ ),
77
+ 400: OpenApiResponse(
78
+ description="Bad request - validation errors or command execution failed"
79
+ ),
80
+ 403: OpenApiResponse(
81
+ description="Forbidden - insufficient permissions"
82
+ ),
83
+ 404: OpenApiResponse(
84
+ description="Not found - command or device not found"
85
+ ),
86
+ 429: OpenApiResponse(
87
+ description="Too many requests - rate limit exceeded"
88
+ )
89
+ }
90
+ )
91
+
92
+ COMMAND_BULK_EXECUTE_SCHEMA = extend_schema(
93
+ summary="Bulk execute commands",
94
+ description="Execute multiple commands on multiple devices in a single API call.",
95
+ tags=["Commands"],
96
+ request={
97
+ "type": "object",
98
+ "properties": {
99
+ "executions": {
100
+ "type": "array",
101
+ "items": {
102
+ "type": "object",
103
+ "properties": {
104
+ "command_id": {"type": "integer"},
105
+ "device_id": {"type": "integer"},
106
+ "username": {"type": "string"},
107
+ "password": {"type": "string", "format": "password"}
108
+ },
109
+ "required": ["command_id", "device_id", "username", "password"]
110
+ }
111
+ }
112
+ },
113
+ "required": ["executions"]
114
+ },
115
+ responses={
116
+ 200: OpenApiResponse(
117
+ description="Bulk execution completed",
118
+ examples=[
119
+ {
120
+ "results": [
121
+ {"execution_id": 1, "success": True, "command_log_id": 123},
122
+ {"execution_id": 2, "success": False, "error": "Permission denied"}
123
+ ],
124
+ "summary": {
125
+ "total": 2,
126
+ "successful": 1,
127
+ "failed": 1
128
+ }
129
+ }
130
+ ]
131
+ )
132
+ }
133
+ )
134
+
135
+ # Command Log ViewSet Schemas
136
+ COMMAND_LOG_LIST_SCHEMA = extend_schema(
137
+ summary="List command logs",
138
+ description="Retrieve a list of command execution logs with filtering and search capabilities.",
139
+ tags=["Command Logs"]
140
+ )
141
+
142
+ COMMAND_LOG_RETRIEVE_SCHEMA = extend_schema(
143
+ summary="Retrieve command log",
144
+ description="Retrieve details of a specific command execution log.",
145
+ tags=["Command Logs"]
146
+ )
147
+
148
+ COMMAND_LOG_CREATE_SCHEMA = extend_schema(
149
+ summary="Create command log",
150
+ description="Create a new command execution log entry.",
151
+ tags=["Command Logs"]
152
+ )
153
+
154
+ COMMAND_LOG_UPDATE_SCHEMA = extend_schema(
155
+ summary="Update command log",
156
+ description="Update an existing command log entry.",
157
+ tags=["Command Logs"]
158
+ )
159
+
160
+ COMMAND_LOG_PARTIAL_UPDATE_SCHEMA = extend_schema(
161
+ summary="Partial update command log",
162
+ description="Partially update an existing command log entry.",
163
+ tags=["Command Logs"]
164
+ )
165
+
166
+ COMMAND_LOG_DESTROY_SCHEMA = extend_schema(
167
+ summary="Delete command log",
168
+ description="Delete a command log entry.",
169
+ tags=["Command Logs"]
170
+ )
171
+
172
+ COMMAND_LOG_STATISTICS_SCHEMA = extend_schema(
173
+ summary="Get command log statistics",
174
+ description="Retrieve statistics about command execution logs including success rates and common errors.",
175
+ tags=["Command Logs"],
176
+ responses={
177
+ 200: OpenApiResponse(
178
+ description="Statistics retrieved successfully",
179
+ examples=[
180
+ {
181
+ "total_logs": 1000,
182
+ "success_rate": 85.5,
183
+ "last_24h": {
184
+ "total": 50,
185
+ "successful": 45,
186
+ "failed": 5
187
+ },
188
+ "top_commands": [
189
+ {"command_name": "show interfaces", "count": 150},
190
+ {"command_name": "show version", "count": 120}
191
+ ],
192
+ "common_errors": [
193
+ {"error": "Connection timeout", "count": 10},
194
+ {"error": "Invalid command", "count": 5}
195
+ ]
196
+ }
197
+ ]
198
+ )
199
+ }
200
+ )
201
+
202
+ from drf_spectacular.utils import OpenApiParameter
203
+
204
+ COMMAND_LOG_EXPORT_SCHEMA = extend_schema(
205
+ summary="Export command logs",
206
+ description="Export command logs in various formats (CSV, JSON).",
207
+ tags=["Command Logs"],
208
+ parameters=[
209
+ OpenApiParameter(
210
+ name='format',
211
+ description='Export format',
212
+ required=False,
213
+ type=str,
214
+ enum=['csv', 'json'],
215
+ default='json'
216
+ ),
217
+ OpenApiParameter(
218
+ name='start_date',
219
+ description='Start date for export (YYYY-MM-DD)',
220
+ required=False,
221
+ type=str
222
+ ),
223
+ OpenApiParameter(
224
+ name='end_date',
225
+ description='End date for export (YYYY-MM-DD)',
226
+ required=False,
227
+ type=str
228
+ ),
229
+ ],
230
+ responses={
231
+ 200: OpenApiResponse(description="Export data"),
232
+ 400: OpenApiResponse(description="Invalid parameters")
233
+ }
234
+ )