I just wrote a function for Windows that runs program as a different user because when I run program under administrator rights it is not working good. Then I thought it would be good to have a crossplatform version of this function.
On Linux with reference to the patch etc. described in the link I posted earlier, the contributed file runexecuteafterasuser.pas contains this:
(* The user has requested that the command passed as the parameter be run as a
different (usually more-privileged) user. Construct an appropriate prefix.
*)
function Prefix(const command, asUser: string): string; platform; experimental;
begin
if (asUser = '') or (asUser = 'root') then
result := 'sudo --askpass --reset-timestamp ' + command
else
result := 'sudo --askpass --reset-timestamp --user=' + asUser + ' ' + command
end { Prefix } ;
I did it like that after a lot of fiddling around because one can almost always rely on sudo being installed, and the --askpass option is generally set up to call into whatever graphical environment is running to bring up a dialog(ue), although this might require a line in /etc/sudo.conf or that the SUDO_ASKPASS shell variable has to be set somewhere.
However as I've said: making sure that the user is a member of the appropriate group, and/or that there are suitable udev rules in place, is almost always to be preferred. If that doesn't work, for example if a program is to listen on a low-numbered port, then use an appropriate POSIX capability.
There's problems there, which I'm sure I've touched on before (i.e. cited thread): in order to set a capability, you either need to be root or the capability-setting program needs to be blessed with the "this can set capabilities" capability. However if you bless something like an IDE with "this can set capabilities", then it can subsequently bless any program it generates with "this can set capabilities": if the POSIX people had really thought things through then there'd be a special "this can set any capability except for the 'this can set capabilities' capability".
MarkMLl