8

我想做的是:

  1. 创建一个.exp文件,该*.txt文件将从同一目录中读取文件并将文本文件中的所有内容解析为期望脚本中的字符串变量。
  2. 循环字符串,其中包含一系列主机名,并执行一系列命令,直到字符串被枚举。

所以脚本的作用是从同一目录下的文件中读取一系列主机名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"

任何帮助是极大的赞赏....

4

3 回答 3

18

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

# 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
}

您可以使用一两个工作程序对其进行一些重构,但这是基本思想。

于 2013-07-17T10:35:26.367 回答
5

我会重构一下:

#!/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
于 2013-07-15T19:50:10.463 回答
1

使用此处的两种解决方案中的任何一种,我还将创建一个日志文件,您可以稍后查看。使脚本运行后的任何问题的故障排除变得容易,尤其是在您配置数百台主机时。

添加:

log_file -a [日志文件名]

在你的循环之前。

干杯,

ķ

于 2015-04-24T16:07:25.677 回答