2013-12-12 119 views
1

我想在循环中运行此脚本。bash/expect/loop - 如何循环执行telnet的简单bash脚本

什么是需要做的是阅读的文件在这样的文件中的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

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

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

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 
+0

这些脚本很好用!但它只使用myhosts.txt中的第一个IP,并且它不使用myhosts.txt中第一行下的ip。 但是登录正在工作 – Mitchel

+0

对不起,它有效,我有那个删除的退出:D 谢谢非常多:) – Mitchel

+0

它退出,因为我继承了你的输入错误。表示退出的行应该发送“exit \ r”,因为该行的意图是告诉生成的telnet退出。但是,错字错误正在告诉脚本退出。 – alvits

2

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

#!/usr/bin/expect -f 

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

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

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

我不能得到它的工作DarkDust ... – Mitchel

+0

你能更具体吗?哪一部分?你得到什么错误信息? – DarkDust

2

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

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