scp 完成后出现的附加提示
Additional prompt appearing after scp completes
此代码中的 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"
}
因为您的 hosts
和 commands
列表都以空字符串结尾。用 puts [list $hosts $commands]
验证
所以你发送了一个空命令,就是"hitting enter"。然后你等待密码提示,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
此代码中的 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"
}
因为您的 hosts
和 commands
列表都以空字符串结尾。用 puts [list $hosts $commands]
所以你发送了一个空命令,就是"hitting enter"。然后你等待密码提示,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