From: Bruno N. <bn...@gm...> - 2007-07-13 20:08:24
|
Hello guys, I'm developing a perl module to login and execute commands via ssh using Expect. It's already on CPAN: http://search.cpan.org/~bnegrao/Net-SSH-Expect-0.08/lib/Net/SSH/Expect.pm<http://search.cpan.org/%7Ebnegrao/Net-SSH-Expect-0.08/lib/Net/SSH/Expect.pm> I'm facing some problems that i don't understand. Now i have a case where i need to send an extra "\n" character to make the prompt reapear after sending a some specific commands, not all. I did a simple script that exemplifies this behaviour. The script bellow is called ssh.pl. The usage is ssh.pl host username password It will login via ssh on host and execute the same four commands 100 times. The problem is shown in the line: $spawn->send("ps\n\n"); # NEEDS TWO \N\N HERE OR THE PROMPT DOESN'T RETURN!! WHY???? I simply don't understand why after sending a "ps\n" the prompt on the remote server doesn't appear, what makes it unavailable for the next command in the loop. But, for example, after sending a "who am i\n", one \n is enough to make the prompt reapear. Can you explain this phenomenon for me? Regards, bruno #!/usr/bin/perl # ssh.pl # ssh to a server and execute 4 commands in a loop, only to test Expect. # usage # ssh.pl host username password if( ! defined $ARGV[0] ) { print "Usage: ssh.pl <host> <username> <password> \n"; exit; } my ($host, $username, $password) = @ARGV; $username = $ENV{USER} if $username eq ""; #!/usr/bin/perl # ssh to a server and execute 4 commands in a loop, only to test Expect. # if( ! defined $ARGV[0] ) { print "Usage: ssh.pl <host> <username> <password> \n"; exit; } my ($host, $username, $password) = @ARGV; $username = $ENV{USER} if $username eq ""; use Expect; #use IO::Pty; my $spawn = new Expect; $spawn->raw_pty(1); $spawn->exp_internal(0); $spawn->spawn("ssh $username\@$host") or die $!; $spawn->log_stdout(0); my $ret = $spawn->expect(10, [ qr/\(yes\/no\)\?\s*$/ => sub { $spawn->send("yes\n"); exp_continue; } ], [ qr/assword:\s*$/ => sub { $spawn->send("$password\n") if defined $password; } ], [ qr/ogin:\s*$/ => sub { $spawn->send("$username\n"); exp_continue; } ], [ qr/REMOTE HOST IDEN/ => sub { print "FIX: .ssh/known_hosts\n"; exp_continue; } ], ); while ($spawn->expect(1, '-re', qr/[\s\S]+/)){ #swallow any output the server throws after loging in } my $PROMPT = 'SSH_PROMPT>> '; $spawn->send("PS1='$PROMPT'\n"); for (my $i = 100; $i > 0; $i--) { if ($spawn->expect(3, -re, qr/$PROMPT$/)) { print $spawn->before(); $spawn->send("df -m /\n"); } else { exit $i; } if ($spawn->expect(3, $PROMPT)) { print $spawn->before(); $spawn->send("ls -l /bin/ls\n"); } else { exit $i; } if ($spawn->expect(3, $PROMPT)) { print $spawn->before(); $spawn->send("who am i\n"); } else { exit $i; } if ($spawn->expect(3, $PROMPT)) { print $spawn->before(); $spawn->send("ps\n\n"); # NEEDS TWO \N\N HERE OR THE PROMPT DOESN'T RETURN!! WHY???? } else { exit $i; } print ("\n\n$i $i $i $i $i $i $i $i $i $i $i\n\n"); } exit; |