Updating File - Allowed IP Addresses

I created this algorithm during Google's Cybersecurity Certificate Program.

Project description

I used python to create an automated function that will update a file with the correct allowed IP addresses, removing any that are no longer allowed. A screenshot of the full code, all-together is below. The individual steps are labeled within the code as well as below the screenshot.

From Function to Script

While this code itself is written as a function more than a script, it could be written as a script as well. To change it to a script, I'd update it to include the paths to the import_file and remove_list. For example, I could write this as a script so that anytime someone marks an IP address as needing to be removed, this script automatically runs and removes it from the list of allowed/not-allowed ip addresses. This would allow for more efficiency and less repetitive tasks.

Entire code

Open the file that contains the allow list

import_file = "allow_list.txt"

Read the file contents

with open(import_file, "r") as file:

ip_addresses = file.read()

Convert the string into a list

ip_addresses = ip_addresses.split()

Remove IP addresses that are on the remove list

remove_list = ["192.168.97.225", "192.168.158.170", "192.168.201.40", "192.168.58.57"]

for element in ip_addresses:

if element in remove_list:

ip_addresses.remove(i)

Update the file with the revised list of IP addresses

ip_addresses = " ".join(ip_addresses)

with open(import_file, "w") as file:

file.write(ip_addresses)

Last updated