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

百般思念 提交于 2019-12-12 10:54:02

问题


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.



来源:https://stackoverflow.com/questions/5823665/how-to-open-perl-file-handle-to-write-data-via-sudo-or-as-another-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!