use strict; use warnings; use Expect; my $login = "xxx"; my $pass = "xxx2"; my $test_dir = "/foo/bar/"; my $cmd = "if [ -d $test_dir ]; then echo DIR_EXIST:1; else echo DIR_EXIST:0; fi"; my $timeout = 30; my $ex = Expect->new('ssh','-t',"$login\@hostname",$cmd); # the -t forces TTY allocation, helpful for Expect! $ex->expect( $timeout, [ qr/password:\s*$/i => sub { $ex->send($pass,"\n"); return 1; } ], [ timeout => sub { warn "Timeout waiting for password prompt"; return 1; } ], ); $ex->expect ( $timeout, [ qr/DIR_EXIST:\d/ => sub { print "Result: ",$ex->match(); } ], );