I am trying to modify a configuration file using Python. How can I do the equivalent of multiple sed commands in this format:
sed -ci 's/ServerTokens OS/ServerTokens Prod/' /etc/httpd/conf/httpd.conf
most efficiently in Python? This is what I am doing right now:
with open("httpd.conf", "r+") as file:
tmp = []
for i in file:
if '#ServerName' in i:
tmp.append(i.replace('#ServerName www.example.com', 'ServerName %s' % server_name , 1))
elif 'ServerAdmin' in i:
tmp.append(i.replace('root@localhost', webmaster_email, 1))
elif 'ServerTokens' in i:
tmp.append(i.replace('OS', 'Prod', 1))
elif 'ServerSignature' in i:
tmp.append(i.replace('On', 'Off', 1))
elif 'KeepAlive' in i:
tmp.append(i.replace('Off', 'On', 1))
elif 'Options' in i:
tmp.append(i.replace('Indexes FollowSymLinks', 'FollowSymLinks', 1))
elif 'DirectoryIndex' in i:
tmp.append(i.replace('index.html index.html.var', 'index.php index.html', 1))
else:
tmp.append(i)
file.seek(0)
for i in tmp:
file.write(i)
It's needlessly complex since I could just use subprocess and sed instead. Any suggestions?