Adam
Adam

Reputation: 1

Using Expect, how do I extract certain value from a file and input into a variable of an Expect script

I have two files. One is called bgp_ip.log and the other is an expect script called bgp.sh

bgp_ip.log contains just one IP address which was input into the file by another script called getip.sh which is working fine.

Now I'm trying to figure out how to get bgp.sh to extract the IP address in bgp_ip.log and place it into a variable container. In this script context, the variable container is called $BGP_IP as shown in the script below:

The reason for having this variable so that the script below is able to execute the Router BGP commands based on the IP address obtained from bgp_ip.log

#!/usr/bin/expect

set username "testaccount"

set password "testaccount"

set hostname "R-KANSAS-01"

set BGP_IP "?????" <<<< I'm not sure how can I extract the IP from bgp_ip.log and place into this variable

spawn telnet "$hostname"

expect "login: " {
  send "$username\n"
  expect "Password: "
  send "$password\n"
  expect "> "

send "show bgp summary instance $BGP_IP\n"

log_file "R-KANSAN-01_temp.log"

log_user 1

expect "#"


send "exit\n"; exit 0

  interact
}

Any help is appreciated..Thanks.

Upvotes: 0

Views: 334

Answers (1)

Dinesh
Dinesh

Reputation: 16446

You need to read the file and get the data from it

set file_name "bgp_ip.log"

set fp [open $file_name "r"]
set BGP_IP [read $fp]
close $fp

The variable BGP_IP will hold the IP address. I am assuming that the file contains only the IP address and nothing else.

If not, then you need regexp to get it.

Just add this code before spawning telnet in your code.

Upvotes: 1

Related Questions