Expect 脚本是 运行 只有一个命令并显示错误

Expect script is running only one command and displays an error

脚本:

#!/usr/bin/expect
set username "sv111111"
set password "Sandy789"
set f [open "servers.txt"]
set hosts [split [read $f] "\n"]
close $f
foreach host $hosts {
#spawn ssh -o StrictHostKeyChecking=no $username@$hosts
spawn ssh $username@$host
expect "$username@$host's password:"
send -- "$password\n"
expect "$"
send -- "sudo -u sandy /opt/sandy/ship/common/tools/arpq.sh\n"
expect "$username@$host's password:"
send -- "$password\n"
expect "$"
send -- "sudo -u sandy /opt/sandy/ship/common/tools/showps2.pl\n"

expect "$"
send -- "exit\n"
expect eof
close
}

在上面的脚本中,它完美地为 servers.txt 文件中提到的所有服务器运行了第一个 sudo 命令。第二个 sudo 命令未执行并显示以下错误。

spawn ssh sv111111@
ssh: : Name or service not known
send: spawn id exp10 not open
    while executing
"send -- "$password\n""
    ("foreach" body line 5)
    invoked from within
"foreach host $hosts {
#spawn ssh -o StrictHostKeyChecking=no $username@$hosts
spawn ssh $username@$host
expect "$username@$host's password:"
send -- ..."
    (file "./sandy_try.sh" line 8)

请帮忙

read 命令抓取文件内容 并带有尾随换行符 。然后,当您按换行符拆分时,列表有一个尾随元素,它是一个空字符串。使用其中之一:

set f [open "servers.txt"]
set hosts [split [read -nonewline $f] "\n"]
# .....................^^^^^^^^^^
close $f
foreach host $hosts { ...

set f [open "servers.txt"]
while {[gets $f host] != -1} {
    spawn ssh ...
}
close $f