Ssh 期望脚本读取空行

Ssh 期望脚本读取空行,ssh,expect,Ssh,Expect,我有一个IP列表,我通过ssh循环到每个IP中,并捕获一些日志。目前,它将循环通过所有IP并执行我想要的操作,问题发生在它到达最后一个IP时,在最后一行完成后,它尝试生成另一个空行,导致错误。(spawn ssh root@) 如何防止发生此错误 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.

我有一个IP列表,我通过ssh循环到每个IP中,并捕获一些日志。目前,它将循环通过所有IP并执行我想要的操作,问题发生在它到达最后一个IP时,在最后一行完成后,它尝试生成另一个空行,导致错误。(
spawn ssh root@

如何防止发生此错误

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
...
错误:

[root@172.17.255.255: ]# 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

文本文件以换行符结尾

first line\n
...
last line\n
因此,当您将整个文件读入一个变量,然后在换行符上拆分时,您的列表如下所示:

{first line} {...} {last line} {}
因为最后一行换行后有一个空字符串

在Tcl/expect中迭代文件行的惯用方法是:

set f [open file r]
while {[gets $f host] != -1} {
    do something with $host
}
close $f
或者,使用的
-nonewline
选项


我想这里已经回答了这个问题:此外,我通常认为使用
expect+ssh
是一种痛苦。你可能想试试Ansible这样的工具,它会让你的生活更轻松。谢谢你,我使用了
-nonewline
,它工作起来很有魅力!
set f [open file]
set hosts [split [read -nonewline $f] \n]
close $f
foreach host $hosts {...}