Skip to main content
2 of 2
Formatted text.
Paulo Tomé
  • 3.9k
  • 6
  • 28
  • 40

Unix Shell script using expect

I am new to using expect. I am running the below code to get the token from a server:

set timeout 20

set token ""

sleep 1

spawn ssh -l $serveruser1 $serverip

# -- is used to disable the interpretion of flags by Expect.
expect {
    -re "OK"        {
        send_user "** Enter command to get the token. **\n"
        send -- "-t $switchtype -s h -c \[Long_CLLI:$switchname\] -u $switchuser -l auto-sarm -e n \r"
    }
    timeout {
        send_user "** Session timeout on $serverip upon LOGIN**\n"
        exit -1
    }
}

sleep 1


expect {
    -indices -re "\n.+\n(.+\@)" {
        set token $expect_out(1,string)
        send_user "**Get the token $token **\n"}
    timeout {
        send_user "** Session timeout upon getting token**"
        exit -1}
}

The code is working fine for most of the switches, however for few it is failing by returning code RE006. Therefore, for those switches I need to change the switch type. I have made the below change:

set timeout 60

set token ""

sleep 1

spawn ssh -l $serveruser1 $serverip

# -- is used to disable the interpretion of flags by Expect.
expect {
    -re "OK"        {
        send_user "** Enter command to get the token. **\n"
        send -- "-t $switchtype -s h -c \[Long_CLLI:$switchname\] -u $switchuser -l auto-sarm -e n \r"
    }
    timeout {
        send_user "** Session timeout on $serverip upon LOGIN**\n"
        exit -1
    }
}

sleep 1

expect {
    -re "RE006"        {
        send_user "** Enter command to get the token. **\n"
        send -- "-t $switchtype1 -s h -c \[Long_CLLI:$switchname\] -u $switchuser -l auto-sarm -e n \r"
    }
    timeout {
        send_user "** Session timeout on $serverip upon LOGIN**\n"
        exit -1
    }
}

expect {
    -indices -re "\n.+\n(.+\@)" {
        set token $expect_out(1,string)
        send_user "**Get the token $token **\n"}
    timeout {
        send_user "** Session timeout upon getting token**"
        exit -1}
}

Now, this works fine for the previously failed switches. How can I handle both cases?