【问题标题】:bash/expect/loop - how to loop a simple bash script doing telnetbash/expect/loop - 如何循环执行 telnet 的简单 bash 脚本
【发布时间】:2013-12-30 13:21:06
【问题描述】:

我想循环运行这个脚本。

需要做的是读取该文件中包含 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。

【问题讨论】:

    标签: bash loops while-loop telnet expect


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      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
      

      【讨论】:

      • 脚本运行良好!但它只使用 myhosts.txt 中的第一个 IP,它不使用 myhosts.txt 第一行下的 ip 但登录正常
      • 对不起,我有那个退出要删除:D非常感谢你:)
      • 它退出是因为我继承了您的拼写错误。说明退出的行应该发送“exit\r”,因为该行的目的是告诉生成的 telnet 退出。但是拼写错误告诉脚本退出。
      • exit更改为send "exit\r"; expect eof; exp_close; wait
      【解决方案3】:

      我不是expect 的专家,但您需要做的第一件事是更改您的期望脚本以接受参数。它应该像这样工作(看起来你需要-f in #!/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
      

      【讨论】:

      • 你能说得更具体点吗?哪一部分?您收到什么错误消息?
      猜你喜欢
      • 2013-09-02
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      相关资源
      最近更新 更多