5

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?

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
  • 1
    Well to change Effective UID `$>` you need to be running as root, is your script running either setuid root or as the root user? – Doon Apr 28 '11 at 19:34

2 Answers2

2

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.

daxim
  • 39,270
  • 4
  • 65
  • 132
  • I do not know if I can open a writable file handle that uses `sudo`. I'm really trying to avoid `sudo`, unless I can make that file handle writable for that user. As for the second option, I'd need to pass the `sudo`'ed program a Perl hash reference, somehow, which doesn't seem straightforward. Does this help the question make more sense? – Alex Reynolds Apr 28 '11 at 21:47
0

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.

David Harris
  • 2,332
  • 1
  • 13
  • 25
  • ...note, however, that this can be a royal pain to update/maintain long-term because most (if not all) *nices will clear the suid/sgid bits every time you edit the file. – Dave Sherohman Apr 29 '11 at 08:52