scp完成后出现其他提示

时间:2018-01-18 19:31:51

标签: unix expect scp

在此代码中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"
}

1 个答案:

答案 0 :(得分:1)

因为hostscommands列表都以空字符串结尾。使用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