Search code examples
bashloopswhile-looptelnetexpect

bash/expect/loop - how to loop a simple bash script doing telnet


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.


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