Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open Perl file handle to write data via sudo (or as another user)

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?

like image 269
Alex Reynolds Avatar asked Nov 05 '22 23:11

Alex Reynolds


1 Answers

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.

like image 159
daxim Avatar answered Nov 09 '22 10:11

daxim