Well this is my script. It is to configure my systems sysctl.conf.
infile = open('sysctl.conf')
outfile = open('sysctl.conf.new', 'w')
replacements = {'Net.ipv4.icmp_echo_ignore_all' :'1',
'Net.ipv4.icmp_echo_ignore_broadcasts' :'1',
'Net.ipv4.ip_forward' : '0',
'Net.ipv4.tcp_syncookies':'1',
'Net.ipv4.conf.all.rp_filter': '1',
'Net.ipv4.conf.all.Log.martiansd':'1',
'Net.ipv4.conf.all.Secure_redirects' : '1',
'Net.ipv4.conf.all.Send_redirects' : '0',
'Net.ipv4.conf.all.Accept_Source_Route': '0',
'Net.ipv4.conf.all.Accept_redirects':'0',
'Net.ipv4.tcp_max_syn_backlog': '4096',
}
for line in infile:
if '#' in line:
pass
elif '=' in line:
w = line.split('=')
for var, value in replacements.iteritems():
if var in w[0]:
line=line.replace(w[1],value)
outfile.write(line)
infile.close()
outfile.close()
This script works fine but there is one problem. If any of the parameters in replacement is not present in sysctl.conf then it is not going to add it in the new configuration file.It only modifies the parameters present with my values. I want to add all parameters in the configuration or change if they are already present. How to do it?
I know it should be easy but I am stuck here.
ConfigParser
as a general panacea for linux configuration parsing; just stating that it may be appropriate for your use case since your file appears to contain key-value pairs with key and value separated by=
. As for the section problem, here's a workaround from the great Alex Martelli