我想要做的是:
.exp
文件,将从 *.txt
中读取文件,并将文本文件中的所有内容解析为expect脚本中的字符串变量。 所以脚本的作用是从
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"
任何帮助是极大的赞赏....
最佳答案
代码应该将两个文件的内容读入行列表,然后遍历它们。它最终是这样的:
# 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
}
您可以使用一两个工作程序对其进行重构,但这是基本思想。
关于shell - 将文件读入 String 并在 Expect Script 中执行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662391/