aztlan667 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I have a problem which has been stumping me for a while. I need to be able to login to a remote machine, escalate privileges using su, and then run an arbitrary command as root on the remote machine. I'm using Net::OpenSSH and Expect to supply the root password, but I'm still not able to get it working. Here's the code I have so far:

my $ssh = Net::OpenSSH->new($remote_host); my $command = 'remote privileged command'; my $root_pw = 'IamNotTheRealPassword'; my ($pty, $pid) = $ssh->open2pty({stderr_to_stdout => 1}, 'su', '-') + or die "Can't open PTY: $!\n"; my $expect = Expect->init($pty); $expect->expect(10, [qr/assword/ => sub { shift->send("$root_pw"); }] ) or die "Timed out\n"; $expect->raw_pty(1); $expect->spawn($command) or die "Can't execute command $command: $!\ +n"; $expect->expect(2); my $out = $expect->before();

Obviously, I'm doing something wrong with Expect because its running the command on the local machine, not the remote one. Is there something obvious I'm missing? I've gone through both the Net::OpenSSH docs and the Expect docs but I can't seem to figure it out. Any help would be greatly appreciated!

Replies are listed 'Best First'.
Re: Using Net::OpenSSH to su commands
by salva (Canon) on Mar 01, 2014 at 09:33 UTC
    Instead of using spawn, you have to send the command you want to run to the remote shell via its stdin channel:
    $expect->send("$command\n");

    A better approach is to tell su to run the command directly using the -c flag:

    my ($pty, $pid) = $ssh->open2pty({stderr_to_stdout => 1}, 'su', '-c', +$command) or die "Can't open PTY: $!\n";

      Thanks for the replies. Yes, I wound up using su -c $command and got it to work. I'm still trying to figure out a good way of getting the exit status. $object->exitstatus doesn't seem to be giving me anything useful. But at least its working!

Re: Using Net::OpenSSH to su commands
by vinoth.ree (Monsignor) on Mar 01, 2014 at 03:45 UTC