2

I wrote a check for Nagios to detect if the currently installed Version of Java is the newest or if there are Updates to be applied.

First I get both the currently installed version of Java (using some code I found to retrieve the currently installed version) and the newest available version (using the document http://java.com/applet/JreCurrentVersion2.txt). Then I transform them using regular expressions (result: $1.$2.$3) to the same style, e.g.:

7.0.25

When printing the transformed versions via Wscript.Echo I can see, both are identical, but the String Comparison Operator StrComp() returns always false, if the Strings are equal or different. With an old version installed I get

Critical: Java Version 7.0.24 - available: 7.0.25

which is intended, but with the correct version I also get

Critical: Java Version 7.0.25 - available: 7.0.25

instead of

OK: Java Version 7.0.25

I attached the complete script down below:

check_java.vbs

On Error Resume Next

CONST rOK = 0
CONST rWarning = 1
CONST rCritical = 2
CONST rUnknown = 3

blnJavaInstalled = False
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProducts = objWMIService.ExecQuery("SELECT Version FROM Win32_Product")
For Each objProduct in colProducts
  If Err.Number = 0 Then
    If (InStr(UCase(objProduct.Name),"JAVA") And Not InStr(UCase(objProduct.Name),"UPDATER")) Then
      blnJavaInstalled = True
      version = objProduct.Version
    End If
  End If
Next
If blnJavaInstalled <> True Then
  Wscript.Echo "No Java found."
  Wscript.Quit(rUnknown)
End If

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.Pattern = "([0-9]+)\.([0-9]+).([0-9]*[1-9])0*"

curVersion = objRegEx.Replace(version, "$1.$2.$3")

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://java.com/applet/JreCurrentVersion2.txt", False
o.send

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.Pattern = "1\.([0-9]+)\.([0-9]+)_([0-9]+)"

newVersion = objRegEx.Replace(o.responseText, "$1.$2.$3")

If StrComp(curVersion, newVersion) Then
    Wscript.Echo "OK: Java Version " & curVersion
    Wscript.Quit(rOK)
Else
    Wscript.Echo "Critical: Java Version " & curVersion & " - available: " & newVersion
    Wscript.Quit(rCritical)
End If
4

2 回答 2

1

o.responseText有一个尾随换行符,所以你实际上是在比较7.0.257.0.25\r\n这显然是不相等的。您可以使用以下内容显示尾随换行符:

>>> WScript.Echo "_" & o.responseText & "_"
_7.0.25
_

将您的第二个正则表达式更改为

objRegEx.Pattern = "1\.([0-9]+)\.([0-9]+)_([0-9]+)[\s\S]*"

o.responseText或在进行正则表达式替换之前删除换行符:

newVersion = objRegEx.Replace(Replace(o.responseText, vbNewLine, ""), "$1.$2.$3")
于 2013-06-20T15:00:27.633 回答
1

如果比较的字符串相等,则StrComp返回 0 (False)。所以切换你的 If 语句的分支。由于您对哪个字符串更大或更小不感兴趣,请考虑使用 = 运算符(错误风险较小)。

于 2013-06-20T14:24:28.170 回答