2

I want to add a line(such as '*/data/mod/myservice start some_parameter*'.) to /etc/rc.d/rc.local file in shell script. If there exists a line start with '*/data/mod/myservice start*', then replace it by new one.

In my script, it execute the next python method.

def excuteCmd(cmd):
    import commands
    output = commands.getoutput(cmd)

def setTask(cmd, installFlag):
    print cmd, installFlag
    excuteCmd('cat /etc/rc.d/rc.local >  oldTask')
    input = open('oldTask','r')
    emptyFile = False
    lines = input.readlines()
    input.close()
    taskNum = len(lines)
    output = open('newTask', 'w')
    if (taskNum  == 0):
            if (installFlag):
                    output.write(cmd + '\n')
    else:
            for i in range(taskNum):
                    if (lines[i].find(cmd) == -1):
                            output.write(lines[i])
            if (installFlag):
                    output.write(cmd + '\n')
    output.close()
    excuteCmd('sudo cat newTask > /etc/rc.d/rc.local')
    excuteCmd('rm -f oldTask')
    excuteCmd('rm -f newTask')

But when i execute sudo cat newTask > /etc/rc.d/rc.local, it raise the following error.

-bash: /etc/rc.d/rc.local: Permission denied

Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
zhouzuan2k
  • 157
  • 2
  • 8

2 Answers2

2

This means that you don't have permission to either write to or delete the file. Also, you won't be able to run the sudo command like that without typing in a password, so ideally the script itself would be run using sudo python scriptname.

jeffknupp
  • 5,966
  • 3
  • 28
  • 29
  • Also, I think I'm right, the sudo command only refers to the thing that are executed before the > sign, not after. jknupp probably know that, but I did'nt think it was clear in his answer :) – Niclas Nilsson Dec 28 '11 at 14:08
2

sudo command > filename executes command using sudo (with root privileges), but writes into the filename with user's privileges (insufficient to write to /etc). Imagine it like this:

(sudo command) > filename

The sudo applies to the bracketed part only.

You could run your whole script using sudo.

eumiro
  • 207,213
  • 34
  • 299
  • 261