bash/expect/loop - 如何通过 telnet 循环一个简单的 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20538286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash/expect/loop - how to loop a simple bash script doing telnet
提问by Mitchel
I would like to run this script in a loop.
我想循环运行这个脚本。
What is needs to do is read a file with in that file IP addresses like:
需要做的是读取文件中的 IP 地址,例如:
10.0.0.0
10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4
And run this script on every ip listed above here.
并在此处列出的每个 IP 上运行此脚本。
This is what i have:
这就是我所拥有的:
#!/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
How do i get the script above working every IP in a txt file.
我如何让上面的脚本在 txt 文件中的每个 IP 上工作。
回答by alvits
You can read the file within your expect script.
您可以在您的期望脚本中读取该文件。
Open the file and assign the file descriptor to a variable, read each line and execute the above code you wrote.
打开文件并将文件描述符分配给一个变量,读取每一行并执行您编写的上述代码。
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
回答by glenn Hymanman
This is just a comment on @user3088572's answer. The idiomatic way to read a file line by line is:
这只是对@user3088572 的回答的评论。逐行读取文件的惯用方法是:
set fildes [open "myhosts.txt" r]
while {[gets $fildes ip] != -1} {
# do something with $ip
}
close $fildes
回答by DarkDust
I'm not an expert with expect
, but the first thing you need to do is change your expect script to accept arguments. It should work like this (looks like you'll need -f
in #!/usr/bin/expect
):
我不是 专家expect
,但您需要做的第一件事是更改您的期望脚本以接受参数。它应该像这样工作(看起来你需要-f
在#!/usr/bin/expect
):
#!/usr/bin/expect -f
set ip [lindex $argv 0]
spawn telnet $ip
...
Then you can simply iterate over the list of your IPs in your bash script:
然后你可以简单地在你的 bash 脚本中迭代你的 IP 列表:
while read ip ; do
myExpectScript $ip
done < list_of_ip.txt