bash / expect / loop - 如何循环执行telnet的简单bash脚本

时间:2013-12-12 08:18:27

标签: bash loops while-loop telnet expect

我想循环运行这个脚本。

需要做的是在该文件中读取一个文件IP地址,如:

10.0.0.0
10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4

并在上面列出的每个ip上运行此脚本。

这就是我所拥有的:

#!/usr/bin/expect

spawn telnet 10.0.0.0
expect "User Name :"
send "username\r"

expect "Password  :"
send "password\r"
expect ">"
send "4\r"
expect "*#"
exit

如何让上面的脚本处理txt文件中的每个IP。

3 个答案:

答案 0 :(得分:3)

您可以在期望的脚本中阅读该文件。

打开文件并将文件描述符分配给变量,读取每一行并执行上面编写的代码。

set fildes [open "myhosts.txt" r]
set ip [gets $fildes]
while {[string length $ip] > 0} {

    spawn telnet $ip
    expect "User Name :"
    send "username\r"

    expect "Password  :"
    send "password\r"
    expect ">"
    send "4\r"
    expect "*#"
    exit
    set ip [gets $fildes]
}
close $fildes

答案 1 :(得分:2)

我不是expect的专家,但您需要做的第一件事是更改您的expect脚本以接受参数。它应该像这样工作(看起来你需要-f中的#!/usr/bin/expect):

#!/usr/bin/expect -f

set ip [lindex $argv 0]
spawn telnet $ip
...

然后,您可以在bash脚本中简单地遍历IP列表:

while read ip ; do
    myExpectScript $ip
done < list_of_ip.txt

答案 2 :(得分:2)

这只是对@ user3088572答案的评论。逐行读取文件的惯用方法是:

set fildes [open "myhosts.txt" r]
while {[gets $fildes ip] != -1} {
    # do something with $ip
}
close $fildes