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

Ton*_*ony 7 unix shell loops tcl expect

我想做的是:

  1. 创建一个.exp文件,该*.txt文件将从同一目录中的文件中读取,并将文本文件中的所有内容解析为expect脚本中的字符串变量.
  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"
Run Code Online (Sandbox Code Playgroud)

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

Don*_*ows 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
}
Run Code Online (Sandbox Code Playgroud)

您可以使用一两个工作程序重构一下,但这是基本的想法.


gle*_*man 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
Run Code Online (Sandbox Code Playgroud)