├── .idea ├── .gitignore ├── IEEE NOMS 2024.iml ├── inspectionProfiles │ └── profiles_settings.xml ├── misc.xml ├── modules.xml └── vcs.xml ├── NOTICE ├── README.md ├── SECURITY.md ├── bubbln.py ├── bubbln_demo_video.mp4 ├── chatGPT_prompting.py ├── license.txt ├── parameter_input.py ├── playbook_executor.py ├── playbook_extractor.py ├── prompt_generator.py ├── requirements.txt ├── ssh_ip_addresses.txt └── utility.py /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/IEEE NOMS 2024.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2024 Olasupo Okunaiya 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer 8 | in the documentation and/or other materials provided with the distribution. 9 | 10 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this 11 | software without specific prior written permission. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 14 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 15 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 16 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 17 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 18 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![published](https://static.production.devnetcloud.com/codeexchange/assets/images/devnet-published.svg)](https://developer.cisco.com/codeexchange/github/repo/olasupo/bubbln_network-automation) [![Run in Cisco Cloud IDE](https://static.production.devnetcloud.com/codeexchange/assets/images/devnet-runable-icon.svg)](https://developer.cisco.com/codeexchange/devenv/olasupo/bubbln_network-automation/) 2 | 3 | # Bubbln: An AI-driven Network Automation 4 | 5 | In the world of network engineering, automation has completely transformed the way things work. But, before automation, setting up and managing networks was a tedious job filled with challenges. Engineers had to manually type out configurations, often doing the same tasks repeatedly on different devices. This led to mistakes and wasted time. 6 | 7 | Then came automation tools like Ansible, Chef, and Puppet, which changed everything. They made network management much easier and allowed for scalability. But there was still a problem: creating automation scripts required a lot of technical know-how and was prone to errors because it relied on human input. 8 | 9 | And that's why we built Bubbln. It's a game-changer in network engineering, integrating AI into Ansible to take automation to the next level. With Bubbln, we can automatically generate and execute playbooks with incredible accuracy, thereby improving automation efficiency and increasing network engineer’s productivity. It was developed using Python programming language and acts as a bridge between ChatGPT and network systems, making interactions seamless and deployments effortless. 10 | 11 | ## Current Capabilities 12 | 13 | **AI-Driven Playbook Generation for OSPF and EIGRP based networks:** Bubbln has been rigorously tested to leverage ChatGPT for generation of playbooks for networks based on OSPF and EIGRP networks, with a very high accuracy rate. 14 | 15 | **Auto-creation of Inventory files:** Users do not need to prepare the hosts file. Bubbln will auto-generate this file from input provided by the user. 16 | 17 | **Customizable Configurations:** Users can input specific router protocols (OSPF or EIGRP), interface configurations, and other network details to tailor the generated playbooks. 18 | 19 | **Documentation:** Bubbln automatically creates a report that contains the network configurations, prompts, and generated playbooks for easy reference in future. 20 | 21 | **No expertise required:** By auto-generation of the playbooks and inventory file, Bubbln has been able to eliminate a major hurdle to network automation – need for users to learn the automation tools e.g Ansible, Chef. 22 | 23 | **Improved Efficiency:** With AI automation, Bubbln speeds up the deployment of network configurations, reducing the time required for manual playbook creation, thereby increasing the productivity of network engineers. 24 | 25 | ## Getting Started 26 | 27 | There are two main approaches to installing Bubbln on your local machine. 28 | 29 | ### Docker Container 30 | 31 | Bubbln has been packaged using docker containers for easy distribution and usage. The following steps can be followed to deploy the Bubbln container on your local machine. 32 | 33 | 1. **Ensure docker is installed** on your local machine by entering the below command. This command works for windows and linux OS: 34 | 35 | ```bash 36 | docker --version 37 | ``` 38 | 39 | The version of docker would be displayed if it is installed. Otherwise, please follow the link below to install docker on your machine: 40 | 41 | - Windows: [Docker Desktop for Windows](https://docs.docker.com/desktop/install/) 42 | - Ubuntu: [Docker Engine for Ubuntu](https://docs.docker.com/engine/install/ubuntu/) 43 | - CentOS: [Docker Engine for CentOS](https://docs.docker.com/engine/install/centos/) 44 | - Debian: [Docker Engine for Debian](https://docs.docker.com/engine/install/debian/) 45 | - Fedora: [Docker Engine for Fedora](https://docs.docker.com/engine/install/fedora/) 46 | 47 | 2. **Download the docker image**: Create a directory for the project and download Bubbln image using the below command: 48 | 49 | ```bash 50 | docker pull olasupoo/bubbln:latest 51 | ``` 52 | 53 | 3. **Run the docker container** using the below command: 54 | 55 | ```bash 56 | docker run -it --network host --name bubbln-container olasupoo/bubbln 57 | ``` 58 | 4. **Install nano** 59 | 60 | ```bash 61 | apt update 62 | apt install nano 63 | ``` 64 | 65 | 5. **Update the ssh_ip_addresses.txt file**: Update the ssh_addresses.txt file with the SSH IP addresses of the routers you want to configure. Bubbln will utilize this information along with the login credentials (inputted at runtime) to automatically generate a hosts.yml file required by ansible for network configuration. To do this enter the below command to edit the file: 66 | 67 | ```bash 68 | nano ssh_ip_addresses.txt 69 | ``` 70 | 71 | 6. **Obtain an OpenAPI API Key**: You may follow this guide to sign up and obtain an API key: 72 | 73 | ```bash 74 | https://platform.openai.com/docs/quickstart?context=python 75 | ``` 76 | 77 | 7. **Utilizing a Virtualization machine of choice**, setup a network with the following basic configurations: 78 | 79 | * Enable SSH on each of the routers. 80 | * Configure IP addresses and enable only interfaces required for connectivity by Bubbln. 81 | * Configure static routes to enable Bubbln reach the routers on the network. 82 | * Ensure all the routers can be reached by ping and SSH from your host machine. 83 | 84 | 8. **Initialize Bubbln** by entering the below command: 85 | 86 | ```bash 87 | python3 bubbln.py 88 | ``` 89 | 90 | ### Github Repository Clone 91 | 92 | You can clone Bubbln’s GitHub repository by following the below steps: 93 | 94 | 1. **Prerequisites** 95 | 96 | * Bubbln works well with Python 3.10. You need to ensure python3.10 is installed on your local machine. This can be confirmed by entering the below command: 97 | 98 | ```bash 99 | python -V 100 | ``` 101 | 102 | * If it is not Installed, then the below command can be utilized to install python 3.10: 103 | 104 | ```bash 105 | sudo apt update 106 | sudo apt install python3.10 107 | ``` 108 | 109 | 2. **Build and Prepare the Project** 110 | * **Clone the Bubbln repository from GitHub**: To clone the repository, first verify you have git installed on your machine by issuing the following commands: 111 | 112 | ```bash 113 | git --version 114 | ``` 115 | 116 | If git is installed, the version number would be displayed, otherwise, you can issue the following commands to have git installed on your machine: 117 | 118 | ```bash 119 | sudo apt update 120 | sudo apt install git 121 | ``` 122 | 123 | * **Navigate or create a directory for the project** on your machine and issue the following commands to clone the Bubbln git repository: 124 | 125 | ```bash 126 | git clone https://github.com/olasupo/bubbln_network-automation.git 127 | ``` 128 | 129 | 3. **Create a Virtual Environment for the application** 130 | Firstly, confirm virtualenv is installed on your machine by inputting the following command: 131 | 132 | ```bash 133 | pip show virtualenv 134 | ``` 135 | 136 | If the output shows something similar to the below, then go to the next step to install virtualenv 137 | 138 | `` 139 | WARNING: Package(s) not found: env, virtual 140 | `` 141 | 142 | Issue the below command to install virtualenv: 143 | 144 | ```bash 145 | pip install virtualenv 146 | ``` 147 | 148 | 4. **Create a virtual environment for the project:** 149 | 150 | ```bash 151 | python3 -m venv chosen_name_of_your_virtual_env 152 | ``` 153 | 154 | 5. **Activate the virtual environment**: 155 | 156 | ```bash 157 | source venv/bin/activate 158 | ``` 159 | 160 | 6. **Install the dependencies** 161 | 162 | ```bash 163 | sudo apt install python3-dev && 164 | sudo apt install gcc && 165 | sudo apt install libssh-dev 166 | ``` 167 | 168 | You can then run the below command to install the necessary packages for the app. 169 | 170 | ```bash 171 | pip install -r requirements.txt 172 | ``` 173 | 174 | 7. **Update the ssh_ip_addresses.txt file**: Update the ssh_addresses.txt file with the SSH IP addresses of the routers you want to configure. Bubbln will utilize this information along with the login credentials (inputted at runtime) to automatically generate a hosts.yml file required by ansible for network configuration. 175 | 176 | 8. **Obtain an OpenAPI API Key**: You may follow this guide to sign up and obtain an API key 177 | 178 | - OpenAI Key: [OpenAI Key](https://platform.openai.com/docs/quickstart?context=python) 179 | 180 | 9. **Utilizing a Virtualization machine of choice**, setup a network with the following basic configurations: 181 | * Enable SSH on each of the routers. 182 | * Configure IP addresses and enable only interfaces required for connectivity by Bubbln 183 | * Configure static routes to enable Bubbln reach the routers on the network. 184 | * Ensure all the routers can be reached by ping and SSH from your host machine. 185 | 186 | 10. **Initialize Bubbln** 187 | * **While ensuring that python virtual environment** is activated as stated in step 5, run the below command to initialize Bubbln 188 | 189 | ```bash 190 | python3 bubbln.py 191 | ``` 192 | 193 | # How Bubbln Works 194 | 195 | Bubbln serves as an intermediary between ChatGPT and a network infrastructure, providing logic, control functions, and facilitating network automation. Its operation can be summarized as follows: 196 | 197 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/1e9a9ca5-e8c5-4ea0-a6c2-c78967457382) 198 | _Figure 1Bubbln architecture and interaction with a network of four routers._ 199 | 200 | ### Initialization: 201 | 202 | When Bubbln is initialized, it checks the “user_config.pkl” file to see if Bubbln has ever been initiated. This is indicated by the presence of a welcome message status in the file. If it exists, Bubbln jumps straight to request the user to input the OpenAI key. Otherwise, it displays a welcome message, and updates the user_config.pkl file accordingly. Upon successful input of the API key, the user is prompted for the SSH credentials of the routers. These parameters are then encrypted and saved in the user_config.pkl file. The SSH credential is later decrypted and parsed as input to dynamically generate a hosts.yml file at runtime. 203 | 204 | **Responsible Code Section:** bubbln.py: welcome_message_feature() 205 | 206 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/74fccfdc-5191-4b47-a02e-dc076ebe0ebb) 207 | _Figure 2 Bubbln's welcome message_. 208 | 209 | ### Parameter Input & Validation: 210 | 211 | In the parameter input stage, Bubbln first checks for the existence of a file called “router_configuration.pkl”. If it exists, the user is prompted to decide whether to load an existing configuration or input a new set of configurations. If the file is empty or non-existent, then users are prompted to input the configuration parameters for each router on the network. These parameters serve as variables that are combined with hardcoded instructions written in natural language to form the prompt sent to ChatGPT. Key parameters include: 212 | 213 | **Router Configurations:** 214 | - OSPF Area 215 | - OSPF Process ID 216 | - Number of networks to advertise (OSPF/EIGRP) 217 | - AS Number (EIGRP) 218 | - Interface names 219 | - IP Addresses (in CIDR format) 220 | 221 | This module also ensures that parameters are keyed in using the correct data type and format e.g. IP addresses are expected in CIDR format and OSPF Area should be of type integer. Upon completion of parameter input, all parameters are saved into a file called “router_configuration.pkl” upon validation of accuracy by the user. 222 | 223 | **Responsible Code Section**: parameter_input.py 224 | 225 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/03134054-876b-4cfb-b8c3-75f749420b9e) 226 | _Figure 3 Bubbln receiving Network Parameters._ 227 | 228 | Before generating the prompt, a summary of the inputted parameters is displayed for user validation. This step ensures accuracy and minimizes errors. Users are given the option to make corrections if any discrepancies are found. 229 | 230 | **Responsible Code Section**: parameter_input.py: validate_inputs() 231 | 232 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/8e02f95f-4f82-4cb2-91aa-fd6b4d2d4197) 233 | _Figure 4 Bubbln Awaiting Validation of Inputted Network Parameters._ 234 | 235 | ### Auto-Generation of Prompt: 236 | 237 | After validation of inputted parameters, Bubbln composes the prompt by combining the inputted parameters with a set of well-engineered hardcoded instructions written in natural language. 238 | 239 | **Responsible Code Section**: prompt_generator.py 240 | 241 | ### ChatGPT Prompting: 242 | 243 | The auto-composed prompt is then sent to ChatGPT utilizing gpt-4 chatCompletions model with a temperature parameter of 0.2 and maximum tokens of 1500. The following functions were designed into this process stage 244 | 245 | **Responsible Code Section**: chatGPT_prompting.py 246 | 247 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/df8b0096-e99c-4550-99fd-58e2577e8160) 248 | _Figure 5 ChatGPT prompting in progress_ 249 | 250 | ### Playbook Generation & Extraction: 251 | 252 | After ChatGPT processes the prompt from Bubbln, it provides a response which usually contains the generated playbook and explanatory notes. Bubbln then extracts the playbook from the explanatory notes by searching for “---” which usually connotes the start of playbooks and saves each generated playbook uniquely using the nomenclature Router_i_Playbook.yml. 253 | 254 | **Responsible Code Section**: playbook_extractor.py 255 | 256 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/ddec4b40-0d2c-4b6c-a2a4-ccbbbd97793b) 257 | _Figure 6 ChatGPT-generated playbook._ 258 | 259 | ### Playbook Execution: 260 | Bubbln loads the saved “Router_i_Playbook.yml” playbook and dynamically generates the hosts.yml file and parses them to the python library ansible_runner for further execution on the configured network. Bubbln generates the hosts.yml file at run time by using the pre-inputted SSH credentials in user_config.pkl file - and decrypts them, as well as IP addresses from the ssh_ip_addresses.txt file, as inputs 261 | 262 | **Responsible Code Section**: playbook_execution.py 263 | 264 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/e11fef3a-d1d3-49be-8c9d-7458eac55098) 265 | _Figure 7 Playbook execution in progress_ 266 | 267 | ### Sample result of Executed Playbook 268 | 269 | Upon successful execution of all playbooks, a query of the routing table on router 4 indicates that router 4 could reach all the prefixes on the network. 270 | 271 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/7d4b3c55-7e8c-41a7-810b-5054aa3106cb) 272 | _Figure 8 Output of 'sh ip route' executed on R1_ 273 | 274 | ### File Management and Handling 275 | 276 | Throughout the execution process, Bubbln manages the creation, saving, and loading of various files to streamline the network automation process. 277 | * **user_config.pkl**: This dictionary file dynamically created at run time is used to store encrypted API keys, SSH credentials and initial welcome message information. 278 | * **router_configuration.pkl**: It is auto created by Bubbln and used to store network configuration parameters for easy loading during subsequent sessions. 279 | * **hosts.yml**: This is a runtime autogenerated file that contains inventory of the network devices. It is auto deleted after the program runs. 280 | * **network_configuration_report.pdf**: This auto-generated report by Bubbln is a documentation of all the routers configured their parameters, generated playbooks, and prompt for each execution of the Bubbln application. It is created after a successful execution of playbooks and network testing and is meant for auditing and documentation purposes. 281 | * **Router_i_Playbook.yml**: After extraction of generated playbooks from ChatGPT’s raw response, Bubbln automatically saves a copy of the generated playbook using unique names for each playbook. 282 | 283 | ![image](https://github.com/olasupo/naijacontest/assets/4561196/003ca819-e051-4010-801c-71b35996da2f) 284 | _Figure 9 File structure after successful deployment of a four-router network_ 285 | 286 | ### Providing Feedback 287 | 288 | We are glad to hear your thoughts and suggestions. Kindly do this through the discussion section of our GitHub - https://github.com/olasupo/bubbln_network-automation/discussions/1#discussion-6487475 289 | 290 | We can also be reached on: 291 | Olasupo Okunaiya – [olasupo.o@gmail.com](mailto:olasupo.o@gmail.com) 292 | 293 | 294 | 295 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | This is Bubbln's version and full support is provided where required. 6 | 7 | | Version | Supported | 8 | | ------- | ------------------ | 9 | | 1.0.0 | :white_check_mark: | 10 | 11 | 12 | ## Reporting a Vulnerability 13 | 14 | In the situation where security vulnerabilities are noted, please do not hesitate to alert us about this on olasupo.o@gmail.com 15 | 16 | Thank you for your support and contribution. 17 | -------------------------------------------------------------------------------- /bubbln.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | from chatGPT_prompting import validate_openai_key 4 | from parameter_input import parameter_input_function 5 | import openai 6 | import time 7 | from colorama import init 8 | from cryptography.fernet import Fernet 9 | import getpass 10 | from utility import animate_message, print_line, load_user_config, save_user_config, encrypt_key, decrypt_key 11 | 12 | # Initialize colorama 13 | init() 14 | 15 | os.system('clear') 16 | 17 | # Get the path of the current script or module 18 | current_path = os.path.dirname(os.path.abspath(__file__)) 19 | 20 | # Create a unique folder for each program execution based on timestamp 21 | timestamp = time.strftime('%Y%m%d%H%M%S') 22 | execution_folder = os.path.join(current_path, f"execution_{timestamp}") 23 | os.makedirs(execution_folder, exist_ok=True) 24 | 25 | # Move to the execution folder 26 | os.chdir(execution_folder) 27 | 28 | user_config = load_user_config() 29 | 30 | def welcome_message_feature(): 31 | # Welcome message animation and logic to decide if it should be displayed, i.e display logic message only at 32 | # first-time execution of the program. Do not display it afterwards. 33 | welcome_message = ( 34 | "\n\nWelcome. My name is Bubbln. I was developed to aid a research on the potentials of automating " 35 | "a Network using Large Language Models (Specifically, ChatGPT). This research is being undertaken " 36 | "by Olasupo Okunaiya as part of his Masters degree project on the CMP7200 course in the School of " 37 | "Computing and Digital Technology at Birmingham City University. The project is being supervised " 38 | "by Associate Professor Ron Austin (https://www.linkedin.com/in/ronaustin1]) during the period " 39 | "June 2023 to 28th September, 2023. The research will be written up and submitted for assessment " 40 | "in September, 2023 and may be used for external publication for a further 12 months. Thank you. " 41 | "\n\n- Olasupo Okunaiya (linkedin.com/in/olasupoo)\n\n") 42 | 43 | existing_config_file = os.path.join(current_path, "user_config.pkl") 44 | 45 | # Load or create user configuration 46 | if os.path.exists(existing_config_file): 47 | with open(existing_config_file, "rb") as file: 48 | user_config = pickle.load(file) 49 | show_full_message = user_config.get("show_full_message", False) 50 | else: 51 | user_config = {} 52 | show_full_message = False 53 | 54 | # Display welcome message if required 55 | if not show_full_message: 56 | print_line() 57 | print("\n\t\t----------THIS IS A ONE-TIME WELCOME MESSAGE----------\n") 58 | animate_message(welcome_message) 59 | animate_message( 60 | "\nThis is an experiment to assess the potential of using chatGPT to generate ansible playbooks in network " 61 | "automation\n\n") 62 | 63 | print_line() 64 | user_config["show_full_message"] = True 65 | with open(existing_config_file, "wb") as file: 66 | pickle.dump(user_config, file) 67 | 68 | # This is the main function of the program responsible for taking user inputs, forming prompts and calling other 69 | # functions 70 | def main(): 71 | welcome_message_feature() 72 | elapsed_time = 0 73 | program_start_time = time.time() # Useful to track program execution time 74 | 75 | # Checks if there is an existing configuration file. If so, then that is loaded 76 | config_file = os.path.join(current_path, "user_config.pkl") 77 | if os.path.exists(config_file): 78 | with open(config_file, "rb") as file: 79 | user_config = pickle.load(file) 80 | else: 81 | user_config = {} 82 | openai_key = user_config.get("openai_key") 83 | if not openai_key: 84 | print("\n\n\t\t==========This is a One-time Requirement==========\n\n") 85 | while True: 86 | openai_key = getpass.getpass("Please enter your OpenAI API Key: ") 87 | if validate_openai_key(openai_key): 88 | break 89 | else: 90 | print("Invalid API key! You can obtain a key from your OpenAI account.") 91 | 92 | # Generate or load Fernet key 93 | fernet_key = user_config.get("fernet_key") 94 | if fernet_key: 95 | cipher_suite = Fernet(fernet_key) 96 | else: 97 | fernet_key = Fernet.generate_key() 98 | cipher_suite = Fernet(fernet_key) 99 | user_config["fernet_key"] = fernet_key 100 | 101 | encrypted_openai_key = encrypt_key(openai_key, cipher_suite) 102 | user_config["openai_key"] = encrypted_openai_key 103 | save_user_config(user_config) 104 | else: 105 | # Load Fernet key 106 | fernet_key = user_config.get("fernet_key") 107 | cipher_suite = Fernet(fernet_key) 108 | openai_key = decrypt_key(openai_key, cipher_suite) 109 | 110 | openai.api_key = openai_key 111 | 112 | # Function to read SSH IP addresses from a file 113 | def read_ssh_ips(filename): 114 | with open(filename, 'r') as file: 115 | ssh_ips = [line.strip() for line in file.readlines() if line.strip()] 116 | return ssh_ips 117 | 118 | # Read SSH IP addresses from a file 119 | ssh_file = os.path.join(current_path, 'ssh_ip_addresses.txt') 120 | ssh_ips = read_ssh_ips(ssh_file) 121 | 122 | # Initialize an empty dictionary to store router details 123 | router_details = {} 124 | 125 | # Assign SSH IP addresses to routers 126 | for i in range(len(ssh_ips)): 127 | router_details[f"R{i + 1}"] = {"ansible_host": ssh_ips[i]} 128 | 129 | # Load or create fernet key 130 | fernet_key = user_config.get("fernet_key") 131 | if fernet_key: 132 | cipher_suite = Fernet(fernet_key) 133 | else: 134 | key = Fernet.generate_key() 135 | cipher_suite = Fernet(key) 136 | user_config["fernet_key"] = key 137 | 138 | # Prompt user for username and password 139 | while True: 140 | try: 141 | username = input("Please input the SSH username: ") 142 | if not username: # Check if username is empty 143 | print("Username cannot be empty. Please try again.") 144 | continue 145 | password = getpass.getpass("Please input the SSH password: ") 146 | if not password: # Check if password is empty 147 | print("Password cannot be empty. Please try again.") 148 | continue 149 | # Encrypt username and password 150 | 151 | encrypted_username = cipher_suite.encrypt(username.encode()) 152 | encrypted_password = cipher_suite.encrypt(password.encode()) 153 | user_config["ansible_user"] = encrypted_username 154 | user_config["ansible_ssh_pass"] = encrypted_password 155 | 156 | # Update the vars section of the hosts.yml file with encrypted credentials 157 | host_file = os.path.join(current_path, '.hosts.yml') 158 | 159 | with open(host_file, 'w') as hosts_file: 160 | # Write router details 161 | hosts_file.write("routers:\n hosts:\n") 162 | for router, details in router_details.items(): 163 | hosts_file.write(f" {router}:\n") 164 | hosts_file.write(f" ansible_host: {details['ansible_host']}\n") 165 | hosts_file.write(f" vars:\n") 166 | hosts_file.write(f" ansible_connection: network_cli\n") 167 | hosts_file.write(f" ansible_network_os: ios\n") 168 | hosts_file.write(f" ansible_action_warnings: False\n") 169 | hosts_file.write(f" ansible_user: {encrypted_username}\n") 170 | hosts_file.write(f" ansible_ssh_pass: {encrypted_password}\n") 171 | 172 | # Successfully got username and password, break out of loop 173 | break 174 | 175 | except Exception as e: 176 | print("An error occurred while processing your input:", e) 177 | print("Please try again.") 178 | 179 | # The inventory file is loaded 180 | inventory_file = user_config.get("inventory_file") 181 | if not inventory_file: 182 | inventory_file = '.hosts.yml' 183 | user_config["inventory_file"] = inventory_file 184 | 185 | with open(config_file, "wb") as file: 186 | pickle.dump(user_config, file) 187 | 188 | openai.api_key = openai_key 189 | model_name = "gpt-4" 190 | 191 | #Call function to begin inputting parameters 192 | parameter_input_function(execution_folder, model_name, elapsed_time, program_start_time) 193 | 194 | if __name__ == "__main__": 195 | 196 | main() 197 | # Delete the hidden hosts.yml file after the program ends 198 | os.remove(os.path.join(current_path, '.hosts.yml')) -------------------------------------------------------------------------------- /bubbln_demo_video.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/olasupo/bubbln_network-automation/f88f8ff9c5b7af2bf279af8c916abbc059277a67/bubbln_demo_video.mp4 -------------------------------------------------------------------------------- /chatGPT_prompting.py: -------------------------------------------------------------------------------- 1 | #import libraries 2 | import openai 3 | import time 4 | import threading 5 | import traceback 6 | import openai 7 | from openai.error import AuthenticationError 8 | from playbook_extractor import playbook_extractor_function 9 | 10 | 11 | # Function to validate the provided OpenAI API key 12 | def validate_openai_key(api_key): 13 | # Set the OpenAI API key 14 | openai.api_key = api_key 15 | # Define a test message to check if the API key is correct 16 | messages = [ 17 | {"role": "system", "content": "Test if the API key is correct."}, 18 | ] 19 | success = False 20 | try: 21 | # Test the API key by sending a chat completion request 22 | openai.ChatCompletion.create(model="gpt-4", messages=messages, max_tokens=5) 23 | success = True 24 | except AuthenticationError as e: 25 | # Handle authentication error if the API key is invalid 26 | print("Invalid API key:", e) 27 | except Exception as e: 28 | # Handle other unexpected errors 29 | print("An unexpected error occurred:", e) 30 | return success 31 | 32 | 33 | # Function responsible for prompting ChatGPT to generate playbooks 34 | def chatGPT_prompter(prompt, model_name, conversation_history): 35 | # Define an inner function to make the API call asynchronously 36 | def api_call(): 37 | nonlocal response 38 | try: 39 | # Create messages including the conversation history and user prompt 40 | messages = [ 41 | {"role": "system", "content": "You are a network engineer trying to automate a network."}, 42 | ] 43 | messages.extend(conversation_history) 44 | messages.append({"role": "user", "content": prompt}) 45 | 46 | # Call ChatGPT to generate a response 47 | response = openai.ChatCompletion.create( 48 | model=model_name, 49 | messages=messages, 50 | max_tokens=1500, 51 | ) 52 | except Exception as e: 53 | # Handle errors during playbook generation 54 | print("An error occurred during playbook generation:", e) 55 | traceback.print_exc() 56 | response = None 57 | 58 | response = None 59 | 60 | # Display a waiting message while generating the playbook 61 | print("\n\nPlease wait while a playbook is being generated", end='', flush=True) 62 | 63 | # Start a thread to make the API call asynchronously 64 | animation_thread = threading.Thread(target=api_call) 65 | animation_thread.start() 66 | 67 | # Display an animation while waiting for the response 68 | while animation_thread.is_alive(): 69 | for _ in range(5): 70 | time.sleep(1.0) 71 | print('.', end='', flush=True) 72 | print('\b\b\b \b\b\b', end='', flush=True) # Erase the dots 73 | 74 | # Wait for the animation thread to finish 75 | animation_thread.join() 76 | 77 | # Extract relevant information from the response 78 | text_before_code, code, text_after_code, conversation_history = playbook_extractor_function(response, 79 | conversation_history) 80 | return text_before_code, code, text_after_code, conversation_history 81 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /parameter_input.py: -------------------------------------------------------------------------------- 1 | import readline 2 | import os 3 | import time 4 | from utility import PDF, validate_cidr_network, convert_cidr_network, convert_cidr_network_wildcard, animate_message, \ 5 | get_positive_integer_input, save_configuration, load_configuration, print_summary 6 | from prompt_generator import prompt_generator_function 7 | 8 | # Function to get router parameters from the user 9 | def parameter_input_function(execution_folder, model_name, elapsed_time, program_start_time): 10 | while True: 11 | animate_message("\n\n\t\t\tLet's Begin Setup of Your Network") # Display welcome message 12 | print("\n\t\t\t===================================\n\n") 13 | input_param_start_time = time.time() # Record start time for input 14 | interface_configurations = load_configuration() # Load existing configurations if available 15 | if interface_configurations is None: # If no configurations found 16 | interface_configurations = [] 17 | router_count = get_positive_integer_input("How many routers do you want to configure: ") # Get number of routers 18 | for i in range(router_count): 19 | print(f"\n\nWe will now take the configuration parameters for Router {i + 1} : \n\n") 20 | router_interface_count = get_positive_integer_input(f"How many interfaces are to be configured?: ") # Get number of interfaces 21 | protocol_count = get_positive_integer_input(f"And how many protocols: ") # Get number of protocols 22 | interface_configurations.append( 23 | get_router_interface_configuration(protocol_count, router_interface_count)) # Get router interface configurations 24 | save_configuration(interface_configurations) # Save configurations 25 | else: # If existing configurations found 26 | response = input("\nWe found a previous configuration. Would you like to load it? (y/n): ") 27 | if response.lower() == "n": 28 | interface_configurations = [] 29 | router_count = get_positive_integer_input("\nHow many routers do you want to configure: ") 30 | for i in range(router_count): 31 | print(f"\n\nWe will now take the configuration parameters for Router {i + 1} : \n\n") 32 | router_interface_count = get_positive_integer_input(f"How many interfaces are to be configured?: ") 33 | protocol_count = get_positive_integer_input(f"...And how many protocols?: ") 34 | interface_configurations.append( 35 | get_router_interface_configuration(protocol_count, router_interface_count)) 36 | save_configuration(interface_configurations) 37 | os.system('clear') # Clear screen 38 | print("\n\n**********Please review and validate your inputs**********") 39 | if validate_inputs(interface_configurations): # Validate user inputs 40 | input_param_end_time = time.time() 41 | input_param_duration = input_param_end_time - input_param_start_time 42 | # Create a PDF object 43 | pdf = PDF() 44 | pdf.set_auto_page_break(auto=True, margin=15) 45 | # Add a chapter for router configurations 46 | pdf.add_page() 47 | pdf.chapter_title("Router Configurations") 48 | pdf.chapter_body("Explanation and details about router configurations.") 49 | generate_playbooks_start_time = time.time() # Start time for generating playbooks 50 | # Call function to generate prompts and save them 51 | generate_playbooks_duration, elapsed_time = prompt_generator_function(pdf, interface_configurations, 52 | execution_folder, model_name, 53 | generate_playbooks_start_time) 54 | # Save the PDF document 55 | pdf.output(os.path.join(execution_folder, "network_configuration_report.pdf"), "F") 56 | 57 | # Print summary 58 | execute_playbooks_duration = elapsed_time 59 | summary_duration = time.time() - program_start_time 60 | print_summary(input_param_duration, generate_playbooks_duration, execute_playbooks_duration, 61 | summary_duration) 62 | experiment_summary_file = f"experiment_summary_{time.strftime('%Y%m%d%H%M%S')}.txt" 63 | with open(experiment_summary_file, "w") as file: 64 | file.write(f"Input Router Duration: {input_param_duration}\n") 65 | file.write(f"Generate Playbooks Duration: {generate_playbooks_duration}\n") 66 | file.write(f"Execute Playbooks Duration: {execute_playbooks_duration}\n") 67 | file.write(f"Total Summary Duration: {summary_duration}\n") 68 | 69 | print() 70 | break 71 | else: 72 | print("\n\nPlease update your inputs:\n") 73 | 74 | # Function to validate user inputs 75 | def validate_inputs(interface_configurations): 76 | for i, router_config in enumerate(interface_configurations): 77 | print(f"Router {i + 1}:") 78 | for protocol_config in router_config: 79 | if 'protocol' in protocol_config: 80 | protocol = protocol_config['protocol'] 81 | print(f"\tProtocol: {protocol}") 82 | if protocol.lower() == 'ospf': 83 | area = protocol_config['area'] 84 | process_id = protocol_config['process_id'] 85 | num_networks = len(protocol_config['networks']) 86 | print(f"\t\tOSPF Area: {area}") 87 | print(f"\t\tOSPF Process ID: {process_id}") 88 | print(f"\t\tNumber of networks to advertise: {num_networks}") 89 | for j, network in enumerate(protocol_config['networks']): 90 | print(f"\t\tNetwork {j + 1}: {network}") 91 | elif protocol.lower() == 'eigrp': 92 | as_number = protocol_config['as_number'] 93 | num_networks = len(protocol_config['networks']) 94 | print(f"\t\tEIGRP AS Number: {as_number}") 95 | print(f"\t\tNumber of networks to advertise: {num_networks}") 96 | for j, network in enumerate(protocol_config['networks']): 97 | print(f"\t\tNetwork {j + 1}: {network}") 98 | for interface_config in router_config: 99 | if 'interface' in interface_config and 'ip' in interface_config: 100 | interface_name = interface_config['interface'] 101 | ip_address = interface_config['ip'] 102 | print(f"\tInterface: {interface_name}") 103 | print(f"\tIP Address: {ip_address}") 104 | print() 105 | 106 | while True: 107 | confirm = input("Do you want to proceed with the above inputs? (y/n): ") 108 | if confirm.lower() == 'y': 109 | return True 110 | elif confirm.lower() == 'n': 111 | while True: 112 | index_to_correct = input( 113 | "\n\nOn which router do you want to make corrections - Enter '1' for Router1 etc: ") 114 | try: 115 | index = int(index_to_correct) - 1 116 | if 0 <= index < len(interface_configurations): 117 | router_config = interface_configurations[index] 118 | protocol_count = len([config for config in router_config if 'protocol' in config]) 119 | interface_count = len( 120 | [config for config in router_config if 'interface' in config and 'ip' in config]) 121 | print(f"\nCorrecting inputs for Router {index + 1}...\n") 122 | interface_configurations[index] = get_router_interface_configuration(protocol_count, 123 | interface_count) 124 | os.system('clear') 125 | break 126 | else: 127 | print( 128 | f"Invalid input! Please enter a valid router index between 1 and {len(interface_configurations)}.") 129 | except ValueError: 130 | print("Invalid input! Please enter a valid router index number.") 131 | print("\n\nPlease review and validate your corrected inputs:") 132 | return validate_inputs(interface_configurations) 133 | else: 134 | print("Invalid input! Please enter 'y' or 'n'.") 135 | 136 | # Function to get router interface configuration from user 137 | def get_router_interface_configuration(protocol_count, interface_count): 138 | router_interface_config = [] 139 | history = [] 140 | 141 | def input_with_history(prompt): 142 | line = input(prompt) 143 | if line: 144 | history.append(line) 145 | return line 146 | 147 | def handle_navigation(current_index): 148 | if current_index < 0: 149 | current_index = 0 150 | elif current_index >= len(history): 151 | current_index = len(history) - 1 152 | readline.set_history_length(len(history)) 153 | readline.set_history_item(current_index, history[current_index]) 154 | return history[current_index], current_index 155 | 156 | def navigate_inputs(): 157 | current_index = len(history) 158 | while True: 159 | key = input_with_history("") 160 | if key == "\x1b[A": # Up arrow key 161 | current_index -= 1 162 | line, current_index = handle_navigation(current_index) 163 | print("\r" + " " * len(line) + "\r" + line) 164 | elif key == "\x1b[B": # Down arrow key 165 | current_index += 1 166 | line, current_index = handle_navigation(current_index) 167 | print("\r" + " " * len(line) + "\r" + line) 168 | else: 169 | break 170 | 171 | def get_positive_integer_input(prompt): 172 | while True: 173 | try: 174 | value = int(input_with_history(prompt)) 175 | if value > 0: 176 | return value 177 | else: 178 | animate_message("Sorry, that's an invalid input! Please enter a positive integer.\n") 179 | except ValueError: 180 | animate_message("Sorry, that's an invalid input! Please enter a positive integer.\n") 181 | 182 | # Input router configurations based on protocol and interface count 183 | for _ in range(protocol_count): 184 | while True: 185 | protocol = input_with_history( 186 | "Please input the network protocol to configure (Choice: OSPF, EIGRP): ").lower() 187 | if protocol.lower() in ['ospf', 'eigrp']: 188 | break 189 | else: 190 | animate_message("Sorry, that's an invalid input! Please enter either 'OSPF' or 'EIGRP'\n") 191 | 192 | if protocol.lower() == 'ospf': 193 | area = get_positive_integer_input("Enter the OSPF Area: ") 194 | process_id = get_positive_integer_input("Enter the OSPF Process ID: ") 195 | num_networks = get_positive_integer_input("Enter the number of networks to advertise: ") 196 | networks = [] 197 | print("Please input the networks to advertise using the Format: x.x.x.x/y ") 198 | for k in range(num_networks): 199 | while True: 200 | network = input_with_history(f"Network {k + 1}: ") 201 | if validate_cidr_network(network): 202 | break 203 | else: 204 | animate_message( 205 | "That's an invalid input! Please enter a valid CIDR network in the format x.x.x.x/y.") 206 | network_address = convert_cidr_network_wildcard(network) 207 | networks.append(network_address) 208 | router_interface_config.append( 209 | {'protocol': protocol, 'area': area, 'process_id': process_id, 'networks': networks}) 210 | elif protocol.lower() == 'eigrp': 211 | as_number = get_positive_integer_input("Enter the AS Number: ") 212 | num_networks = get_positive_integer_input("Enter the number of networks to advertise: ") 213 | networks = [] 214 | print("Please input the networks to advertise using the Format: x.x.x.x/y ") 215 | for k in range(num_networks): 216 | while True: 217 | network = input_with_history(f"Network {k + 1}: ") 218 | if validate_cidr_network(network): 219 | break 220 | else: 221 | animate_message( 222 | "Sorry, that's an invalid input! Please enter a valid CIDR network in the format " 223 | "x.x.x.x/y.\n") 224 | network_address = convert_cidr_network_wildcard(network) 225 | networks.append(network_address) 226 | 227 | router_interface_config.append({'protocol': protocol, 'as_number': as_number, 'networks': networks}) 228 | 229 | for _ in range(interface_count): 230 | # Input interface configurations with IP addresses 231 | interface = input_with_history("Enter the interface name: ").lower() 232 | while True: 233 | ip_network = input_with_history("Enter the IP address and network (Format: x.x.x.x/y): ") 234 | if validate_cidr_network(ip_network): 235 | break 236 | else: 237 | animate_message( 238 | "Sorry, that's an invalid input! Please enter a valid CIDR network in the format x.x.x.x/y.\n") 239 | ip_address = convert_cidr_network(ip_network) 240 | router_interface_config.append({'interface': interface, 'ip': ip_address}) 241 | 242 | navigate_inputs() # Enable input navigation 243 | 244 | return router_interface_config 245 | -------------------------------------------------------------------------------- /playbook_executor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | from ansible_runner import run 4 | from tenacity import retry, stop_after_attempt, wait_random_exponential 5 | from cryptography.fernet import Fernet 6 | from utility import print_blue, print_colored_code 7 | 8 | # Get the path of the current script or module 9 | current_path = os.path.dirname(os.path.abspath(__file__)) 10 | 11 | 12 | # This is the function to execute the generated playbooks which were dynamically stored. 13 | @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(10)) 14 | def execute_playbook(playbook_file, model_name, router_number, text_before_code, text_after_code, conversation_history): 15 | try: 16 | while True: 17 | with open(playbook_file, "r") as file: 18 | playbook_content = file.read() 19 | 20 | print(f"\n\nGenerated Playbook for Router {router_number} has been Saved To: {playbook_file}\n") 21 | print_blue(text_before_code) 22 | print() 23 | print_colored_code(playbook_content) 24 | print() 25 | print_blue(text_after_code) 26 | print() 27 | 28 | # Dynamically decrypt ansible_user and ansible_ssh_pass before running the playbook 29 | decrypt_ansible_credentials() 30 | 31 | r = run( 32 | playbook=playbook_file, 33 | inventory=os.path.join(current_path, '.hosts.yml'), 34 | private_data_dir=current_path, 35 | quiet=False 36 | ) 37 | print() 38 | return playbook_content 39 | 40 | except Exception as e: 41 | print("Error executing Ansible playbook:", e) 42 | 43 | 44 | # Function to decrypt ansible credentials 45 | def decrypt_ansible_credentials(): 46 | try: 47 | # Read the encrypted credentials from the hosts.yml file 48 | with open(os.path.join(current_path, '.hosts.yml'), 'r') as hosts_file: 49 | encrypted_hosts_content = hosts_file.read() 50 | 51 | # Load user_config from pickle file 52 | with open(os.path.join(current_path, "user_config.pkl"), "rb") as decrypt_source: 53 | user_config = pickle.load(decrypt_source) 54 | 55 | # Load fernet key from user_config 56 | fernet_key = user_config.get("fernet_key") 57 | 58 | if fernet_key: 59 | cipher_suite = Fernet(fernet_key) 60 | 61 | # Decode and decrypt the credentials 62 | decrypted_username = cipher_suite.decrypt(user_config["ansible_user"]).decode('utf-8') 63 | decrypted_password = cipher_suite.decrypt(user_config["ansible_ssh_pass"]).decode('utf-8') 64 | else: 65 | print("Fernet key not found in user_config!") 66 | return 67 | 68 | decrypted_hosts_content = encrypted_hosts_content.replace(f"b'{user_config['ansible_user'].decode()}'", 69 | decrypted_username 70 | ).replace( 71 | f"b'{user_config['ansible_ssh_pass'].decode()}'", decrypted_password) 72 | 73 | # Write the decrypted content back to the hosts.yml file 74 | with open(os.path.join(current_path, '.hosts.yml'), 'w') as hosts_file: 75 | hosts_file.write(decrypted_hosts_content) 76 | 77 | except Exception as e: 78 | print("Error decrypting ansible credentials:", e) 79 | 80 | -------------------------------------------------------------------------------- /playbook_extractor.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | 3 | # Function to extract playbook from raw response 4 | def playbook_extractor_function(response, conversation_history): 5 | if response is None: # If response is None, playbook generation failed 6 | print("Playbook generation failed.") 7 | return "", "", "", conversation_history 8 | 9 | try: 10 | full_response = response['choices'][0]['message']['content'] # Get full response from API 11 | 12 | # Append assistant's response to conversation history 13 | conversation_history.append({'role': 'assistant', 'content': full_response}) 14 | 15 | # Find start and end index of code block 16 | code_start_index = full_response.find('---') 17 | code_end_index = full_response.find('...', code_start_index) 18 | 19 | if code_start_index != -1 and code_end_index != -1: # If code block found 20 | # Extract text before code block, code block, and text after code block 21 | text_before_code = full_response[:code_start_index] 22 | code = full_response[code_start_index:code_end_index + 3] # Include '---' and '...' in the code 23 | text_after_code = full_response[code_end_index + 3:] 24 | else: # If code block not found 25 | text_before_code = full_response 26 | code = "" 27 | text_after_code = "" 28 | 29 | return text_before_code.strip(), code.strip(), text_after_code.strip(), conversation_history 30 | 31 | except Exception as e: # Handle exceptions 32 | print("An error occurred while processing the generated playbook:", e) 33 | traceback.print_exc() # Print traceback for debugging 34 | return "", "", "", conversation_history 35 | -------------------------------------------------------------------------------- /prompt_generator.py: -------------------------------------------------------------------------------- 1 | from playbook_executor import execute_playbook 2 | import os 3 | from chatGPT_prompting import chatGPT_prompter 4 | import time 5 | 6 | 7 | # Function to generate prompts and execute playbooks for each router configuration 8 | def prompt_generator_function(pdf, interface_configurations, execution_folder, model_name, 9 | generate_playbooks_start_time): 10 | # Iterate over each router configuration 11 | for i, router_config in enumerate(interface_configurations): 12 | conversation_history = [] # Initialize conversation history for the current router 13 | 14 | # Add a subheading for the current router in the PDF report 15 | pdf.set_font('Arial', 'B', 12) 16 | pdf.cell(0, 10, f"Router {i + 1} Configurations", 0, 1, 'L') 17 | pdf.ln(5) 18 | 19 | # Define the initial prompt for generating the playbook 20 | prompt = ("Requirements: Strictly adhere to the following explicitly stated requirements; Write a " 21 | "simple Ansible playbook with separate tasks for each protocol and interface configurations " 22 | "with the following details;") 23 | 24 | prompt += f" hosts: R{i + 1}" # Add host information to the prompt 25 | 26 | prompt += " Do not worry about the inventory file;" # Additional requirements 27 | # Add more requirements to the prompt 28 | prompt += " Ensure each Task is named;" 29 | prompt += " Never provide explanations for the generated playbook;" 30 | prompt += " Do not use variables and templates to generate the playbooks;" 31 | prompt += ("Ensure all generated playbooks adhere to yaml's rule of always starting a playbook with " 32 | "`---` and ending the playbook with a new line containing `...`;") 33 | prompt += " Always use ios_config module and ensure unsupported parameters are not generated;;" 34 | prompt += " Use `parents` argument to implement stanzas;" 35 | prompt += ("when configuring interfaces, ensure you generate codes for only provided interfaces and " 36 | "always implement 'No Shutdown' for each interface;") 37 | prompt += ("when configuring routing protocols, ensure you generate codes for only provided protocols " 38 | "and that the protocol is initialized only under the parents argument using the format " 39 | "`router protocol-type xx`. Also, DO NOT configure router id;") 40 | prompt += " set `replace` argument to block. `replace` argument should always be child to `ios_config`;" 41 | 42 | redistribute_required = False # Flag to track if redistribution is required 43 | 44 | # Iterate over protocol configurations for the current router 45 | for protocol_config in router_config: 46 | if 'protocol' in protocol_config: 47 | protocol = protocol_config['protocol'] 48 | prompt += f" Protocol: {protocol}" # Add protocol information to the prompt 49 | if protocol.lower() == 'ospf': 50 | # Extract OSPF configuration details 51 | area = protocol_config['area'] 52 | process_id = protocol_config['process_id'] 53 | num_networks = len(protocol_config['networks']) 54 | # Add OSPF configuration details to the prompt 55 | prompt += f" OSPF Area: {area}, Process ID: {process_id}, Number of networks to advertise: {num_networks}" 56 | # Add network information to the PDF report 57 | for j, network in enumerate(protocol_config['networks']): 58 | pdf.set_font('Arial', '', 12) 59 | pdf.cell(0, 10, f"network: {network}", 0, 1, 'L') 60 | pdf.ln(5) 61 | prompt += f" network{j + 1}: {network}" 62 | elif protocol.lower() == 'eigrp': 63 | # Extract EIGRP configuration details 64 | as_number = protocol_config['as_number'] 65 | num_networks = len(protocol_config['networks']) 66 | # Add EIGRP configuration details to the prompt 67 | prompt += f" EIGRP AS Number: {as_number}, Number of networks to advertise: {num_networks}" 68 | # Add network information to the PDF report 69 | for j, network in enumerate(protocol_config['networks']): 70 | pdf.set_font('Arial', '', 12) 71 | pdf.cell(0, 10, f"network: {network}", 0, 1, 'L') 72 | pdf.ln(5) 73 | prompt += f" network{j + 1}: {network}" 74 | 75 | # Check if both EIGRP and OSPF are configured 76 | if protocol.lower() == 'eigrp': 77 | for other_protocol_config in router_config: 78 | if 'protocol' in other_protocol_config and other_protocol_config['protocol'].lower() == 'ospf': 79 | redistribute_required = True 80 | 81 | # Add redistribution tasks to the prompt if required 82 | if redistribute_required: 83 | prompt += (f"; Using dedicated tasks, Please redistribute the routing protocols using " 84 | f"'redistribute ospf {process_id} metric 1000 33 255 1 1500' for redistributing OSPF " 85 | f"into EIGRP and 'redistribute eigrp {as_number} subnets' for redistributing EIGRP " 86 | f"into OSPF;") 87 | prompt += ("The redistribution tasks, should be generated after the routing protocol configuration " 88 | "tasks have been generated;") 89 | 90 | # Add interface configurations to the prompt and PDF report 91 | for interface_config in router_config: 92 | if 'interface' in interface_config and 'ip' in interface_config: 93 | interface_name = interface_config['interface'] 94 | ip_address = interface_config['ip'] 95 | pdf.set_font('Arial', '', 12) 96 | pdf.cell(0, 10, f"Interface: {interface_name}, IP: {ip_address}", 0, 1, 'L') 97 | pdf.ln(5) 98 | prompt += f" Interface: {interface_name}, IP: {ip_address}" 99 | 100 | prompt = prompt.rstrip(";") # Remove the trailing semicolon 101 | 102 | # Add a chapter for the prompt used to generate each playbook in the PDF report 103 | pdf.add_page() 104 | pdf.chapter_title(f"Prompt for Router {i + 1}") 105 | pdf.chapter_body(prompt) 106 | 107 | # Generate playbook using ChatGPT based on the prompt 108 | text_before_code, playbook, text_after_code, conversation_history = chatGPT_prompter(prompt, model_name, 109 | conversation_history) 110 | generate_playbooks_duration = time.time() - generate_playbooks_start_time 111 | 112 | # Add a chapter for the generated playbook in the PDF report 113 | pdf.add_page() 114 | pdf.chapter_title(f"Generated Playbook for Router {i + 1}") 115 | pdf.chapter_body(playbook) 116 | 117 | # Save generated playbook to a file 118 | playbook_file = os.path.join(execution_folder, f"Router_{i + 1}_Playbook.yml") 119 | with open(playbook_file, "w") as file: 120 | file.write(playbook) 121 | 122 | # Execute the generated playbook 123 | start_time = time.time() 124 | execute_playbook(playbook_file, model_name, i + 1, text_before_code, text_after_code, conversation_history) 125 | 126 | elapsed_time = time.time() - start_time 127 | 128 | return generate_playbooks_duration, elapsed_time 129 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.10.11 2 | aiosignal==1.3.1 3 | annotated-types==0.6.0 4 | ansible==9.5.1 5 | ansible-base==2.10.17 6 | ansible-core==2.17.7 7 | ansible-pylibssh==1.1.0 8 | ansible-runner==2.3.6 9 | asttokens==2.4.1 10 | async-timeout==4.0.3 11 | attrs==23.2.0 12 | backcall==0.2.0 13 | certifi==2024.7.4 14 | cffi==1.16.0 15 | chardet==5.2.0 16 | charset-normalizer==3.3.2 17 | colorama==0.4.6 18 | contourpy==1.2.1 19 | cryptography==43.0.1 20 | cycler==0.12.1 21 | dataclasses-json==0.6.5 22 | decorator==5.1.1 23 | docutils==0.21.2 24 | exceptiongroup==1.2.1 25 | executing==2.0.1 26 | fonttools==4.51.0 27 | fpdf==1.7.2 28 | frozenlist==1.4.1 29 | getch==1.0 30 | greenlet==3.0.3 31 | idna==3.7 32 | imageio==2.34.1 33 | ipython==8.24.0 34 | jedi==0.19.1 35 | Jinja2==3.1.5 36 | jsonpatch==1.33 37 | jsonpointer==2.4 38 | kiwisolver==1.4.5 39 | langchain==0.3.0 40 | langchain-community==0.2.9 41 | langchain-core==0.1.50 42 | langchain-text-splitters==0.0.1 43 | langsmith==0.1.54 44 | lockfile==0.12.2 45 | MarkupSafe==2.1.5 46 | marshmallow==3.21.2 47 | marshmallow-enum==1.5.1 48 | matplotlib==3.8.4 49 | matplotlib-inline==0.1.7 50 | multidict==6.0.5 51 | mypy-extensions==1.0.0 52 | numexpr==2.10.0 53 | numpy==1.26.4 54 | openai==0.27.8 55 | openapi-schema-pydantic==1.2.4 56 | orjson==3.10.3 57 | packaging==23.2 58 | parso==0.8.4 59 | pexpect==4.9.0 60 | pickleshare==0.7.5 61 | pillow==10.3.0 62 | prompt-toolkit==3.0.43 63 | psutil==5.9.8 64 | ptyprocess==0.7.0 65 | pure-eval==0.2.2 66 | pycparser==2.22 67 | pydantic==2.7.1 68 | pydantic_core==2.18.2 69 | Pygments==2.18.0 70 | PyInputPlus==0.2.12 71 | pyparsing==3.1.2 72 | PySimpleValidate==0.2.12 73 | python-daemon==3.0.1 74 | python-dateutil==2.9.0.post0 75 | PyYAML==6.0.1 76 | reportlab==4.2.0 77 | requests==2.32.0 78 | resolvelib==1.0.1 79 | six==1.16.0 80 | SQLAlchemy==2.0.29 81 | stack-data==0.6.3 82 | stdiomask==0.0.6 83 | tabulate==0.9.0 84 | tenacity==8.2.3 85 | terminalplot==0.4.0 86 | tqdm==4.66.4 87 | traitlets==5.14.3 88 | typing-inspect==0.9.0 89 | typing_extensions==4.11.0 90 | urllib3==2.2.2 91 | wcwidth==0.2.13 92 | yarl==1.9.4 93 | -------------------------------------------------------------------------------- /ssh_ip_addresses.txt: -------------------------------------------------------------------------------- 1 | 172.168.1.17 2 | 192.168.2.2 3 | 192.168.4.2 4 | 192.168.6.2 5 | 6 | -------------------------------------------------------------------------------- /utility.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | import pickle 3 | from pygments import highlight 4 | from pygments.lexers import get_lexer_by_name 5 | from pygments.formatters import TerminalFormatter 6 | import re 7 | import ipaddress 8 | import os 9 | from fpdf import FPDF 10 | 11 | # Get the current directory path 12 | current_path = os.path.dirname(os.path.abspath(__file__)) 13 | 14 | # Load or create user configuration 15 | def load_user_config(): 16 | existing_config_file = os.path.join(current_path, "user_config.pkl") 17 | if os.path.exists(existing_config_file): 18 | with open(existing_config_file, "rb") as file: 19 | return pickle.load(file) 20 | else: 21 | return {} 22 | 23 | def save_user_config(config): 24 | existing_config_file = os.path.join(current_path, "user_config.pkl") 25 | with open(existing_config_file, "wb") as file: 26 | pickle.dump(config, file) 27 | 28 | # Encrypt or load OpenAI key 29 | def encrypt_key(key, cipher_suite): 30 | return cipher_suite.encrypt(key.encode()) 31 | 32 | def decrypt_key(encrypted_key, cipher_suite): 33 | return cipher_suite.decrypt(encrypted_key).decode() 34 | 35 | def animate_message(message): 36 | # Animate the message to be printed one character at a time 37 | for char in message: 38 | print(char, end='', flush=True) 39 | 40 | # Function to get the terminal width 41 | def get_terminal_width(): 42 | try: 43 | _, columns = shutil.get_terminal_size() 44 | return columns 45 | except: 46 | return 80 47 | 48 | # Function to print a line with "=" based on the terminal width 49 | def print_line(): 50 | width = get_terminal_width() 51 | print("=" * width) 52 | 53 | # Function to get a positive integer input from the user 54 | def get_positive_integer_input(prompte): 55 | while True: 56 | try: 57 | value = int(input(prompte)) 58 | if value > 0: 59 | return value 60 | else: 61 | animate_message("Sorry, that is an invalid input! Please enter a positive integer\n") 62 | except ValueError: 63 | animate_message("Sorry, that is an invalid input! Please enter a valid integer\n") 64 | 65 | # Function to save router configurations 66 | def save_configuration(configurations): 67 | config_file = os.path.join(current_path, "router_configurations.pkl") 68 | with open(config_file, "wb") as file: 69 | pickle.dump(configurations, file) 70 | 71 | # Function to load router configurations 72 | def load_configuration(): 73 | config_file = os.path.join(current_path, "router_configurations.pkl") 74 | if os.path.exists(config_file): 75 | with open(config_file, "rb") as file: 76 | return pickle.load(file) 77 | else: 78 | return None 79 | 80 | # Function to print text in blue color 81 | def print_blue(text): 82 | animate_message("\033[94m{}\033[0m".format(text)) 83 | 84 | # Function to format and print colored code 85 | def print_colored_code(code): 86 | lexer = get_lexer_by_name("yaml") # Set the appropriate lexer for the code language 87 | formatter = TerminalFormatter() 88 | colored_code = highlight(code, lexer, formatter) 89 | print(colored_code) 90 | 91 | # Function to print a summary of execution times 92 | def print_summary(input_router_duration, generate_playbooks_duration, execute_playbooks_duration, summary_duration): 93 | print_blue("\n\n********** Below is a Summary of How Long It Took Us To Setup Your Network **********") 94 | print_blue("\n1. We spent {:.2f} seconds to input the various router parameters.".format(input_router_duration)) 95 | print_blue("\n2. The process for generating all the playbooks took {:.2f} seconds.".format(generate_playbooks_duration)) 96 | print_blue("\n3. We spent {:.2f} seconds to execute all the generated playbooks".format(execute_playbooks_duration)) 97 | print_blue("\n4. In Total, it has taken {:.2f} seconds to automate your network from start to finish".format(summary_duration)) 98 | 99 | # Function to validate CIDR network format 100 | def validate_cidr_network(cidr_network): 101 | # Validate if the CIDR network format is correct 102 | network_parts = cidr_network.split("/") 103 | if len(network_parts) != 2: 104 | return False 105 | 106 | ip_address = network_parts[0] 107 | subnet_mask = network_parts[1] 108 | if not re.match(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip_address): 109 | return False 110 | 111 | try: 112 | ipaddress.IPv4Network(cidr_network, strict=False) 113 | return True 114 | except (ipaddress.AddressValueError, ipaddress.NetmaskValueError, ValueError): 115 | return False 116 | 117 | # Function to convert CIDR network to network address 118 | def convert_cidr_network(cidr_network): 119 | ip, subnet = cidr_network.split("/") 120 | subnet_mask = (0xFFFFFFFF << (32 - int(subnet))) & 0xFFFFFFFF 121 | subnet_mask = [(subnet_mask >> i) & 0xFF for i in [24, 16, 8, 0]] 122 | ip_parts = ip.split(".") 123 | network_address = ".".join(ip_parts[:4]) + " " + ".".join(str(part) for part in subnet_mask) 124 | return network_address 125 | 126 | # Function to convert CIDR network to network address with wildcard mask 127 | def convert_cidr_network_wildcard(cidr_network): 128 | ip, subnet = cidr_network.split("/") 129 | subnet_mask = (0xFFFFFFFF << (32 - int(subnet))) & 0xFFFFFFFF 130 | subnet_mask = [(subnet_mask >> i) & 0xFF for i in [24, 16, 8, 0]] 131 | wildcard_mask = [(255 - subnet_mask[i]) for i in range(4)] 132 | ip_parts = ip.split(".") 133 | network_address = ".".join(ip_parts[:4]) + " " + ".".join(str(part) for part in wildcard_mask) 134 | return network_address 135 | 136 | # Class to format the PDF report 137 | class PDF(FPDF): 138 | def header(self): 139 | self.set_font('Arial', 'B', 12) 140 | self.cell(0, 10, 'Network Configuration Report', 0, 1, 'C') 141 | 142 | def chapter_title(self, title): 143 | self.set_font('Arial', 'B', 14) 144 | self.cell(0, 10, title, 0, 1, 'L') 145 | self.ln(5) 146 | 147 | def chapter_body(self, content): 148 | self.set_font('Arial', '', 12) 149 | self.multi_cell(0, 10, content) 150 | self.ln(10) 151 | --------------------------------------------------------------------------------