Last active
November 7, 2024 05:18
-
-
Save huynhbaoan/9367b2bb1db65668df60097d1a1ee639 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipaddress | |
import pandas as pd | |
import sys | |
def check_ip_in_cidr(ip, cidr): | |
""" | |
Checks if a given IP address belongs to a specified CIDR range. | |
:param ip: IP address as a string. | |
:param cidr: CIDR range as a string. | |
:return: Boolean indicating if IP is within the CIDR range. | |
""" | |
try: | |
return ipaddress.ip_address(ip) in ipaddress.ip_network(cidr) | |
except ValueError: | |
# Handle invalid IP or CIDR inputs | |
return False | |
def verify_ip_cidr_to_csv(input_file, output_file): | |
""" | |
Reads a space-delimited file with IP addresses and CIDR ranges, checks if each IP belongs to its CIDR, | |
and outputs the result to a new CSV file with an additional "Belongs to CIDR" column. | |
:param input_file: Path to the input space-delimited file with columns "IP Address" and "CIDR". | |
:param output_file: Path to the output CSV file. | |
""" | |
# Read the file with space as delimiter | |
dataframe = pd.read_csv(input_file, delim_whitespace=True, names=["IP Address", "CIDR"]) | |
# Perform the check and add results to a new column | |
dataframe['Belongs to CIDR'] = dataframe.apply(lambda row: check_ip_in_cidr(row['IP Address'], row['CIDR']), axis=1) | |
# Write the results to a new CSV file | |
dataframe.to_csv(output_file, index=False) | |
print(f"Results have been written to {output_file}") | |
if __name__ == "__main__": | |
# Ensure the script is run with the correct number of arguments | |
if len(sys.argv) != 3: | |
print("Usage: python script_name.py <input_file> <output_file>") | |
sys.exit(1) | |
input_file = sys.argv[1] | |
output_file = sys.argv[2] | |
# Run the IP to CIDR verification and output results | |
verify_ip_cidr_to_csv(input_file, output_file) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipaddress | |
import pandas as pd | |
def find_correct_cidr(ip, target_cidr): | |
""" | |
Finds the correct CIDR block with the same or larger netmask that contains the IP. | |
:param ip: The IP address to check. | |
:param target_cidr: The original CIDR block as a string. | |
:return: Correct CIDR block containing the IP or None if not found. | |
""" | |
ip_addr = ipaddress.ip_address(ip) | |
target_network = ipaddress.ip_network(target_cidr, strict=False) | |
# Start with the original prefix length and increase if necessary | |
for prefix_len in range(target_network.prefixlen, 33): # 33 for IPv4 max +1 | |
candidate_network = ipaddress.ip_network(f"{ip}/{prefix_len}", strict=False) | |
if candidate_network.network_address == target_network.network_address: | |
return str(candidate_network) | |
return None | |
def correct_cidr_for_ips(dataframe): | |
""" | |
Checks and finds the correct CIDR block for each IP address based on its target CIDR. | |
:param dataframe: DataFrame with columns "IP Address" and "CIDR". | |
:return: DataFrame with an additional "Correct CIDR" column. | |
""" | |
results = [] | |
for _, row in dataframe.iterrows(): | |
ip = row['IP Address'] | |
cidr = row['CIDR'] | |
correct_cidr = find_correct_cidr(ip, cidr) | |
results.append(correct_cidr) | |
dataframe['Correct CIDR'] = results | |
return dataframe | |
# Load your data from a CSV (space-delimited) with IP and CIDR columns | |
data = pd.read_csv('input.csv', delim_whitespace=True, names=["IP Address", "CIDR"]) | |
# Calculate the correct CIDR blocks | |
result_df = correct_cidr_for_ips(data) | |
# Output the results to a new CSV file | |
result_df.to_csv('corrected_cidr_output.csv', index=False) | |
print("Results have been written to corrected_cidr_output.csv") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment