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

Hi, My application runs on v5.10.1 and Expect.pm v1.21. My perl script (scriptA) is trying to run another script (scriptB) as user root using Expect. As scriptB is inetractive, I've set $exp->interact. However, once scriptB has teminated, it will stay logged in as user root instead of returning to the calling user.
my $timeout = 5; my $exp = Expect->new; $exp->raw_pty(1); $exp->spawn("su root"); $exp->log_stdout(0); $exp->expect($timeout, [ '-re', 'Password:\s*$' => sub { $exp->send("admin\n"); } ], [ timeout => sub { die "Timeout" } ], ); #waiting for #[root@ana-02 ~]# $exp->expect($timeout, [ '-re', '\][#%]\s*$' => sub {} ], [ timeout => sub { die "Timeout, no prompt" } ], ); $exp->log_stdout(1); my $result = $exp->send("dummy.pl\n"); { #Ignoring :: IO::Stty not installed, cannot change mod +e at test.pl line 22 local $SIG{__WARN__} = sub { my $warn = shift; if ($warn !~ /IO::Stty/) { print STDERR $warn; } }; $exp->interact(); } $exp->log_stdout(0); $exp->expect($timeout, [ '-re', '\][#%]\s*$' => sub { $exp->send(" exit\n"); } ], [ timeout => sub { die "Timeout" } ], ); $exp->soft_close(); my $status = $exp->exitstatus; print "$status\n";
(The "exit" command isnt beint called); how can I disable/turn off the interact mode, so I can logoff root and return to my calling script? Thanks Daphna

Replies are listed 'Best First'.
Re: Switching to non/interactive mode with Expect.pm
by almut (Canon) on May 03, 2010 at 15:18 UTC
    As scriptB is interactive, I've set $exp->interact.

    You'll have to somehow find a way to quit the requested interactive mode of the root shell, either by interactively typing "exit", or putting the exit on the same line right after the dummy.pl:

    my $result = $exp->send("dummy.pl ; exit\n");

    or by replacing the shell process with dummy.pl, in which case the end of the su-session will be when the Perl program ends.   I.e., try to exec the command  (works for me):

    my $result = $exp->send("exec dummy.pl\n");

    Alternatively, you might also just use sudo to run the command (with NOPASSWD configured for whoever is supposed to run the command - see 'man sudoers' for details) — which would also be preferable from a security point of view...

      Thanks!! it works of course.