How to open Perl file handle to write data via sud

2019-06-23 14:45发布

问题:

I'd like to write data to a file, but the file handle should be opened with access permissions for a specific user.

Thus, the following statement:

open (FH, "> $filename") or die "$@\n";

would allow writing to a file as that particular user.

Is there a way to do this within a Perl script, without the entire script being run with sudo -u $username?

回答1:

There are two established ways. Stackers, you are invited to edit this answer to fill in the drawbacks for each.

Run the program with sudo. The first thing you do in the program is to open the files you need and keep the handles, and then immediately afterwards drop the root privileges. Any further processing must take place with low privileges. The Apache httpd works likes this, it opens the log files as root, but continues running as nobody or similar.

If you don't like that way, run the program normally, and when you need to elevate, create a new process and have it run with a user configured sudo, su -, kdesu/gksu or whatnot. The CPAN client works likes this, it fetches, unpacks, builds and tests a module as a normal user, but calls sudo make install etc. when it's time to install.



回答2:

An alternative to daxim's suggestions is to have the script owned by the specific user and have the script permissions include the setuid and/or setgid bits.