add command to rc.local

Written in

by

Yesterday I was working on simple install script which was suppose to insert a command to rc.local. It is more complicated matter than you would think. Sometimes, there is already „exit 0“ and then you don’t want to end up after that command. You also don’t want to add your command twice there. Here is what I came up with (in python):

import sys

rclocal = '/etc/rc.local'
iptables_redirect = """iptables -t nat -A PREROUTING \
-i eth0 -p tcp --dport 80 -j REDIRECT --to-ports 8000"""
edited_file = [ ]
if iptables_redirect not in open(rclocal).read():
    with open(rclocal) as f:
       lines  = f.readlines()
    for l in lines:
      if l == "exit 0\n":
        edited_file.append(iptables_redirect + "\n")
      edited_file.append(l)
    with open(rclocal,"w") as f:
        for l in edited_file:
            f.write("%s"%l)

if iptables_redirect not in open(rclocal).read():
    with open(rclocal,'a+') as f:
        f.write(iptables_redirect+'\n')

Tags