I recently started to learn Python for the purpose of making my life as a network engineer easier when performing repetitive tasks.
The script below does parse a huge inventory.xml file I get from a reporting tool to find the ID of ports I want it to and then writes back to the XML file a structure representing a cable between the two network ports. I do convey the name of the ports I want to link in a basic CVS file with 2 columns.
<link>
<portid1>ca1cfd39-cf8f-4d69-a52b-d06357da66b1</portid1>
<portid2>79d8c32a-8891-4bd4-a0a1-1a6e1b333a4b</portid2>
</link>
This is the code I tried to comment to the best of my ability:
#links.csv file shoud be made as follows :
#port1,port2
#port1,port2
# .
# .
# .
from lxml import etree
import csv
import fileinput
#preparing variables
result=[]
trigger=False
tree=etree.parse("inventory.xml")
#parsing the csv file containing the port names to link together
with open('links.csv', 'rb') as csvfile:
fichier=csv.reader(csvfile)
for row in fichier:
name1=row[0] #name of the first port
name2=row[1]
portid1=str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name1)) #searches for the port id in the .xml
portid2=str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name2))
portid1=portid1[2:-2] #output was surrounded by [""] so i cut the first two and last two
portid2=portid2[2:-2]
result.append(("<link>\n<portid1>{}</portid1>\n<portid2>{}</portid2>\n</link>\n").format(portid1, portid2)) #store data
result="".join(result)
#search the file until we find the <links> line, then we print the result
for line in fileinput.input('inventory.xml', inplace=1):
if line.startswith(' <links>'):
trigger=True
else:
if trigger:
print result
trigger=False
if line.rstrip():
print line, #wannabe pretty print
The goal of posting here is mainly to make my code as readable to others and as standard as possible, because I know the work I do will probably be read of tweaked by others in the future.