input from file.txt
ip route 10.8.125.144/28 10.0.59.5 description Sunny_House_HLR1_SIG
output needed in file2.txt
static-route-entry 10.8.125.144/28
next-hop 10.0.59.5
description "Sunny_House_HLR1_SIG"
no shutdown
exit
exit
может кто подскажет как это сделать?





Вы можете читать из файла, используя следующую инструкцию:
in_file = open('file.txt', 'r')
data = in_file.read()
in_file.close()
И писать:
out_file = open('file2.txt', 'w')
out_file.write(data)
out_file.close()
Я бы рекомендовал проверить раздел официальной документации Python по чтению / записи с файлами.
Что касается синтаксического анализа, понимания и форматирования полученных данных, это немного сложнее. Это зависит от того, какие данные вы ожидаете получить, как именно вы хотите ими манипулировать и т. д.
Для примера, который вы привели конкретно (и Только в этом примере), вот очень простой анализ данных:
# Read data from file.txt
# Split the string based on spaces,
# discarding the entries you don't use
# by labeling them as underscores
_, _, sre, nh, _, desc = data.split(' ')
# Insert the extracted values into a
# multi-line formatted string
final_output = f"""\
static-route-entry {sre}
next-hop {nh}
description {desc}
exit
exit
"""
# Write final_output to file2.txt
Если данные, которые вы ожидаете в файле file.txt, каким-либо образом различаются, вам придется написать более сложный алгоритм для синтаксического анализа, но это должно дать вам начало.
Обычно, когда вы имеете дело с IP-адресами, где вы также хотите их проверить, лучше всего использовать Модуль IPy (подробнее в ответах на этот вопрос)
Однако в вашем случае вы пытаетесь прочитать файл конфигурации и создать сценарий. В этом случае адреса уже подтверждены. Таким образом, использование regex для получения текстовых совпадений из конфигурации и их запись в формате сценария должно помочь.
import re # Import re module
# Define the pattern you'd like to match. You can use pat1 which does a more stringent check on the IP digits and decimals
pat1 = re.compile('^ip\s+route\s+(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}/\d{1,2})\s+(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})\s+description\s+(.*?)$')
Однако, поскольку здесь проверка не требуется, вы также можете использовать приведенный ниже шаблон, который меньше по размеру и даст такое же совпадение (вы можете увидеть, как он работает на regex101.com)
pat2 = re.compile('^ip\s+route\s+([0-9|.]{7,15}/\d{1,2})\s+([0-9|.]{7,15})\s+description\s+(.*?)$')
# Once the pattern is set, all you need to do is search for text and get the match
# Since you'd want to do this recursively over multiple lines of the input file and write to the output file, you need to open both files and iterate through the lines
with open (<outputfile>, 'w') as outfile: # open the <path of outputfile+filename> as outfile
with open (<inputfile>, 'r') as infile: # open the <path of inputfile+filename> as outfile
for line in infile: # read each line of the inputfile
match = re.search(pat2,line) # match pattern with the line
# assign the results of matching groups to variables
ip, dr, desc = match.group(1), match.group(2), match.group(3)
# Write to the output file in the required format
# You'll see the use of '\n' for next line and '\t' for tab
outfile.write("static-route-entry {}\n\tnext-hop {}\n\tdescription {}\n\tno shutdown\n\texit\nexit".format(ip, dr, desc))
Я предполагаю, что вам нужно будет указать следующий переход, описание и отключение в том же отступе, что и при первом выходе. Вы можете использовать '\ t' для добавления вкладок, если вам нужно, но если это сценарий, это не имеет значения.
[Out]:
static-route-entry 10.8.125.144/28
next-hop 10.0.59.5
description Sunny_House_HLR1_SIG
no shutdown
exit
exit