当scp在此代码中完成后,将出现额外的提示符。我试过几种方法来防止这种情况的发生,但它还是出现了。为了清楚起见,在for循环之后出现两个提示,然后程序继续。
#!/usr/bin/expect
# Set timeout
set timeout 1
# Set the user and pass
set user "user"
set pass "pass"
# Get the lists of hosts, one per line
set f [open "hosts.txt"]
set hosts [split [read $f] "\n"]
close $f
# Get the commands to run, one per line
set f [open "commands.txt"]
set commands [split [read $f] "\n"]
close $f
# Clear console
set clear "clear"
# Iterate over the hosts
foreach host $hosts {
# Establish ssh conn
spawn ssh $user@$host
expect "password:"
send "$pass\r"
# Iterate over the commands
foreach cmd $commands {
expect "$ "
send "$cmd\r"
expect "password:"
send "$pass\r"
}
# Tidy up
# expect "$ "
# send "exit\r"
# expect eof
# send "close"
}
发布于 2018-01-18 20:14:48
因为您的hosts
和commands
列表都以空字符串结尾。用puts [list $hosts $commands]
验证
所以你发送一个空命令,这就是“按回车”。然后等待密码提示,在1秒内超时,然后继续执行程序.
这是由于您读取文件的方式:read
获取文件内容,包括文件的尾换行符。然后,当您在换行符上拆分字符串时,列表将包括尾尾换行符后面的空字符串。
取而代之的是这样做:
set commands [split [read -nonewline $f] "\n"]
# ........................^^^^^^^^^^
请参阅https://tcl.tk/man/tcl8.6/TclCmd/read.htm
你也可以这么做
set f [open "commands.txt"]
while {[gets $f line] != -1} {
# skip empty lines and commented lines (optional)
if {[regexp {^\s*(#|$)} $line]} continue
lappend commands [string trim $line]
}
close $f
https://stackoverflow.com/questions/48328971
复制相似问题