'fout.write(line.replace) for multiple lines with different values is not working correctly?
I am a network engineer trying to write a Python Script to create Switch configs (initially). I did one that had 1000's of lines as i put all the config in the script. So i decided to create a base txt file and then replace certain parts of it, the script does create the switch config file but not correctly. This is small part of the full script but once this part is ironed out it will be finished...more or less. If you run this yourself you, only Automation will work at the moment.
Network = input('Which Network is this config for? (Automation, CCTV or Corp): ')
Unit = input('Which Unit? (A, B or C): ')
Cab = input('Which Cab will the Switch be installed in? ')
Number = input('What will the number of the Switch be? e.g. 01, 02 etc? ')
Mgmt_vlan = input('What is the management vlan? ')
Data_Vlan = input('What is the Data Vlan? ')
default_gateway = '172.x.x.254'
def config():
while True:
if Network == 'Automation':
Host_Name = f'Unit{Unit}_Auto_Sw{Cab}{Number}'
Mgmt_ip = f'172.24.{Mgmt_vlan}.{Data_Vlan} 255.255.255.0'
new_default_gateway = default_gateway
new_default_gateway = f'172.24.{Mgmt_vlan}.254'
print(Host_Name)
print(Mgmt_ip)
print(new_default_gateway)
fin = open('config.txt', 'rt')
fout = open(f'{Host_Name}.txt', 'wt')
for line in fin:
fout.write(line.replace('#host#', f'{Host_Name}'))
fout.write(line.replace('#mgmt#', f'{Mgmt_vlan}'))
fout.write(line.replace('#mgmt_ip#', f'{Mgmt_ip}'))
break
config()
This is the txt file and output below:
en ! conf t ! hostname #host# !
vlan #mgmt# ! int vlan #mgmt# ip address #mgmt_ip# no shut ! ip
default-gateway #default_gateway#
Output
en en en ! ! ! conf t conf t conf t ! ! ! hostname UnitA_Auto_SwQ01
hostname #host# hostname #host# ! ! ! vlan #mgmt# vlan 63 vlan #mgmt#
! ! ! int vlan #mgmt# int vlan 63 int vlan #mgmt# ip address #mgmt_ip#
ip address #mgmt_ip# ip address 172.24.63.12 255.255.255.0 no shut no
shut no shut ! ! ! ip default-gateway #default_gateway#ip
default-gateway #default_gateway#ip default-gateway #default_gateway#
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
