Last active
November 2, 2022 15:32
-
-
Save SonGokussj4/0fc76e0f5c1c726faceffc716214039e to your computer and use it in GitHub Desktop.
Convert IP address data in csv to CIDR format
This file contains 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
""" | |
Change IP to CIDR (ignore second IP) and export to CSV | |
Usage: | |
python3 main.py <source_file> | |
Example data: | |
<source_file>: | |
1.0.174.0,1.0.174.255,AS,TH,"Nakhon Si Thammarat","Phra Phrom",8.33911,99.9009 | |
1.0.78.0,1.0.78.255,AS,JP,Hiroshima,Hiroshima,34.4002,132.475 | |
23.251.37.48,23.251.38.7,AS,CN,Shaanxi,Xi'an,34.3416,108.94 | |
<export_file>: | |
16821760,AS,TH,"Nakhon Si Thammarat","Phra Phrom",8.33911,99.9009 | |
16797184,AS,JP,Hiroshima,Hiroshima,34.4002,132.475 | |
402335024,AS,CN,Shaanxi,Xi'an,34.3416,108.94 | |
""" | |
import csv | |
import time | |
import sys | |
from pathlib import Path | |
SOURCE_FILEPATH = Path(sys.argv[1]) | |
EXPORT_FILEPATH = SOURCE_FILEPATH.parent / "export.csv" | |
def read_data(filename, skip_header=False): | |
with open(filename) as csv_file: | |
if skip_header: | |
next(csv_file) | |
for row in csv_file: | |
try: | |
items = row.split(",") | |
# items[-1] = items[-1].strip() | |
yield items | |
except ValueError: | |
print(f"Failed to read {row[0]}") | |
def convertToCIDR(ip_address): | |
nums = ip_address.split(".") | |
result = int(nums[0]) * 16777216 + int(nums[1]) * 65536 + int(nums[2]) * 256 + int(nums[3]) | |
return result | |
def main(): | |
start = time.time() | |
with open(EXPORT_FILEPATH, "w") as f: | |
writer = csv.writer(f, delimiter=",", lineterminator="", quotechar="", quoting=csv.QUOTE_NONE) | |
generator = read_data(SOURCE_FILEPATH) | |
for ip1, _, *rest in generator: | |
cidr = convertToCIDR(ip1) | |
writer.writerow([cidr, *rest]) | |
end = time.time() - start | |
print(f"Exported {EXPORT_FILEPATH.absolute()}") | |
print(f"Done in {end:.2} seconds") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment