将文件读入String并在Expect Script中执行循环

时间:2013-07-15 19:35:36

标签: shell unix loops tcl expect

我想做的是:

  1. 创建一个.exp文件,该文件将从同一目录中的*.txt文件中读取,并将文本文件中的所有内容解析为expect脚本中的字符串变量。
  2. 循环包含一系列主机名的字符串,并执行一系列命令,直到枚举该字符串。
  3. 所以脚本的作用是从同一目录中的txt文件读取一系列主机名,然后将它们读成字符串,.exp文件将自动登录到每个他们并且执行了一系列命令。

    我编写了以下代码,但它无效:

    #!/usr/bin/expect
    
    set timeout 20
    set user test
    set password test
    
    set fp [open ./*.txt r]
    set scp [read -nonewline $fp]
    close $fp
    
    spawn ssh $user@$host
    
    expect "password"
    send "$password\r"
    
    expect "host1"
    send "$scp\r"
    
    expect "host1"
    send "exit\r"
    

    非常感谢任何帮助......

3 个答案:

答案 0 :(得分:14)

代码应该将两个文件的内容读入行列表,然后迭代它们。它最终是这样的:

# Set up various other variables here ($user, $password)

# Get the list of hosts, one per line #####
set f [open "host.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

# Iterate over the hosts
foreach host $hosts {
    spawn ssh $user@host
    expect "password:"
    send "$password\r"

    # Iterate over the commands
    foreach cmd $commands {
        expect "% "
        send "$cmd\r"
    }

    # Tidy up
    expect "% "
    send "exit\r"
    expect eof
    close
}

你可以用一两个工人程序重构一下,但这是基本的想法。

答案 1 :(得分:3)

我有点重构:

#!/usr/bin/expect

set timeout 20
set user test
set password test

proc check_host {hostname} {
    global user passwordt

    spawn ssh $user@$hostname
    expect "password"
    send "$password\r"
    expect "% "                ;# adjust to suit the prompt accordingly
    send "some command\r"
    expect "% "                ;# adjust to suit the prompt accordingly
    send "exit\r"
    expect eof
}

set fp [open commands.txt r]
while {[gets $fp line] != -1} {
    check_host $line
}
close $fp

答案 2 :(得分:1)

在这里使用这两个解决方案中的任何一个,我还会创建一个日志文件,您可以在以后查看。在脚本运行后,可以轻松解决任何问题,尤其是在配置数百台主机时。

添加:

  

log_file -a [日志文件名]

在你的循环之前。

干杯,

ķ