无法在VBScript中使用正则表达式

时间:2018-12-02 11:22:35

标签: regex vbscript

我有一个PuTTY日志文件,其中捕获了所有SSH会话的输出。我想读取该日志文件并以所需的形式破坏其内容。 在日志文件中,对于我执行的每个ping命令,都有所需的模式。

我想在.CSV文件中输出,该文件包含日期,时间,IP和状态作为标头和日志文件中的数据。日志文件的内容如下所示:

=~=~=~=~=~=~=~=~=~=~=~= PuTTY log 2018.11.19 07:47:18 =~=~=~=~=~=~=~=~=~=~=~=
Using username "admin".
PING 172.27.1.4 (172.27.1.4) 56(84) bytes of data.
64 bytes from 172.27.1.4: icmp_req=1 ttl=64 time=1.22 ms
64 bytes from 172.27.1.4: icmp_req=2 ttl=64 time=1.05 ms
--- 172.27.1.4 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 1.058/1.139/1.221/0.088 ms
=~=~=~=~=~=~=~=~=~=~=~= PuTTY log 2018.11.19 07:47:22 =~=~=~=~=~=~=~=~=~=~=~=
Using username "admin".
PING 172.27.1.5 (172.27.1.5) 56(84) bytes of data.
64 bytes from 172.27.1.5: icmp_req=1 ttl=64 time=1.08 ms
64 bytes from 172.27.1.5: icmp_req=2 ttl=64 time=1.04 ms
--- 172.27.1.5 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 1.041/1.061/1.081/0.020 ms 
=~=~=~=~=~=~=~=~=~=~=~= PuTTY log 2018.11.19 07:47:26 =~=~=~=~=~=~=~=~=~=~=~=
Using username "admin".
PING 172.27.1.6 (172.27.1.6) 56(84) bytes of data.
From 172.27.1.6 icmp_seq=1 Destination Host Unreachable
From 172.27.1.6 icmp_seq=2 Destination Host Unreachable
--- 172.27.1.6 ping statistics ---
2 packets transmitted, 0 received, +2 errors, 100% packet loss, time 1004ms pipe 2

对于每个IP,可以在=~=~=~---中找到整个数据。 如果发现TTL,则状态为正常,而“目标主机不可达”或“请求超时”则状态为不正常。

编写了一个示例VBScript,但它仅列出了日志文件的第一个值。

Set fso = CreateObject("Scripting.FileSystemObject")
Set f=fso.opentextfile("log.txt",1)
a = f.ReadAll
Set r = New RegExp
r.Global = True
r.Multiline = True
r.IgnoreCase = True
r.Pattern = "=~=~=~=~=~=~=~=~=~=~=~= PuTTY log ((.|\n)*?)---"

Set Matches = r.Execute(a)
If Matches.Count > 0 Then Data = Matches(0).SubMatches(0)
MsgBox Data
WriteFileText "Test.txt", Data
f.Close

Function WriteFileText(sFile, Data)
    Dim objFSO, oTS, sText
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set oTS = objFSO.CreateTextFile(sFile, 2)
    oTS.WriteLine Data
    oTS.Close
    Set oTS = Nothing
    Set objFSO = Nothing
End Function

1 个答案:

答案 0 :(得分:0)

由于仅处理第一个匹配项,因此您只得到第一个匹配项:

Set Matches = r.Execute(a)
If Matches.Count > 0 Then Data = Matches(0).SubMatches(0)
MsgBox Data
WriteFileText "Test.txt", Data

将该代码更改为循环,它应该执行您想要的操作:

Set f = fso.CreateTextFile(sFile, 2)
For Each m In r.Execute(a)
    f.WriteLine m.SubMatches(0)
Next
f.Close

为片段中的“不健康”子字符串添加嵌套检查,将使您能够输出状态“健康”或“不健康”。

Set re2 = New RegExp
re2.Pattern = "destination host Unreachable|request timed out"
re2.IgnoreCase = True

If re2.Test(m.SubMatches(0)) Then
    WScript.Echo "Unhealthy"
Else
    WScript.Echo "Healthy"
End If

或者,找到匹配项时检查ttl=\d+并报告“健康”,否则报告“不健康”。