Search code examples
tclexpect

how to access nth element of array in a expect script where n is a command line arg


I am trying to automate vpn login using expect script. I intend to choose a vpn address from a list of addresses as same address doesn't work all the time. I have this right now:

cat connect_script

#!/usr/bin/expect -f

# example-vpn1.com
# example-vpn2.com
# example-vpn3.com

spawn /opt/cisco/anyconnect/bin/vpn connect example-vpn1.com

expect {
    "Username:*" {
        sleep 1
        send "username\r"
        exp_continue
    } 
    "Password:" {
        sleep 1
        send "password\r"
        exp_continue
    } 
}

This works fine but often example-vpn1.com will stop working, so i will manually change example-vpn1.com to example-vpn2.com

I want to create an array like

vpnaddr = [example-vpn1.com, example-vpn2.com, example-vpn3.com]

and then send a command-line argument

e.g. connect_script 0 or connect_script 1

such that vaddr[0] or vaddr[1] is used to connect to vpn in expect script.

Something like below code.

#!/usr/bin/expect -f

set vpnaddr [list example-vpn1.com example-vpn2.com example-vpn3.com]

set IDX [lindex $argv 0]

spawn /opt/cisco/anyconnect/bin/vpn connect vpnaddr[IDX]

expect {
    "Username:*" {
        sleep 1
        send "username\r"
        exp_continue
    } 
    "Password:" {
        sleep 1
        send "password\r"
        exp_continue
    } 
}

what is the correct way to do vpnaddr[IDX] here?


Solution

  • What you are calling an array is a Tcl list. Using correct terms is important because a Tcl array is something different.

    Use the lindex command to get an item from a list, not square brackets. Instead of vpnaddr[IDX], you need to do [lindex $vpnaddr $IDX].