#!/usr/bin/perl use strict; use warnings; use Expect; my $cmd1 = "show version | no-more "; my $access_protocol = 'telnet'; my $router = '172.16.2.1'; my $expect_log_file = 'expect-log-file.txt'; my $timeout = 15; my $username = 'username1'; my $password = 'asdfasdfasdf'; #Uncomment to hide stdout: #$Expect::Log_Stdout = 0; my $exp = Expect->spawn("$access_protocol $router") or die "Can't connect to $router: $!\n"; $exp->expect ($timeout, ['(yes/no)',sub{my $fh = shift; $fh->send("yes\n"); exp_continue;}], ['(sername: )|(ogin: )$',sub{my $fh = shift; $fh->send("$username\n"); exp_continue;}], ['(assword:)$',sub{my $fh = shift; $fh->send("$password\n"); exp_continue;}], ['timeout',sub{&login_error();}], '-re', '> $', #wait for router prompt, then exit expect ); $exp->log_file($expect_log_file); $exp->expect ($timeout, ['',sub{my $fh = shift; $fh->send("$cmd1 \n");}] ); $exp->expect ($timeout, ['More',sub{my $fh = shift; $fh->send(" "); exp_continue}], '-re', '[#>:]$', #wait for router prompt, then exit expect, ); $exp->expect ($timeout, ['',sub{my $fh = shift; $fh->send("exit \n");}] ); sub login_error { print "Unable to login to router $router. Try to login manually with SSH. \n"; exit; } #### perl ./exp_1.pl Trying 172.16.2.1... Connected to 172.16.2.1 (172.16.2.1). Escape character is '^]'. EX3200-J (ttyp1) login: username1 Password: --- JUNOS 12.3R6.6 built 2014-03-13 06:58:47 UTC username1@EX3200-J> show version | no-more Hostname: EX3200-J Model: ex3200-24t JUNOS Base OS boot [12.3R6.6] JUNOS Base OS Software Suite [12.3R6.6] JUNOS Kernel Software Suite [12.3R6.6] JUNOS Crypto Software Suite [12.3R6.6] JUNOS Online Documentation [12.3R6.6] JUNOS Enterprise Software Suite [12.3R6.6] JUNOS Packet Forwarding Engine Enterprise Software Suite [12.3R6.6] JUNOS Routing Software Suite [12.3R6.6] JUNOS Web Management [12.3R6.6] JUNOS FIPS mode utilities [12.3R6.6] username1@EX3200-J>