For循环在期望脚本中不起作用

For loop not working in expect sript

我已经编写了一个 expect 脚本来使用 ssh 登录到另一台服务器。但是,当我想使用 for 循环对多个服务器执行相同操作时,它不起作用。 以下是脚本:

    #!/usr/bin/expect
    match_max 5000
set expect_out(buffer) {}

for i in `cat node_list.txt`
do

node_ip=`echo $i| awk -F"," '{print }'`
node_initial_pwd=`echo $i| awk -F"," '{print }'`

spawn ssh root@$node_ip

expect {
"*(yes/no)?" {send "yes\r";exp_continue}
"'s password:" {send "$node_initial_pwd\r";exp_continue}
"*current*" {send "$node_initial_pwd\r";exp_continue}
"Enter*" {send "Jan2016!\r";exp_continue}
"Retype*" {send "Jan2016!\r";exp_continue}
"\$" { puts "matched prompt"}
}

done
node_list.txt 的 IP 和密码用逗号 (,) 分隔。

我得到的错误是:

mayankp@mayankp:~/scripts/new$ ./connect-to-server.sh
invalid command name "i"
while executing
"i"
("for" initial command)
invoked from within
"for i in `cat node_list.txt`"
(file "./connect-to-server.sh" line 6)

你能帮我实现这个目标吗?我知道我混淆了 bash 和 expect 在这里,但我不知道如何 运行 for loop in expect.

正如您所说,您在这里混淆了 shell 和 Expect 语法。 Expect 基于 Tcl,通用语言命令的文档可以在 http://www.tcl.tk/man/tcl/TclCmd/contents.htm .

找到

您尝试编写的循环的未经测试的粗略翻译是

set inputchannel [open node_list.txt]

while {[gets $inputchannel line] != -1} {
    set fields [split $line ,]
    set node_ip [lindex $fields 0]
    set node_initial_pwd [lindex $fields 1]

    spawn ssh root@$node_ip

    ...etc...
}