Question

I would like to run this script in a loop.

What is needs to do is read a file with in that file IP addresses like:

10.0.0.0
10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4

And run this script on every ip listed above here.

This is what i have:

#!/usr/bin/expect

spawn telnet 10.0.0.0
expect "User Name :"
send "username\r"

expect "Password  :"
send "password\r"
expect ">"
send "4\r"
expect "*#"
exit

How do i get the script above working every IP in a txt file.

Was it helpful?

Solution

You can read the file within your expect script.

Open the file and assign the file descriptor to a variable, read each line and execute the above code you wrote.

set fildes [open "myhosts.txt" r]
set ip [gets $fildes]
while {[string length $ip] > 0} {

    spawn telnet $ip
    expect "User Name :"
    send "username\r"

    expect "Password  :"
    send "password\r"
    expect ">"
    send "4\r"
    expect "*#"
    exit
    set ip [gets $fildes]
}
close $fildes

OTHER TIPS

I'm not an expert with expect, but the first thing you need to do is change your expect script to accept arguments. It should work like this (looks like you'll need -f in #!/usr/bin/expect):

#!/usr/bin/expect -f

set ip [lindex $argv 0]
spawn telnet $ip
...

Then you can simply iterate over the list of your IPs in your bash script:

while read ip ; do
    myExpectScript $ip
done < list_of_ip.txt

This is just a comment on @user3088572's answer. The idiomatic way to read a file line by line is:

set fildes [open "myhosts.txt" r]
while {[gets $fildes ip] != -1} {
    # do something with $ip
}
close $fildes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top