Description: |
If you have ever used Expect to execute commands on a remote system I am sure you have run into the problem of parsing the command output from the output of the Expect methods exp_before(), clear_accum(), etc... . If you send your command to this subroutine it will parse the output for you and return the command output as it would be returned from a backtick execution.
Note: This subroutine uses a global Expect object variable which already has an established connection. The subroutine will not take commands that end in & .. for those commands just use $expect->print method. |
# Executes a command via a global expect object and
# returns the output of the command.
#
# Arguments:
# 1 - Command <string variable containing the command string
+>
# Returns:
# String variable cotaining the output of the specified command.
#
sub expect_execute($) {
$expect->clear_accum();
my $command = shift;
my $x = '';
my $temp = '';
if ( $command =~ /;$/ ) {
chop( $command );
}
print $expect "$command | sed 's/^/COMMAND_OUT: /g'; echo -n E
+ND_; echo EXPECT\n";
$expect->expect( 300, -re => '^END_EXPECT' );
my $result = $expect->exp_before();
( my @result ) = split( /\n/, $result );
$result = '';
foreach $x ( @result ) {
$temp = $x;
if ( chop( $temp ) eq "\r" ) {
chop( $x );
}
if ( $x =~ m/^COMMAND_OUT: / ) {
$temp = substr( $x, 13 );
$result = $result . $temp . "\n";
}
}
return $result;
}