tiger_groove
tiger_groove

Reputation: 1016

expect script reading empty line

I have a list of IPs that I am looping through to ssh into each of them and capture some logs. Currently, it will loop through all the IPs and do what I want, the issue occurs when it hits the last IP, after it is done with the last line, it attempts to spawn another empty line resulting in an error. (spawn ssh root@)

How can I prevent this error from happening?

myexpect.sh

set user user
set pass pass
set timeout 600

# Get the list of hosts, one per line #####
set f [open "/my/ip/list.txt"]
set hosts [split [read $f] "\n"]
close $f

# Iterate over the hosts
foreach host $hosts {
    spawn ssh $user@$host
    expect {
            "connecting (yes/no)? " {send "yes\r"; exp_continue}
            "assword: " {send "$pass\r"}
    }

    expect "# "
    send "myscript.sh -x\r"
    expect "# "
    send "exit\r"
    expect eof
}

myiplist.txt

172.17.255.255
172.17.255.254
...

error:

[[email protected]: ]# exit  //last ip in the list
Connection to 172.17.255.255 closed.
spawn ssh root@
ssh: Could not resolve hostname : Name or service not known
expect: spawn id exp5 not open

Upvotes: 1

Views: 1413

Answers (1)

glenn jackman
glenn jackman

Reputation: 246932

Text files end with a newline

first line\n
...
last line\n

So when you read the whole file into a variable, then split on newlines, your list looks like this:

{first line} {...} {last line} {}

because there is an empty string after the last newline.

The idiomatic way to iterate over the lines of a file in Tcl/expect is this:

set f [open file r]
while {[gets $f host] != -1} {
    do something with $host
}
close $f

Or, use the -nonewline option of the read command

set f [open file]
set hosts [split [read -nonewline $f] \n]
close $f
foreach host $hosts {...}

Upvotes: 3

Related Questions