runbooks 0.2.5__py3-none-any.whl → 0.7.0__py3-none-any.whl

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 (249) hide show
  1. conftest.py +26 -0
  2. jupyter-agent/.env +2 -0
  3. jupyter-agent/.env.template +2 -0
  4. jupyter-agent/.gitattributes +35 -0
  5. jupyter-agent/.gradio/certificate.pem +31 -0
  6. jupyter-agent/README.md +16 -0
  7. jupyter-agent/__main__.log +8 -0
  8. jupyter-agent/app.py +256 -0
  9. jupyter-agent/cloudops-agent.png +0 -0
  10. jupyter-agent/ds-system-prompt.txt +154 -0
  11. jupyter-agent/jupyter-agent.png +0 -0
  12. jupyter-agent/llama3_template.jinja +123 -0
  13. jupyter-agent/requirements.txt +9 -0
  14. jupyter-agent/tmp/4ojbs8a02ir/jupyter-agent.ipynb +68 -0
  15. jupyter-agent/tmp/cm5iasgpm3p/jupyter-agent.ipynb +91 -0
  16. jupyter-agent/tmp/crqbsseag5/jupyter-agent.ipynb +91 -0
  17. jupyter-agent/tmp/hohanq1u097/jupyter-agent.ipynb +57 -0
  18. jupyter-agent/tmp/jns1sam29wm/jupyter-agent.ipynb +53 -0
  19. jupyter-agent/tmp/jupyter-agent.ipynb +27 -0
  20. jupyter-agent/utils.py +409 -0
  21. runbooks/__init__.py +71 -3
  22. runbooks/__main__.py +13 -0
  23. runbooks/aws/ec2_describe_instances.py +1 -1
  24. runbooks/aws/ec2_run_instances.py +8 -2
  25. runbooks/aws/ec2_start_stop_instances.py +17 -4
  26. runbooks/aws/ec2_unused_volumes.py +5 -1
  27. runbooks/aws/s3_create_bucket.py +4 -2
  28. runbooks/aws/s3_list_objects.py +6 -1
  29. runbooks/aws/tagging_lambda_handler.py +13 -2
  30. runbooks/aws/tags.json +12 -0
  31. runbooks/base.py +353 -0
  32. runbooks/cfat/README.md +49 -0
  33. runbooks/cfat/__init__.py +74 -0
  34. runbooks/cfat/app.ts +644 -0
  35. runbooks/cfat/assessment/__init__.py +40 -0
  36. runbooks/cfat/assessment/asana-import.csv +39 -0
  37. runbooks/cfat/assessment/cfat-checks.csv +31 -0
  38. runbooks/cfat/assessment/cfat.txt +520 -0
  39. runbooks/cfat/assessment/collectors.py +200 -0
  40. runbooks/cfat/assessment/jira-import.csv +39 -0
  41. runbooks/cfat/assessment/runner.py +387 -0
  42. runbooks/cfat/assessment/validators.py +290 -0
  43. runbooks/cfat/cli.py +103 -0
  44. runbooks/cfat/docs/asana-import.csv +24 -0
  45. runbooks/cfat/docs/cfat-checks.csv +31 -0
  46. runbooks/cfat/docs/cfat.txt +335 -0
  47. runbooks/cfat/docs/checks-output.png +0 -0
  48. runbooks/cfat/docs/cloudshell-console-run.png +0 -0
  49. runbooks/cfat/docs/cloudshell-download.png +0 -0
  50. runbooks/cfat/docs/cloudshell-output.png +0 -0
  51. runbooks/cfat/docs/downloadfile.png +0 -0
  52. runbooks/cfat/docs/jira-import.csv +24 -0
  53. runbooks/cfat/docs/open-cloudshell.png +0 -0
  54. runbooks/cfat/docs/report-header.png +0 -0
  55. runbooks/cfat/models.py +1026 -0
  56. runbooks/cfat/package-lock.json +5116 -0
  57. runbooks/cfat/package.json +38 -0
  58. runbooks/cfat/report.py +496 -0
  59. runbooks/cfat/reporting/__init__.py +46 -0
  60. runbooks/cfat/reporting/exporters.py +337 -0
  61. runbooks/cfat/reporting/formatters.py +496 -0
  62. runbooks/cfat/reporting/templates.py +135 -0
  63. runbooks/cfat/run-assessment.sh +23 -0
  64. runbooks/cfat/runner.py +69 -0
  65. runbooks/cfat/src/actions/check-cloudtrail-existence.ts +43 -0
  66. runbooks/cfat/src/actions/check-config-existence.ts +37 -0
  67. runbooks/cfat/src/actions/check-control-tower.ts +37 -0
  68. runbooks/cfat/src/actions/check-ec2-existence.ts +46 -0
  69. runbooks/cfat/src/actions/check-iam-users.ts +50 -0
  70. runbooks/cfat/src/actions/check-legacy-cur.ts +30 -0
  71. runbooks/cfat/src/actions/check-org-cloudformation.ts +30 -0
  72. runbooks/cfat/src/actions/check-vpc-existence.ts +43 -0
  73. runbooks/cfat/src/actions/create-asanaimport.ts +14 -0
  74. runbooks/cfat/src/actions/create-backlog.ts +372 -0
  75. runbooks/cfat/src/actions/create-jiraimport.ts +15 -0
  76. runbooks/cfat/src/actions/create-report.ts +616 -0
  77. runbooks/cfat/src/actions/define-account-type.ts +51 -0
  78. runbooks/cfat/src/actions/get-enabled-org-policy-types.ts +40 -0
  79. runbooks/cfat/src/actions/get-enabled-org-services.ts +26 -0
  80. runbooks/cfat/src/actions/get-idc-info.ts +34 -0
  81. runbooks/cfat/src/actions/get-org-da-accounts.ts +34 -0
  82. runbooks/cfat/src/actions/get-org-details.ts +35 -0
  83. runbooks/cfat/src/actions/get-org-member-accounts.ts +44 -0
  84. runbooks/cfat/src/actions/get-org-ous.ts +35 -0
  85. runbooks/cfat/src/actions/get-regions.ts +22 -0
  86. runbooks/cfat/src/actions/zip-assessment.ts +27 -0
  87. runbooks/cfat/src/types/index.d.ts +147 -0
  88. runbooks/cfat/tests/__init__.py +141 -0
  89. runbooks/cfat/tests/test_cli.py +340 -0
  90. runbooks/cfat/tests/test_integration.py +290 -0
  91. runbooks/cfat/tests/test_models.py +505 -0
  92. runbooks/cfat/tests/test_reporting.py +354 -0
  93. runbooks/cfat/tsconfig.json +16 -0
  94. runbooks/cfat/webpack.config.cjs +27 -0
  95. runbooks/config.py +260 -0
  96. runbooks/finops/README.md +337 -0
  97. runbooks/finops/__init__.py +86 -0
  98. runbooks/finops/aws_client.py +245 -0
  99. runbooks/finops/cli.py +151 -0
  100. runbooks/finops/cost_processor.py +410 -0
  101. runbooks/finops/dashboard_runner.py +448 -0
  102. runbooks/finops/helpers.py +355 -0
  103. runbooks/finops/main.py +14 -0
  104. runbooks/finops/profile_processor.py +174 -0
  105. runbooks/finops/types.py +66 -0
  106. runbooks/finops/visualisations.py +80 -0
  107. runbooks/inventory/.gitignore +354 -0
  108. runbooks/inventory/ArgumentsClass.py +261 -0
  109. runbooks/inventory/FAILED_SCRIPTS_TROUBLESHOOTING.md +619 -0
  110. runbooks/inventory/Inventory_Modules.py +6130 -0
  111. runbooks/inventory/LandingZone/delete_lz.py +1075 -0
  112. runbooks/inventory/PASSED_SCRIPTS_GUIDE.md +738 -0
  113. runbooks/inventory/README.md +1320 -0
  114. runbooks/inventory/__init__.py +62 -0
  115. runbooks/inventory/account_class.py +532 -0
  116. runbooks/inventory/all_my_instances_wrapper.py +123 -0
  117. runbooks/inventory/aws_decorators.py +201 -0
  118. runbooks/inventory/aws_organization.png +0 -0
  119. runbooks/inventory/cfn_move_stack_instances.py +1526 -0
  120. runbooks/inventory/check_cloudtrail_compliance.py +614 -0
  121. runbooks/inventory/check_controltower_readiness.py +1107 -0
  122. runbooks/inventory/check_landingzone_readiness.py +711 -0
  123. runbooks/inventory/cloudtrail.md +727 -0
  124. runbooks/inventory/collectors/__init__.py +20 -0
  125. runbooks/inventory/collectors/aws_compute.py +518 -0
  126. runbooks/inventory/collectors/aws_networking.py +275 -0
  127. runbooks/inventory/collectors/base.py +222 -0
  128. runbooks/inventory/core/__init__.py +19 -0
  129. runbooks/inventory/core/collector.py +303 -0
  130. runbooks/inventory/core/formatter.py +296 -0
  131. runbooks/inventory/delete_s3_buckets_objects.py +169 -0
  132. runbooks/inventory/discovery.md +81 -0
  133. runbooks/inventory/draw_org_structure.py +748 -0
  134. runbooks/inventory/ec2_vpc_utils.py +341 -0
  135. runbooks/inventory/find_cfn_drift_detection.py +272 -0
  136. runbooks/inventory/find_cfn_orphaned_stacks.py +719 -0
  137. runbooks/inventory/find_cfn_stackset_drift.py +733 -0
  138. runbooks/inventory/find_ec2_security_groups.py +669 -0
  139. runbooks/inventory/find_landingzone_versions.py +201 -0
  140. runbooks/inventory/find_vpc_flow_logs.py +1221 -0
  141. runbooks/inventory/inventory.sh +659 -0
  142. runbooks/inventory/list_cfn_stacks.py +558 -0
  143. runbooks/inventory/list_cfn_stackset_operation_results.py +252 -0
  144. runbooks/inventory/list_cfn_stackset_operations.py +734 -0
  145. runbooks/inventory/list_cfn_stacksets.py +453 -0
  146. runbooks/inventory/list_config_recorders_delivery_channels.py +681 -0
  147. runbooks/inventory/list_ds_directories.py +354 -0
  148. runbooks/inventory/list_ec2_availability_zones.py +286 -0
  149. runbooks/inventory/list_ec2_ebs_volumes.py +244 -0
  150. runbooks/inventory/list_ec2_instances.py +425 -0
  151. runbooks/inventory/list_ecs_clusters_and_tasks.py +562 -0
  152. runbooks/inventory/list_elbs_load_balancers.py +411 -0
  153. runbooks/inventory/list_enis_network_interfaces.py +526 -0
  154. runbooks/inventory/list_guardduty_detectors.py +568 -0
  155. runbooks/inventory/list_iam_policies.py +404 -0
  156. runbooks/inventory/list_iam_roles.py +518 -0
  157. runbooks/inventory/list_iam_saml_providers.py +359 -0
  158. runbooks/inventory/list_lambda_functions.py +882 -0
  159. runbooks/inventory/list_org_accounts.py +446 -0
  160. runbooks/inventory/list_org_accounts_users.py +354 -0
  161. runbooks/inventory/list_rds_db_instances.py +406 -0
  162. runbooks/inventory/list_route53_hosted_zones.py +318 -0
  163. runbooks/inventory/list_servicecatalog_provisioned_products.py +575 -0
  164. runbooks/inventory/list_sns_topics.py +360 -0
  165. runbooks/inventory/list_ssm_parameters.py +402 -0
  166. runbooks/inventory/list_vpc_subnets.py +433 -0
  167. runbooks/inventory/list_vpcs.py +422 -0
  168. runbooks/inventory/lockdown_cfn_stackset_role.py +224 -0
  169. runbooks/inventory/models/__init__.py +24 -0
  170. runbooks/inventory/models/account.py +192 -0
  171. runbooks/inventory/models/inventory.py +309 -0
  172. runbooks/inventory/models/resource.py +247 -0
  173. runbooks/inventory/recover_cfn_stack_ids.py +205 -0
  174. runbooks/inventory/requirements.txt +12 -0
  175. runbooks/inventory/run_on_multi_accounts.py +211 -0
  176. runbooks/inventory/tests/common_test_data.py +3661 -0
  177. runbooks/inventory/tests/common_test_functions.py +204 -0
  178. runbooks/inventory/tests/setup.py +24 -0
  179. runbooks/inventory/tests/src.py +18 -0
  180. runbooks/inventory/tests/test_cfn_describe_stacks.py +208 -0
  181. runbooks/inventory/tests/test_ec2_describe_instances.py +162 -0
  182. runbooks/inventory/tests/test_inventory_modules.py +55 -0
  183. runbooks/inventory/tests/test_lambda_list_functions.py +86 -0
  184. runbooks/inventory/tests/test_moto_integration_example.py +273 -0
  185. runbooks/inventory/tests/test_org_list_accounts.py +49 -0
  186. runbooks/inventory/update_aws_actions.py +173 -0
  187. runbooks/inventory/update_cfn_stacksets.py +1215 -0
  188. runbooks/inventory/update_cloudwatch_logs_retention_policy.py +294 -0
  189. runbooks/inventory/update_iam_roles_cross_accounts.py +478 -0
  190. runbooks/inventory/update_s3_public_access_block.py +539 -0
  191. runbooks/inventory/utils/__init__.py +23 -0
  192. runbooks/inventory/utils/aws_helpers.py +510 -0
  193. runbooks/inventory/utils/threading_utils.py +493 -0
  194. runbooks/inventory/utils/validation.py +682 -0
  195. runbooks/inventory/verify_ec2_security_groups.py +1430 -0
  196. runbooks/main.py +1004 -0
  197. runbooks/organizations/__init__.py +12 -0
  198. runbooks/organizations/manager.py +374 -0
  199. runbooks/security/README.md +447 -0
  200. runbooks/security/__init__.py +71 -0
  201. runbooks/{security_baseline → security}/checklist/alternate_contacts.py +8 -1
  202. runbooks/{security_baseline → security}/checklist/bucket_public_access.py +4 -1
  203. runbooks/{security_baseline → security}/checklist/cloudwatch_alarm_configuration.py +9 -2
  204. runbooks/{security_baseline → security}/checklist/guardduty_enabled.py +9 -2
  205. runbooks/{security_baseline → security}/checklist/multi_region_instance_usage.py +5 -1
  206. runbooks/{security_baseline → security}/checklist/root_access_key.py +6 -1
  207. runbooks/{security_baseline → security}/config-origin.json +1 -1
  208. runbooks/{security_baseline → security}/config.json +1 -1
  209. runbooks/{security_baseline → security}/permission.json +1 -1
  210. runbooks/{security_baseline → security}/report_generator.py +10 -2
  211. runbooks/{security_baseline → security}/report_template_en.html +7 -7
  212. runbooks/{security_baseline → security}/report_template_jp.html +7 -7
  213. runbooks/{security_baseline → security}/report_template_kr.html +12 -12
  214. runbooks/{security_baseline → security}/report_template_vn.html +7 -7
  215. runbooks/{security_baseline → security}/run_script.py +8 -2
  216. runbooks/{security_baseline → security}/security_baseline_tester.py +12 -4
  217. runbooks/{security_baseline → security}/utils/common.py +5 -1
  218. runbooks/utils/__init__.py +204 -0
  219. runbooks-0.7.0.dist-info/METADATA +375 -0
  220. runbooks-0.7.0.dist-info/RECORD +249 -0
  221. {runbooks-0.2.5.dist-info → runbooks-0.7.0.dist-info}/WHEEL +1 -1
  222. runbooks-0.7.0.dist-info/entry_points.txt +7 -0
  223. runbooks-0.7.0.dist-info/licenses/LICENSE +201 -0
  224. runbooks-0.7.0.dist-info/top_level.txt +3 -0
  225. runbooks/python101/calculator.py +0 -34
  226. runbooks/python101/config.py +0 -1
  227. runbooks/python101/exceptions.py +0 -16
  228. runbooks/python101/file_manager.py +0 -218
  229. runbooks/python101/toolkit.py +0 -153
  230. runbooks-0.2.5.dist-info/METADATA +0 -439
  231. runbooks-0.2.5.dist-info/RECORD +0 -61
  232. runbooks-0.2.5.dist-info/entry_points.txt +0 -3
  233. runbooks-0.2.5.dist-info/top_level.txt +0 -1
  234. /runbooks/{security_baseline/__init__.py → inventory/tests/script_test_data.py} +0 -0
  235. /runbooks/{security_baseline → security}/checklist/__init__.py +0 -0
  236. /runbooks/{security_baseline → security}/checklist/account_level_bucket_public_access.py +0 -0
  237. /runbooks/{security_baseline → security}/checklist/direct_attached_policy.py +0 -0
  238. /runbooks/{security_baseline → security}/checklist/iam_password_policy.py +0 -0
  239. /runbooks/{security_baseline → security}/checklist/iam_user_mfa.py +0 -0
  240. /runbooks/{security_baseline → security}/checklist/multi_region_trail.py +0 -0
  241. /runbooks/{security_baseline → security}/checklist/root_mfa.py +0 -0
  242. /runbooks/{security_baseline → security}/checklist/root_usage.py +0 -0
  243. /runbooks/{security_baseline → security}/checklist/trail_enabled.py +0 -0
  244. /runbooks/{security_baseline → security}/checklist/trusted_advisor.py +0 -0
  245. /runbooks/{security_baseline → security}/utils/__init__.py +0 -0
  246. /runbooks/{security_baseline → security}/utils/enums.py +0 -0
  247. /runbooks/{security_baseline → security}/utils/language.py +0 -0
  248. /runbooks/{security_baseline → security}/utils/level_const.py +0 -0
  249. /runbooks/{security_baseline → security}/utils/permission_list.py +0 -0
@@ -0,0 +1,526 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ AWS Elastic Network Interfaces (ENI) Discovery and Analysis Script
5
+
6
+ This script provides comprehensive discovery and inventory capabilities for AWS Elastic
7
+ Network Interfaces (ENIs) across multiple accounts and regions. It's designed for enterprise
8
+ network teams who need visibility into network interface distribution, IP address management,
9
+ and network security analysis across large-scale AWS deployments.
10
+
11
+ Key Features:
12
+ - Multi-account ENI discovery using assume role capabilities
13
+ - Multi-region scanning with configurable region targeting
14
+ - IP address search and tracking for network forensics and management
15
+ - Public IP filtering for security posture analysis
16
+ - ENI status monitoring for cost optimization (unused ENIs detection)
17
+ - Enterprise reporting with CSV export and structured output
18
+ - Profile-based authentication with support for federated access
19
+
20
+ Enterprise Use Cases:
21
+ - Network inventory and IP address management (IPAM) across organizations
22
+ - Security analysis for public IP exposure and network attack surface
23
+ - Cost optimization through detection of unused network interfaces
24
+ - Network forensics and IP address tracking for incident response
25
+ - Compliance reporting for network security and configuration standards
26
+ - Multi-account network architecture documentation and governance
27
+ - Capacity planning for network interface allocation and utilization
28
+
29
+ Network Interface Analysis Features:
30
+ - ENI enumeration with attachment status and configuration details
31
+ - IP address tracking for both private and public allocations
32
+ - VPC and subnet association analysis for network topology mapping
33
+ - Security group and network ACL configuration visibility
34
+ - DNS name resolution and endpoint management
35
+ - Network interface lifecycle and cost optimization analysis
36
+
37
+ Security Considerations:
38
+ - Uses IAM assume role capabilities for cross-account ENI access
39
+ - Implements proper error handling for authorization failures
40
+ - Supports read-only operations with no network interface modification capabilities
41
+ - Respects EC2 service permissions and regional access constraints
42
+ - Provides comprehensive audit trail through detailed logging
43
+ - Sensitive IP address information handling with appropriate access controls
44
+
45
+ IP Address Management Features:
46
+ - Targeted IP address search for network forensics and tracking
47
+ - Public IP enumeration for security assessment and compliance
48
+ - Private IP allocation analysis for network capacity planning
49
+ - ENI attachment status for resource utilization tracking
50
+ - Cross-account IP address correlation and conflict detection
51
+
52
+ Performance Considerations:
53
+ - Multi-threaded processing for concurrent ENI API operations
54
+ - Progress tracking with tqdm for operational visibility during long operations
55
+ - Efficient credential management for cross-account network access
56
+ - Memory-optimized data structures for large network interface inventories
57
+ - Queue-based worker architecture for scalable discovery operations
58
+
59
+ Threading Architecture:
60
+ - Worker thread pool with configurable concurrency (max 50 threads for ENI APIs)
61
+ - Queue-based task distribution for efficient network interface discovery
62
+ - Thread-safe error handling and progress tracking
63
+ - Graceful degradation for account access failures
64
+
65
+ Dependencies:
66
+ - boto3/botocore for AWS EC2 ENI API interactions
67
+ - Inventory_Modules for common utility functions and credential management
68
+ - ArgumentsClass for standardized CLI argument parsing
69
+ - threading and queue for concurrent processing architecture
70
+ - colorama for enhanced output formatting and tqdm for progress tracking
71
+
72
+ Cost Optimization Features:
73
+ - Detection of detached ENIs that incur charges without providing value
74
+ - ENI lifecycle analysis for resource optimization recommendations
75
+ - Public IP usage tracking for cost management
76
+ - Network interface utilization reporting for capacity planning
77
+
78
+ Future Enhancements:
79
+ - ENI security group analysis and compliance checking
80
+ - Network traffic analysis integration for performance optimization
81
+ - Automated ENI cleanup recommendations for cost reduction
82
+ - Integration with AWS Config for network configuration drift detection
83
+
84
+ Author: AWS CloudOps Team
85
+ Version: 2024.10.24
86
+ """
87
+
88
+ import logging
89
+ import os
90
+ import sys
91
+ from queue import Queue
92
+ from threading import Thread
93
+ from time import time
94
+
95
+ from ArgumentsClass import CommonArguments
96
+ from botocore.exceptions import ClientError
97
+
98
+ # from datetime import datetime
99
+ from colorama import Fore, init
100
+ from Inventory_Modules import display_results, find_account_enis2, get_all_credentials
101
+ from tqdm.auto import tqdm
102
+
103
+ init()
104
+
105
+ __version__ = "2024.10.24"
106
+
107
+
108
+ ##################
109
+ # Functions
110
+ ##################
111
+
112
+
113
+ def parse_args(f_args):
114
+ """
115
+ Parse command line arguments for AWS Elastic Network Interface discovery operations.
116
+
117
+ Configures comprehensive argument parsing for multi-account, multi-region ENI
118
+ inventory operations. Supports enterprise network management with profile
119
+ management, region targeting, organizational access controls, IP address search,
120
+ and public IP filtering for network security analysis and IP address management.
121
+
122
+ Args:
123
+ f_args (list): Command line arguments from sys.argv[1:]
124
+
125
+ Returns:
126
+ argparse.Namespace: Parsed arguments containing:
127
+ - Profiles: List of AWS profiles to process
128
+ - Regions: Target regions for ENI discovery
129
+ - SkipProfiles/SkipAccounts: Exclusion filters
130
+ - RootOnly: Limit to organization root accounts
131
+ - Filename: Output file for CSV export
132
+ - Time: Enable performance timing metrics
133
+ - loglevel: Logging verbosity configuration
134
+ - pipaddresses: Specific IP addresses to search for
135
+ - ppublic: Filter for public IP addresses only
136
+
137
+ Configuration Options:
138
+ - Multi-region scanning with region filters for targeted network analysis
139
+ - Multi-profile support for federated access across network infrastructure
140
+ - Extended arguments for advanced filtering and account selection
141
+ - Root-only mode for organization-level network inventory
142
+ - File output for integration with network management tools
143
+ - Timing metrics for performance optimization and monitoring
144
+ - Verbose logging for debugging and network audit
145
+
146
+ ENI-Specific Features:
147
+ - IP address search for network forensics and incident response
148
+ - Public IP filtering for security posture analysis and compliance
149
+ - Support for network topology analysis and documentation
150
+ - Integration with enterprise IP address management (IPAM) workflows
151
+
152
+ Network Security Options:
153
+ - Targeted IP address discovery for forensic analysis
154
+ - Public IP enumeration for attack surface assessment
155
+ - Network interface status filtering for cost optimization
156
+ - Cross-account network visibility for security governance
157
+ """
158
+ parser = CommonArguments()
159
+ script_path, script_name = os.path.split(sys.argv[0])
160
+ parser.multiprofile()
161
+ parser.multiregion()
162
+ parser.extendedargs()
163
+ parser.rootOnly()
164
+ parser.timing()
165
+ parser.save_to_file()
166
+ parser.verbosity()
167
+ parser.version(__version__)
168
+ local = parser.my_parser.add_argument_group(script_name, "Parameters specific to this script")
169
+ local.add_argument(
170
+ "--ipaddress",
171
+ "--ip",
172
+ dest="pipaddresses",
173
+ nargs="*",
174
+ metavar="IP address",
175
+ default=None,
176
+ help="Specific IP address(es) to search for across network interfaces - supports multiple IPs for forensic analysis",
177
+ )
178
+ local.add_argument(
179
+ "--public-only",
180
+ "--po",
181
+ action="store_true",
182
+ dest="ppublic",
183
+ help="Filter results to show only ENIs with public IP addresses for security posture analysis",
184
+ )
185
+ return parser.my_parser.parse_args(f_args)
186
+
187
+
188
+ def check_accounts_for_enis(fCredentialList, fip=None, fPublicOnly: bool = False):
189
+ """
190
+ Discover and inventory AWS Elastic Network Interfaces across multiple accounts and regions.
191
+
192
+ Performs comprehensive ENI discovery using multi-threaded processing to efficiently
193
+ inventory network interfaces across enterprise AWS environments. Supports IP address
194
+ filtering for targeted search operations and public IP filtering for security analysis
195
+ and compliance assessment.
196
+
197
+ Args:
198
+ fCredentialList (list): List of credential dictionaries for cross-account access containing:
199
+ - AccountId: AWS account number
200
+ - Region: Target AWS region
201
+ - Success: Boolean indicating credential validity
202
+ - MgmtAccount: Management account identifier
203
+ - ParentProfile: Source AWS profile
204
+ fip (list, optional): Specific IP addresses to search for across network interfaces
205
+ fPublicOnly (bool, optional): Filter to show only ENIs with public IP addresses
206
+
207
+ Returns:
208
+ list: Comprehensive list of ENI dictionaries containing:
209
+ - MgmtAccount: Management account identifier for organizational hierarchy
210
+ - AccountId: AWS account containing the ENI
211
+ - Region: AWS region where ENI is located
212
+ - ENIId: Elastic Network Interface identifier
213
+ - PrivateIpAddress: Primary private IP address assignment
214
+ - PublicIp: Associated public IP address (if any)
215
+ - Status: Current ENI state (available, in-use, attaching, detaching)
216
+ - VpcId: Virtual Private Cloud association
217
+ - SubnetId: Subnet placement for network topology
218
+ - PrivateDnsName: Internal DNS name resolution
219
+
220
+ Threading Architecture:
221
+ - Worker thread pool with maximum 50 concurrent threads for ENI API optimization
222
+ - Queue-based task distribution for efficient network interface discovery
223
+ - Thread-safe error handling and progress tracking with tqdm
224
+ - Graceful degradation for account access failures and authorization issues
225
+
226
+ Enterprise Features:
227
+ - Cross-account ENI discovery with assume role capabilities
228
+ - IP address search for network forensics and incident response
229
+ - Public IP filtering for security posture analysis and compliance
230
+ - Comprehensive error handling for authorization and throttling scenarios
231
+
232
+ Network Security Analysis:
233
+ - Public IP enumeration for attack surface assessment
234
+ - ENI status tracking for unused resource identification
235
+ - Cross-account network visibility for security governance
236
+ - IP address correlation for forensic investigations
237
+
238
+ Error Handling:
239
+ - Authorization failure detection with region opt-in diagnostics
240
+ - AWS API throttling management with appropriate logging
241
+ - Graceful handling of missing ENIs and empty responses
242
+ - Thread-safe error reporting and progress updates
243
+
244
+ Performance Considerations:
245
+ - High concurrency (50 threads) optimized for ENI API characteristics
246
+ - Efficient memory management for large network interface inventories
247
+ - Progress tracking for operational visibility during discovery
248
+ - ENI metadata extraction for enterprise network management
249
+
250
+ Cost Optimization:
251
+ - Detection of unused ENIs that incur charges without providing value
252
+ - Public IP usage analysis for cost management
253
+ - Network interface lifecycle tracking for optimization
254
+ """
255
+
256
+ # Worker thread class for concurrent ENI discovery
257
+ class FindENIs(Thread):
258
+ def __init__(self, queue):
259
+ Thread.__init__(self)
260
+ self.queue = queue
261
+
262
+ def run(self):
263
+ """
264
+ Main worker thread execution loop for ENI discovery and network interface analysis.
265
+
266
+ Continuously processes credential sets from the shared work queue, performing
267
+ comprehensive Elastic Network Interface discovery operations with detailed
268
+ metadata extraction and enterprise network security analysis.
269
+ """
270
+ while True:
271
+ # Retrieve ENI discovery work item from thread-safe queue
272
+ c_account_credentials, c_region, c_fip, c_PlacesToLook, c_PlaceCount = self.queue.get()
273
+ pbar.update() # Update progress tracking for operational visibility
274
+ logging.info(f"De-queued info for account {c_account_credentials['AccountId']}")
275
+
276
+ try:
277
+ logging.info(f"Attempting to connect to {c_account_credentials['AccountId']}")
278
+
279
+ # Execute comprehensive ENI discovery for the current account/region
280
+ # This calls the inventory module's specialized ENI discovery function with IP filtering
281
+ account_enis = find_account_enis2(c_account_credentials, c_region, c_fip)
282
+ logging.info(
283
+ f"Successfully connected to account {c_account_credentials['AccountId']} in region {c_region}"
284
+ )
285
+
286
+ # Process each discovered ENI with comprehensive metadata extraction and filtering
287
+ for eni in account_enis:
288
+ # Add organizational context for multi-account network management
289
+ eni["MgmtAccount"] = c_account_credentials["MgmtAccount"]
290
+
291
+ # Apply public IP filtering for security posture analysis when requested
292
+ if fPublicOnly and eni["PublicIp"] == "No Public IP":
293
+ # Skip ENIs without public IPs when security analysis filter is active
294
+ # This is critical for attack surface assessment and compliance reporting
295
+ pass
296
+ else:
297
+ # Include ENI in enterprise network inventory for comprehensive reporting
298
+ # ENI contains detailed network interface metadata:
299
+ # - IP address assignments (private and public)
300
+ # - VPC and subnet associations for topology mapping
301
+ # - Security group configurations for access control analysis
302
+ # - DNS name resolution for endpoint management
303
+ # - Attachment status for cost optimization analysis
304
+ Results.append(eni)
305
+
306
+ except KeyError as my_Error:
307
+ # Handle cases where expected keys are missing from ENI API responses
308
+ # This can occur with incomplete ENI metadata or API response format changes
309
+ logging.error(f"Account Access failed - trying to access {c_account_credentials['AccountId']}")
310
+ logging.info(f"Actual Error: {my_Error}")
311
+ pass
312
+ except AttributeError as my_Error:
313
+ # Handle cases where profile configuration is incorrect or credential format errors
314
+ # This typically indicates AWS profile misconfiguration or credential management issues
315
+ logging.error(f"Error: Likely that one of the supplied profiles {pProfiles} was wrong")
316
+ logging.warning(my_Error)
317
+ continue
318
+ finally:
319
+ # Always ensure queue management regardless of success/failure for thread pool stability
320
+ # Critical for preventing worker thread deadlock and ensuring operation completion
321
+ self.queue.task_done()
322
+
323
+ # Initialize queue-based threading architecture for scalable ENI discovery
324
+ checkqueue = Queue()
325
+
326
+ # Initialize progress tracking for operational visibility during large-scale operations
327
+ pbar = tqdm(
328
+ desc=f"Finding enis from {len(CredentialList)} accounts / regions",
329
+ total=len(fCredentialList),
330
+ unit=" locations",
331
+ )
332
+
333
+ # Initialize results list for aggregating discovered ENIs
334
+ Results = []
335
+ PlaceCount = 0
336
+ PlacesToLook = fCredentialList.__len__()
337
+
338
+ # Configure worker thread pool size optimized for ENI API characteristics
339
+ # Maximum 50 threads to balance performance with AWS API rate limits
340
+ WorkerThreads = min(len(fCredentialList), 50)
341
+
342
+ # Start worker threads for concurrent ENI discovery
343
+ for x in range(WorkerThreads):
344
+ worker = FindENIs(checkqueue)
345
+ # Setting daemon to True allows main thread exit even if workers are still processing
346
+ worker.daemon = True
347
+ worker.start()
348
+
349
+ # Queue credential sets for processing by worker threads
350
+ for credential in fCredentialList:
351
+ logging.info(f"Connecting to account {credential['AccountId']} in region {credential['Region']}")
352
+ try:
353
+ # Queue credential set with IP filter and progress tracking parameters
354
+ # Tuple format: (credentials, region, ip_filter, total_places, current_count)
355
+ checkqueue.put((credential, credential["Region"], fip, PlacesToLook, PlaceCount))
356
+ PlaceCount += 1
357
+ except ClientError as my_Error:
358
+ # Handle authorization failures during credential queuing
359
+ if "AuthFailure" in str(my_Error):
360
+ logging.error(
361
+ f"Authorization Failure accessing account {credential['AccountId']} in {credential['Region']} region"
362
+ )
363
+ logging.warning(f"It's possible that the region {credential['Region']} hasn't been opted-into")
364
+ pass
365
+
366
+ # Wait for all queued work to complete before proceeding
367
+ checkqueue.join()
368
+ return Results
369
+
370
+
371
+ def present_results(f_ENIsFound: list):
372
+ """
373
+ Present comprehensive ENI discovery results with enterprise network analysis and cost optimization insights.
374
+
375
+ Generates detailed network interface inventory reports with organizational hierarchy,
376
+ security posture analysis, and cost optimization recommendations. Identifies unused
377
+ ENIs that may be generating unnecessary charges and provides executive-level
378
+ operational summaries for network management decision-making.
379
+
380
+ Args:
381
+ f_ENIsFound (list): List of discovered ENI dictionaries containing:
382
+ - Network interface metadata and organizational context
383
+ - IP address assignments and DNS configuration
384
+ - VPC/subnet associations for topology analysis
385
+ - Status information for cost optimization assessment
386
+
387
+ Report Features:
388
+ - Hierarchical organization by management account and region
389
+ - Status-based filtering highlighting cost optimization opportunities
390
+ - Public IP analysis for security posture assessment
391
+ - Comprehensive network topology and resource utilization metrics
392
+
393
+ Cost Optimization Analysis:
394
+ - Identifies detached ENIs that incur charges without providing value
395
+ - Highlights ENIs in transitional states (attaching, detaching)
396
+ - Provides actionable recommendations for network resource cleanup
397
+ - Calculates potential cost savings from unused network interfaces
398
+
399
+ Enterprise Reporting:
400
+ - Multi-account network visibility with management hierarchy
401
+ - Regional distribution analysis for capacity planning
402
+ - Public IP exposure analysis for security compliance
403
+ - CSV export integration for network management tool integration
404
+ """
405
+ # Configure enterprise ENI inventory report display formatting for network management analysis
406
+ display_dict = {
407
+ "MgmtAccount": {"DisplayOrder": 1, "Heading": "Mgmt Acct"}, # Management account hierarchy
408
+ "AccountId": {"DisplayOrder": 2, "Heading": "Acct Number"}, # Account identifier for governance
409
+ "Region": {"DisplayOrder": 3, "Heading": "Region"}, # AWS region for geographic distribution
410
+ "PrivateDnsName": {"DisplayOrder": 4, "Heading": "ENI Name"}, # DNS name for endpoint identification
411
+ "Status": {
412
+ "DisplayOrder": 5,
413
+ "Heading": "Status",
414
+ "Condition": ["available", "attaching", "detaching"],
415
+ }, # Operational state for cost analysis
416
+ "PublicIp": {"DisplayOrder": 6, "Heading": "Public IP Address"}, # Public IP for security analysis
417
+ "ENIId": {"DisplayOrder": 7, "Heading": "ENI Id"}, # ENI identifier for management
418
+ "PrivateIpAddress": {"DisplayOrder": 8, "Heading": "Assoc. IP"}, # Private IP assignment
419
+ }
420
+
421
+ # Sort ENIs for consistent enterprise reporting and network topology analysis
422
+ sorted_ENIs_Found = sorted(f_ENIsFound, key=lambda d: (d["MgmtAccount"], d["AccountId"], d["Region"], d["VpcId"]))
423
+
424
+ # Generate comprehensive ENI inventory report with CSV export capability
425
+ display_results(sorted_ENIs_Found, display_dict, "None", pFilename)
426
+
427
+ # Identify detached ENIs for cost optimization analysis and recommendations
428
+ # ENIs in these states incur charges but provide no operational value
429
+ DetachedENIs = [x for x in sorted_ENIs_Found if x["Status"] in ["available", "attaching", "detaching"]]
430
+
431
+ # Calculate organizational scope metrics for executive network management reporting
432
+ RegionList = list(set([x["Region"] for x in sorted_ENIs_Found]))
433
+ AccountList = list(set([x["AccountId"] for x in sorted_ENIs_Found]))
434
+
435
+ # Display exclusion information for audit trail and operational transparency
436
+ print() if pSkipAccounts is not None or pSkipProfiles is not None else ""
437
+ print(f"These accounts were skipped - as requested: {pSkipAccounts}") if pSkipAccounts is not None else ""
438
+ print(f"These profiles were skipped - as requested: {pSkipProfiles}") if pSkipProfiles is not None else ""
439
+ print()
440
+
441
+ # Inform user about CSV export capability for integration with network management tools
442
+ print(
443
+ f"The output has also been written to a file beginning with '{pFilename}' + the date and time"
444
+ ) if pFilename is not None else ""
445
+
446
+ # Display comprehensive operational summary for executive network management reporting
447
+ print(
448
+ f"Found {len(f_ENIsFound)} ENIs {'with public IPs' if pPublicOnly else ''} across {len(AccountList)} accounts across {len(RegionList)} regions"
449
+ )
450
+
451
+ # Highlight cost optimization opportunities with unused ENI identification
452
+ print(
453
+ f"{Fore.RED}Found {len(DetachedENIs)} ENIs that are not listed as 'in-use' and may therefore be costing you additional money while they're unused.{Fore.RESET}"
454
+ ) if DetachedENIs else ""
455
+ print()
456
+
457
+ # Provide detailed cost optimization analysis when verbose logging is enabled
458
+ if verbose < 40:
459
+ for x in DetachedENIs:
460
+ print(x)
461
+
462
+
463
+ ##################
464
+ # Main execution entry point for enterprise ENI discovery and network security analysis
465
+ ##################
466
+
467
+ ERASE_LINE = "\x1b[2K"
468
+
469
+ if __name__ == "__main__":
470
+ """
471
+ Main orchestration for comprehensive Elastic Network Interface discovery and analysis.
472
+
473
+ Coordinates multi-account, multi-region ENI inventory with detailed network security
474
+ analysis, IP address management support, and enterprise network infrastructure
475
+ governance across AWS Organizations environments.
476
+ """
477
+ # Parse enterprise command-line arguments with ENI-specific network security options
478
+ args = parse_args(sys.argv[1:])
479
+
480
+ # Extract configuration parameters for multi-account network interface discovery
481
+ pProfiles = args.Profiles # AWS profile list for federated ENI access
482
+ pRegionList = args.Regions # Target regions for network interface enumeration
483
+ pSkipAccounts = args.SkipAccounts # Account exclusion list for organizational policy compliance
484
+ pSkipProfiles = args.SkipProfiles # Profile exclusion for credential optimization
485
+ pAccounts = args.Accounts # Specific account targeting for focused network analysis
486
+ pRootOnly = args.RootOnly # Organization root account limitation flag
487
+ pIPaddressList = args.pipaddresses # Specific IP addresses for forensic analysis and tracking
488
+ pPublicOnly = args.ppublic # Public IP filter for security posture assessment
489
+ pFilename = args.Filename # CSV export file for enterprise network reporting
490
+ pTiming = args.Time # Performance timing for operational optimization
491
+ verbose = args.loglevel # Logging verbosity for network infrastructure visibility
492
+
493
+ # Configure enterprise logging infrastructure for ENI operations audit trail
494
+ logging.basicConfig(level=verbose, format="[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
495
+ logging.getLogger("boto3").setLevel(logging.CRITICAL)
496
+ logging.getLogger("botocore").setLevel(logging.CRITICAL)
497
+ logging.getLogger("s3transfer").setLevel(logging.CRITICAL)
498
+ logging.getLogger("urllib3").setLevel(logging.CRITICAL)
499
+
500
+ # Initialize performance timing for operational optimization and SLA compliance
501
+ begin_time = time()
502
+ print()
503
+ print(f"Checking for Elastic Network Interfaces... ")
504
+ print()
505
+
506
+ logging.info(f"Profiles: {pProfiles}")
507
+
508
+ # Execute enterprise credential discovery and validation across organizational network infrastructure
509
+ CredentialList = get_all_credentials(
510
+ pProfiles, pTiming, pSkipProfiles, pSkipAccounts, pRootOnly, pAccounts, pRegionList
511
+ )
512
+
513
+ # Execute comprehensive multi-threaded ENI discovery with IP address filtering and security analysis
514
+ ENIsFound = check_accounts_for_enis(CredentialList, pIPaddressList, pPublicOnly)
515
+
516
+ # Generate comprehensive ENI inventory report with cost optimization and security insights
517
+ present_results(ENIsFound)
518
+
519
+ # Display performance timing metrics for operational optimization and SLA compliance
520
+ if pTiming:
521
+ print(f"{Fore.GREEN}This script took {time() - begin_time:.2f} seconds{Fore.RESET}")
522
+
523
+ # Display completion message for user confirmation and operational closure
524
+ print()
525
+ print("Thank you for using this script")
526
+ print()