#!/usr/bin/perl use strict; use warnings; use Getopt::Long qw(GetOptions); use Expect; use Net::OpenSSH; use Log::Log4perl qw(:easy); #Initializing the log file.. my $log_file = "/tmp/linux_cmd_execute_".$id.".log"; Log::Log4perl->easy_init( { level => $INFO, file => "> $log_file", } ); INFO( "expect usage user - $user host - $host , fuser - $fuser , cmd - $cmd "); my $start_time = time(); INFO("ssh to the host $host"); my $ssh = Net::OpenSSH->new("$user:$pswd\@$host"); if($ssh->error) { print "Unable to connect $host " . $ssh->error; exit; } my $expect; my ( $pty, $pid ) = $ssh->open2pty( { stderr_to_stdout => 1 }, "sudo su - $fuser" ) or die "Failed to attempt sudo su - $fuser"; $expect = Expect->init($pty); $expect->exp_internal(1); $expect->log_file("/tmp/expect.log", "w"); my $before; my $exit1; my $output; my $result = $expect->expect( undef, [ "\[\r\n]?\[^\r\n]+\[%#>\$] \$", sub { my $self = shift; INFO("Sending command $cmd"); $self->send("ls \r"); } ] ) or custom_error( "Expect Failed ",$id); $expect->hard_close(); exit 0;