I am new to Expect and scripting in general. I am trying to make a few scripts to make my life a bit easier when pulling network device configurations. I managed to create a
This is a Perl version for this issue:
Install instruction:
cpan Expect
This script works perfectly for my needs.
Parameter 1: Connection string (example: admin@10.34.123.10)
Parameter 2: Clear text password
Parameter 3: Command to execute
#!/usr/bin/perl
use strict;
use Expect;
my $timeout = 1;
my $command = "ssh " . $ARGV[0] . " " . $ARGV[2];
#print " => $command\n";
my $exp = Expect->spawn($command) or die "Cannot spawn $command: $!\n";
$exp->raw_pty(1);
LOGIN:
$exp->expect($timeout,
[ 'ogin: $' => sub {
$exp->send("luser\n");
exp_continue;
}
],
[ 'yes\/no\)\?\s*$' => sub {
$exp->send("yes\n");
goto LOGIN;
}
],
[ 'assword:\s*$' => sub {
$exp->send($ARGV[1]."\n");
#print "password send: ", $ARGV[1];
exp_continue;
}
],
'-re', qr'[#>:] $'
);
$exp->soft_close();
Or use set ip [gets stdin]
to the IP address from the user input.
For example,
puts "Enter your IP address\n"
set ip [get stdin]
Use this in spawn
. We can do the same for multiple IP addresses using a loop -
spawn ssh $ip -l admin
I would do this (untested):
#!/usr/bin/expect -f
set logfile "/home/text.cfg[clock format [clock seconds] -format %Y%m%d]"
close [open $logfile w] ;# truncate the logfile if it exists
set ip_file "list.txt"
set fid [open $ip_file r]
while {[gets $fid ip] != -1} {
spawn ssh $ip -l admin
expect "Password:"
send "password\r"
expect "admin@"
send "set cli pager off\r"
log_file $logfile
send "show config running\r"
expect "admin@"
log_file
send "exit\r"
expect eof
}
close $fid
Notes:
\r
to simulate hitting enter when you send
commands.expect eof
after you send "exit"A possibility is to pass the IP address as a parameter in your Expect script:
set host_ip [lindex $argv 0]
and then make a shell script, calling your Expect script inside a while
loop:
ips_file="list.txt"
while read line
do
your_expect_script line
done < $ips_file