数据捕获问题在tcl中使用expect

时间:2012-05-22 06:32:37

标签: expect

我有一个怀疑。我想将命令的结果存储在字符串变量中。谁能告诉我代码中的错误是什么?它不起作用。我使用过expect_out(buffer)但它没有用。

#!/usr/bin/expect
package require Expect
set Argu1 [lindex $argv 0]
set Argu2 [lindex $argv 1]

if {$argc == 2} {

    if {[regexp {^(\d|[1-9]\d|1\d\d|2[0-4]\d|[2][5][0-5])\.(\d|[1-9]\d|1\d\d|2[
        0-4]\d|[2][5][0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|[2][5][0-5])\.(\d|[1-9]
        \d|1\d\d|2[0-4]\d|[2][5][0-5])$} $Argu1 match ]} {
        puts "VALID IP-ADDRESS"
        set timeout $Argu2-1
        spawn ping $Argu1
        expect "Expect"
        set string $expect_out(buffer)
        puts $string
        puts "SUCCESS"
        exit 
    } else { 
        puts "INVALID IP-ADDRESS"
    } 
} else { 
    puts "YOU HAVE TO GIVE TWO ARGUMENTS\n FIRST ARGUMENT SHOULD BE 
    IP-ADDRESS \n SECOND ARGUMENT SHOULD BE THE NUMBER OF PACKETS
    YOU WANT TO SEND"
}

1 个答案:

答案 0 :(得分:1)

我不愿意回答你的问题,因为你没有回答我在另一个问题上的回答。然而,看到没有其他人回应,我会尽力帮助你。

我认为你不需要在这里使用 $ expect_out(缓冲区)。假设ping返回“0%丢失”或“0%丢包”意味着ping成功,您可以尝试以下(未经测试)。显然,您可以将“0%”更改为您想要表示成功的任何内容。

#!/usr/bin/expect
package require Expect
set Argu1 [lindex $argv 0]
set Argu2 [lindex $argv 1]

if {$argc == 2} {

    if {[regexp {^(\d|[1-9]\d|1\d\d|2[0-4]\d|[2][5][0-5])\.(\d|[1-9]\d|1\d\d|2[
        0-4]\d|[2][5][0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|[2][5][0-5])\.(\d|[1-9]
        \d|1\d\d|2[0-4]\d|[2][5][0-5])$} $Argu1 match ]} {
        puts "VALID IP-ADDRESS"
        set timeout $Argu2-1
        spawn ping $Argu1
        expect {
          "0%" {puts "The IP address was successfully pinged"}
          "default" {puts "Could not ping this IP address"}
        }
        exit 
    } else { 
        puts "INVALID IP-ADDRESS"
    } 
} else { 
    puts "YOU HAVE TO GIVE TWO ARGUMENTS\n FIRST ARGUMENT SHOULD BE 
    IP-ADDRESS \n SECOND ARGUMENT SHOULD BE THE NUMBER OF PACKETS
    YOU WANT TO SEND"
}

我建议“0%”的原因如下。如果您从Windows计算机成功执行ping操作,您将看到类似这样的内容(请注意“0%丢失”):

C:\Documents and Settings\Brian>ping 192.168.1.1

Pinging 192.168.1.1 with 32 bytes of data:

Reply from 192.168.1.1: bytes=32 time=1ms TTL=64
Reply from 192.168.1.1: bytes=32 time<1ms TTL=64
Reply from 192.168.1.1: bytes=32 time<1ms TTL=64
Reply from 192.168.1.1: bytes=32 time<1ms TTL=64

Ping statistics for 192.168.1.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 1ms, Average = 0ms

在Unix机器上,它可能看起来像这样(注意“0%丢包”):

[brian@rex 4]$ ping -c 1 192.168.1.87
PING 192.168.1.87 (192.168.1.87) 56(84) bytes of data.
64 bytes from 192.168.1.87: icmp_seq=0 ttl=64 time=42.1 ms

--- 192.168.1.87 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 42.153/42.153/42.153/0.000 ms, pipe 2

你可以选择许多成功ping的指标,我选择了0%的数据包丢失这一事实(一个明确的成功指标)。 expect命令搜索ping的结果,如果找到“0%”,则输出“IP地址已成功ping通”。