I am trying to script a configuration file which is dependant on user input.
The python file asks how many devices will be connecting to this device and will duplicate the config across each port dependant on the user input - So user input of 5 will duplicate the config 5 times so the user can copy and paste or push the created config to the device.
When this config duplicates I want to change small parameters like the port number and description. I have worked out how to change multiple parameters but this duplicates config, how can I get around this?
I have looked at Itertools but didn't understand how to leverage that to my desired output.
I have tried:
import os
import sys
a=int(input('How many devices will there be?: '))
q=input('What is the site code?')
with open(f'device.{q}.txt', 'w') as f:
for ports in range(3, a 3):
for lag in range(2, a 2):
f.write(f'set interface x/x/p{ports} user-label "Connection Link to device.{q} : Connection -{lag}"\n\n')
f.close()
In my text file I get:
set interface x/x/p3 user-label "Connection Link to device.device - Desc: Connection-2"
set interface x/x/p3 user-label "Connection Link to device.device - Desc: Connection-3" (I dont want this)
set interface x/x/p4 user-label "Connection Link to device.device - Desc: Connection-2" (I dont want this)
set interface x/x/p4 user-label "Connection Link to device.device - Desc: Connection-3"
I Want in my text file:
set interface x/x/p3 user-label "Connection Link to device.device - Desc: Connection-2"
set interface x/x/p4 user-label "Connection Link to device.device - Desc: Connection-3"
CodePudding user response:
Sorted this issue now:
import os
import sys
print ('\n')
a=int(input('How many devices will there be?: '))
q=input('What is the site code?')
with open(f'device.{q}.txt', 'w') as f:
lag = 2
for ports in range(3, a 3):
f.write(f'set interface 1/1/p{ports} user-label "LAG Member Link to device.{q} - 1-1-101-0: lag-{lag}"\n\n')
lag = lag 1
f.close()
CodePudding user response:
It seems that for each port you only want to print the command once. Therefore, I suggest to add a condition by using enumerate function to check if the message has been written before or not.
import os
import sys
a = 3
q = 2
with open(f"device.{q}.txt", "w") as f:
for port_loop_number, ports in enumerate(range(3, a 3)):
for lag_loop_number, lag in enumerate(range(2, a 2)):
if port_loop_number == lag_loop_number:
f.write(
f'set interface 1/1/p{ports} user-label "LAG Member Link to device.{q} - 1-1-101-0: lag-{lag}"\n\n'
)
I also feel that the nested for loop is not very necessary. Maybe try this instead:
import os
import sys
a = 5
q = 7
with open(f"device.{q}_method2.txt", "w") as f:
for i in range(a):
ports = 3 i
lag = 2 i
f.write(
f'set interface 1/1/p{ports} user-label "LAG Member Link to device.{q} - 1-1-101-0: lag-{lag}"\n\n'
)
Good luck! Let me know if this works or if I can provide further clarification.