in reply to su to root in a perlscript

virtualsue kicked around a problem that sounds a lot like this earlier this year in Running Perl program w/root privs via cron, which might contain some info useful to you as well.

Although it may not be quite what you're needing, in addition to the comments so far regarding the use of sudo, depending on the operations and environment there may also be the possibility you could use ssh public/private key pairs lacking passwords to do specific operations. Doing so would also have the advantage of not requiring your root password to reside in the scripts.

Hope all the comments help, and maybe let us know which solution worked out best for you and why, maybe.

Replies are listed 'Best First'.
Re: Re: su to root in a perlscript
by NaSe77 (Monk) on Aug 01, 2002 at 14:40 UTC
    the the instance i think i go for something like this (its not too pretty but works):
    sub rootMeAndDoStuff(){ my $rootID = getpwnam("root"); if (not ($rootID eq $<)){ print "U have to be root to do the following ...\n"; system "su -c $PartToDoAsRoot"; } }
    but i am not very content with it since this wont work under win32. and sooner or later it has to.

    update: there is in fact a way to do exactly the same under win32:

    sub adminMe(){ my $adminID = 0; if (not ($adminID eq $<)){ print "U have to be an Administator to do this ...\n"; print "Give me a name of a local Administator:\n"; my $admin = <STDIN>; chomp $admin; my $hostname = hostname; system "runas /user:$hostname\\$admin \"cmd /K perl $whatToDoAsAdmin\""; } }

    ----
    NaSe
    :x

      The Unix approach would be to just die if you are not root (if you are sure you need to be root!) and let the user call su or sudo himself (or the script that is calling your perlscript). You might like su, others don't. (If you are not sure, just go ahead and let the program die when it encounters missing privileges.)

      Windows has a very different concept of users, so of course you won't be able to find a single solution that works for Windows and Unix. For Win95/Win98, you can do whatever you want without changing user. For WinNT/Win2K/WinXP, things are more complicated. I don't think there's a solution for WinNT. For Win2K and WinXP, programs can be executed under different privileges. I don't know how accessible the interface is. It *might* be possible, check CPAN (I didn't see anything, but I just shot a quick glance). But it is definitely more effort than just changing a variable.

      Again, the most straightforward solution is to let the user log in as supervisor, then execute the script.

      UpdateTake a look at Re: Running Perl program w/root privs via cron. It could help you to not have to enter a password for Unix (using sudo).