将文件读入 String 并在 Expect Script 中执行循环 [英] Read file into String and do a loop in Expect Script
问题描述
我想做的是:
- 创建一个
.exp
文件,该文件将从同一目录下的*.txt
文件中读取,并将文本文件中的所有内容解析为一个字符串变量期望脚本. - 循环包含一系列主机名的字符串,并执行一系列命令,直到字符串被枚举.
- Create a
.exp
file, which will read from the*.txt
file from the same directory and parse all the content in the text file into a string variable in the expect script. - Loop the string, which contains a series of host names, and excecute a series of command until the string is enumerated.
那么脚本所做的,就是从同一目录下的一个txt
文件中读取一系列主机名,然后将它们读入一个字符串,然后将.exp
文件将自动登录到每个文件并执行一系列命令.
So what the script does, is read a series of hostname from a txt
file in the same directory, and then read them into a string, and the .exp
file will auto log into each of them and excecute a series of commands.
我编写了以下代码,但它不起作用:
I have the following code written but it's not working:
#!/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
"
expect "host1"
send "$scp
"
expect "host1"
send "exit
"
非常感谢任何帮助....
Any help is greatly appreciated....
推荐答案
代码应该将两个文件的内容读入行列表,然后遍历它们.结果是这样的:
The code should read the contents of the two files into lists of lines, then iterate over them. It ends up like this:
# 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] "
"]
close $f
# Get the commands to run, one per line
set f [open "commands.txt"]
set commands [split [read $f] "
"]
close $f
# Iterate over the hosts
foreach host $hosts {
spawn ssh $user@host
expect "password:"
send "$password
"
# Iterate over the commands
foreach cmd $commands {
expect "% "
send "$cmd
"
}
# Tidy up
expect "% "
send "exit
"
expect eof
close
}
您可以使用一两个工作程序对其进行重构,但这是基本思想.
You could refactor this a bit with a worker procedure or two, but that's the basic idea.
这篇关于将文件读入 String 并在 Expect Script 中执行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!