0

I have a tcl script to log into devices and print SUCCESS. This is the script:

The file: (the first IP is valid, and can be logged into, the next 3 are fake).

192.38.133.145
178.18.34.48
183.24.56.3
145.234.67.145

The script:

#!/bin/expect
package require Expect

set file [open "hosts" r]
set f_data [read $file]
set data [split $f_data "\n"]

foreach host $data {
set timeout 8
    if {$host > 0} {
                ## GETS THE HOST IP##
                set host_ip $host

                ##LOGS INTO THE DEVICE##
                spawn ssh test@$host_ip
                expect {
                        "password:" {
                                puts "SUCCESS"
                        } timeout {
                                puts "Could not connect to host: ${host_ip}"
                                #break
                        }

                }
        send "password\r"
        expect ">"
        send "en\r"
        }
}

If I do not include the break, I get the message could not connect to host, but instead of looping to the next host, it sends "en\r". when I do include the break, it gives the message that it cannot reach the host (the second IP, which is expected) and the script ends there (it does not process the 3rd IP). How do I cannot seem to get it to process the 3rd and 4th IPs. I used the method suggested by potrzebie in this thread: TCL: loops How to get out of inner most loop to outside? and still cannot get it to work

Community
  • 1
  • 1
user2883071
  • 960
  • 1
  • 20
  • 50

1 Answers1

1

break should work. The expect man page has this to say in the documentation for the expect command:

Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way.

I'd write your loop like this:

foreach host $data {
    # very basic data validation: an ipv4 address contains some dots
    if {[string match {*.*.*.*} $host]} {
        spawn ssh test@$host
        expect {
            "password:" {
                puts "SUCCESS"
                send "password\r"
                exp_continue
            } 
            timeout {
                puts "Could not connect to host: $host"
                continue
            }
            ">" {
                # I see a prompt. Fall out of this "expect loop"
            }
        }
        send "en\r"
        expect ">"

        # do something to close the connection
        send "exit\r"
        expect eof
    }
}
user2883071
  • 960
  • 1
  • 20
  • 50
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • It still does not consider the last 2 ip addresses. It logs into the first device. Then it spawns the ssh to the second device, it gives the message: `could not connect to host`, and then it ends. It does not spawn an ssh to the other 2 (last) IP addresses on the list. – user2883071 Mar 11 '15 at 18:46