在处理一行后,期望脚本在while循环内部运行

时间:2016-08-31 23:50:14

标签: bash while-loop expect

我有一个while循环:

#!/bin/bash

doit="/pathtocommand"
file="/pathtosourcefile"

while read -r username password; do

$doit "$username" "$password"

done < $file

我的while循环命令($ doit)是一个期望脚本。

#!/usr/bin/expect -f 

## Set up variables to be passed in as command line arguments
#set username [lindex $argv 0];
#set password [lindex $argv 1];
lassign $argv username password

spawn telnet 192.168.100.101 106
expect "200 PWD Server ready"    
send "USER user\r"
expect "300 please send the PASS"
send "PASS password\r"
expect "200 login OK, proceed"

## Use the line below for passwords that do not have to be enclosed    with quotes
send "SETACCOUNTPASSWORD $username PASSWORD $password\r"

# Use the line below for a password that must be quoted ie one that    contains a $ or a ! by escaping the double quotes
#send "SETACCOUNTPASSWORD $username PASSWORD \"$password\"\r"

expect "200 OK"
send "quit\r"
interact

expect脚本的运行次数应与我文件中的行数一样多。但它在第一行处理后停止。我相信它在expect脚本中的某些东西,因为将命令更改为echo之类的东西。

如果我调试脚本,我会看到:

+ doit=/pathtocommand
+ file=/pathtofile
+ read -r username password
+ /pathtofile 0100    01000100
spawn telnet 192.168.100.101 106
Trying 192.168.100.101...
Connected to 192.168.100.101.
Escape character is '^]'.
200 PWD Server ready  
USER user
300 please send the PASS
PASS pass
200 login OK, proceed
SETACCOUNTPASSWORD 0100 PASSWORD 01000100
200 OK
quit
+ read -r username password

在我看来,脚本试图重新开始,然后只是退出。有人可以帮忙吗?我迫不及待地想让这件事情发挥作用。我之前用SSH做过这个没问题。不确定它是telnet还是什么。

1 个答案:

答案 0 :(得分:2)

Expect脚本中的interact命令从标准输入读取。由于标准输入被重定向到文件,expect将从文件中读取,并且下一次没有任何东西可以让shell的while循环读取。< / p>

如果您希望expect与终端进行互动,则应将其输入重定向回/dev/tty

$doit "$username" "$password" </dev/tty