简体   繁体   中英

How do I delete a file owned by root from within bash script?

I want to delete a file (/var/lib/pacman/db.lck) owned by root user from within a simple script owned by a non-privileged user:

#!/bin/bash
rm -f /var/lib/pacman/db.lck

But I don't want to run the script using sudo in order to avoid typing password each time I execute the script as a non-privileged user. In order to achieve this I set the s bit:

-rwsrwsrwx  1 popov  users       41 04.02.2015 10:35 unlock.sh

But after running the script I get

rm: cannot remove ‘/var/lib/pacman/db.lck’: Permission denied

It seems that I wrongly understand the purpose of s bit.

So the question is: How to setup the script permissions (and/or perhaps ownership of the script) which will let the script to delete a root-owned file when invoked by a non-privileged user?

If the problem is that sudo asks the password, you could configure sudo with "NOPASSWD" option with this command. Something like that:

joe ALL=(ALL) NOPASSWD: /full/path/to/command

Another alternative is replacing the shell script with a little C program:

#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>

#define FILENAME "/var/tmp/dummy"

int main() {
    if(unlink(FILENAME) == -1) {
        printf("unlink() of %s failed: %s\n", FILENAME, strerror(errno));
        return 1;
    }
    return 0;
}
  • Change the FILENAME
  • Save it as unlink_it.c .
  • Compile using gcc -Wall -o unlink_it unlink_it.c
  • Copy it to a suitable place (perhaps /usr/local/bin ).
  • Change the owner to root
  • Add the SUID bit to the program
  • Call the special purpose program from your unprivileged shell script.

Beware: Any user on the system can launch the program and thus delete the file unless you limit its use using the UNIX permissions!

First of all, the script needs to be owned by the user that is given to the script while executing (in your case, root ). However, SUID shell scripts are a bad idea (see comment).

The proper solution is not to run the script as SUID, instead you should give the user write permission to the directory that the file resides in. Then the script can unlink (delete) the file even if it belongs to another user and it has no permission to write to it.

A concrete example: You have a user "popov" that is member of the group "popov" and a directory /var/lib/pacman

chgrp popov /var/lib/pacman
chmod g+w /var/lib/pacman

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM