期望脚本读取空行
expect script reading empty line
我有一个 IP 列表,我正在循环访问这些 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
或者,使用 the read command
的 -nonewline
选项
set f [open file]
set hosts [split [read -nonewline $f] \n]
close $f
foreach host $hosts {...}
我有一个 IP 列表,我正在循环访问这些 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
或者,使用 the read command
的-nonewline
选项
set f [open file]
set hosts [split [read -nonewline $f] \n]
close $f
foreach host $hosts {...}