import csv,logging from ipaddress import IPv4Address,IPv4Network from datetime import datetime class commands: def __init__(self, name, ip, mask, comment, inline = None, ObjectGroup = None): self.name = name self.ip = ip self.mask = mask self.comment = comment def ASAHostObject(self): ''' Adds ASA Host Object''' return f'object network {self.name} \n description {self.comment} \n host {self.ip}' def ASASubnetObject(self): ''' Adds ASA Subnet Object''' return f'object network {self.name} \n description {self.comment} \n subnet {self.ip} {self.mask}' def ASA_Inline_Host(self): ''' Addes Inline Host to Object-group ''' return f'network-object host {self.ip}' def ASA_Inline_Subnet(self): ''' Addes Inline subnet to Object-group ''' return f'network-object network {self.ip} {self.mask}' def CSV_Parse(): """ This function parses and checks for errors in csv file If no errors in csv file, it will return PunchCard that will be 'fed' to class Commands later""" PunchCard = [] with open('objectlist.csv','r') as csv_file: csv_reader = csv.reader(csv_file,delimiter = ',') next(csv_reader) DefaultComment = "MACD#-AL97-" + f'{datetime.now():%b-%d-%Y}' for Each_Row in csv_reader: #Let the parse begin if (len(Each_Row[0]) == 0 or len(Each_Row[1]) == 0): #Checking if "Name" and "IP" fields are not blank in csv file. print("Error Occured! 'Object Name' and/or 'IP' fields cannot be empty") return if len(Each_Row[2]) == 0: Each_Row[2] = DefaultComment IP = Check_IP(Each_Row[1]) if IP == False: return elif '/32' in Each_Row[1] or '/' not in Each_Row[1]: Each_Row[1]=IP[0] else: Each_Row[1] = IP PunchCard.append(Each_Row) for Each_Element in PunchCard: print(Each_Element) def Check_IP(ip): ''' CSV Parser calls this function to validate IP/Mask pair. Once validated, CSV Parser appends each punch card with validated IP/Mask pair ''' try: address = IPv4Network(ip, strict = False).with_netmask SplitAddress = address.split('/') IP = SplitAddress[0] MASK = SplitAddress[1] return [IP,MASK] except ValueError as error: error = "Mistake in IP/Subnet Pair : Check CSV file" print (error) return False #print(ASA) # ASA = commands('INT-NET-192.168.1.0', '192.168.1.0','255.255.255.0', 'test-host-internal1') # print(ASA.ASASubnetObject()) CSV_Parse()