in the below code I am not able to print anything except whatever is in the 
$pty.  I want to print LINE_START: in the beginning of each line of the output, 
but it does not print that, it only prints what the output of the exceuted 
command produced. why is that so?

    while(<$pty>) {

         print "LINE_START: $. $_";
    }



I am suspecting it has something to do with select STDOUT; $| = 1;, but i dont 
know what.

complete code:

#!/usr/bin/perl
use strict;
use warnings;
use Net::OpenSSH;
use Expect;

select STDOUT; $| = 1;
select STDERR; $| = 1;

my $password = $ARGV[0];
my $target = $ARGV[1];
my $runas = $ARGV[2]; 
my $cmd = $ARGV[3];
my $timeout = 20;
my $debug = 0;

my $ssh = Net::OpenSSH->new($target,
                        user => 'abcd',
                        password => $password,
                        master_opts => [-o => 'StrictHostKeyChecking=no',
                                             -o => 'ConnectTimeout 60']
                        );
my $sshExitCode = $ssh->error;
if ($sshExitCode eq "0") {
    my $ostype= $ssh->capture("uname -s");chomp($ostype);
    my $sudo_path=$ssh->capture("which sudo");chomp($sudo_path);
    my $su_path=$ssh->capture("which su"); chomp($su_path);
    
    if($sudo_path=~m/no sudo/){
        if ($ostype eq "Linux"){
            $sudo_path="/usr/bin/sudo";
        } else{
            $sudo_path="/usr/local/bin/sudo";
        }
    }

    my ($pty, $pid) = $ssh->open2pty("$sudo_path -k; $sudo_path $su_path - 
$runas -c \"$cmd\"")
         or die "open2pty failed: " . $ssh->error . "\n";

    my $expect = Expect->init($pty);
    $expect->raw_pty(1);
    $expect->expect($timeout, ':') or die "expect failed\n";
    $expect->send("$password\n");
    $expect->expect($timeout, "\n") or die "bad password\n";


    while(<$pty>) {
         print "$. $_";
    }
} else {
    exit $sshExitCode;
}

Reply via email to