in reply to Running a perl script with root, changing to another user and then back to root?

Hello morthed,

Welcome to the Monastery. Well a quick and dirty solution could be to ssh as root do what ever you want exit and continue.

Well ssh might not be the best option what about the Sudo module? You can write a small script to be executed by root. Sample of code:

#!/usr/bin/perl use Sudo; use strict; use warnings; my $su; my $name = "root"; my $pass = "password"; $su = Sudo->new( { sudo => '/usr/bin/sudo', #sudo_args => '...', username => $name, password => $pass, program => '/home/tinyos/Monks/sample.pl', #program_args => '...' } ); my $result = $su->sudo_run(); if (exists($result->{error})) { printf "STDERR: %s\n",$result->{error}; } else { printf "STDOUT: %s",$result->{stdout} if $result->{stdout}; printf "STDERR: %s",$result->{stderr} if $result->{stderr}; } print $ENV{USER}."\n"; __END__ $ perl test.pl STDOUT: root tinyos

In the sample.pl script:

#!/usr/bin/perl use strict; use warnings; print $ENV{USER}."\n";

Hope this helps, BR.

Seeking for Perl wisdom...on the process of learning...not there...yet!

Replies are listed 'Best First'.
Re^2: Running a perl script with root, changing to another user and then back to root?
by morthed (Novice) on Feb 15, 2018 at 14:40 UTC
    Could you please elaborate on that? ssh in the sub script, or ssh in the main script? Right now the main script *runs* as root since the start but after switching is stuck or either using it's privileges to check stuff.. but I need to use another user's priv. to check (that's the entire job :) )

      Hello again morthed,

      You can ssh from the main script as root then in apply the commands that you want, close the session and continue as normal user.

      Check also the updated proposed solution that I just added.

      Hope this helps, BR.

      Seeking for Perl wisdom...on the process of learning...not there...yet!