Мне удалось разобраться со всеми возможными ошибками, кроме тех, которые предназначены для использования случай, когда файл CSV создается вручную (не экспортируется из электронной таблицы в виде файла CSV), и пользователь забывает добавить запятую между двумя значениями или добавляет только имя хоста или IP-адрес, но без запятой после или перед.< /p>
Сейчас цикл прерывается, когда находит строку без разделителя полей.
Легко ли с этим справиться?
В этих случаях решением было бы переписать строку (строку) и добавить запятую, но я не знаю, как это сделать внутри цикла чтения программы чтения CSV:
- Добавьте запятую между именем и IP-адресом.
- Добавьте запятую после имени хоста.
- Добавьте запятую перед IP-адрес
- Добавьте дополнительные запятые в любом месте
# This is the expected input
dntsw1101,10.2.3.1
# For this error I'm throwing a warning to the user
dntsw1101,
# For this error I'm throwing a warning to the user
,1.2.3.1
# For the empty line case I'm throwing a warning to the user
# CSV reader manages this error without any problem
dntsw1101,10.2.3.1,,,
!
# This is issue #1
dntsw110110.2.3.1
# This is issue #2
dntsw1101
# This is issue #3
10.2.3.1
# This is issue #4
dntsw1101,,10.2.3.1
Поскольку все IP-адреса начинаются с 10, 172 или 192 (частное пространство), было бы легко использовать REGEX для группировки в проблеме № 1 и разделить имя хоста и нумерацию из IP-адрес, ища эти значения.
Чтобы добавить более подробную информацию, проблема в том, что он не выдает никаких ошибок или исключений, а только ломается. Это мой текущий сценарий:
# Initialize the list of network devices
switches = []
routers = []
firewalls = []
termservers = []
sitecodes = []
device_error = str('')
# Read the CSV file to populate the lists
try:
with open(args.filename[0]) as file:
network_devices = csv.reader(file, delimiter=",")
for row in network_devices:
if any(x.strip() for x in row): # This is to handle empty rows as well as the 'except'
# REGEX match for valid IP address that allows to filter in by only private IP addressing
ipaddress_pattern = r'^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$'
valid_ip=re.match(ipaddress_pattern,row[1])
if valid_ip:
# check if the site code matches the previous ones
x=(all(x==row[0][:5] for x in sitecodes))
print (str(network_devices.line_num) + ' ' + row[0])
if x:
#capture the site code
sitecodes.append(row[0][:5])
else:
device_error += ('\n=> Check hostname {}, line {}'.format(row[0],network_devices.line_num))
# capture the routers
x=re.search(".*(rt101|rt102)",row[0])
if x:
routers.append(row[1])
continue
# capture the L2 and L3 switches
x=re.search(".*(rt1[1-2]|sw).*",row[0])
if x:
switches.append(row[1])
continue
# Check for rows with hostname but not IP address, or invalid IP addresses not matching the REGEX expression above
else:
# check if row fields are the other way round (ip,hostname)
if re.match(ipaddress_pattern,row[0]):
device_error += ('\n=> Invalid row with IP address in the first field, line {}'.format(network_devices.line_num))
else:
device_error += ('\n=> Check IP address from hostname {}, line {}'.format(row[0],network_devices.line_num))
Это пример файла: убедитесь, что он прерывается на строке 15 при появлении первой неправильной записи, но не обрабатывает последнюю правильную строку.
esdntsw1102,10.2.3.1
esdntrt101,10.2.3.2
1.2.3.2,esdntrt102
esdntrt11,10.2.3.3
,
,,
esdntsw1101,
,10.2.3.8
esdntsw1103,10.2.3.10
esmadrt12,10.2.3.11
esdntsw1104,10.2.3.12,,
esdntsw1103,10.2.3.299
esdntsw1105,10.2.3.13
esdntrt102
esdntrt10210.2.3.14
10.2.3.15
esdntrt102,10.2.3.16
Подробнее здесь: https://stackoverflow.com/questions/790 ... -separator