Select Page
This entry has been published on 2021-08-16 and may be out of date.

Last Updated on 2021-08-16.

[:en]

Scenario

USB server devices, e.g. used for virtual appliances, can be error-prone when it comes to auto-reconnect USB client devices on startup. In addition, if you have to redirect USB license dongles to some virtual server, some devices might get “lost” from time to time for whatever reason.

Solution / Help

Using the following PowerShell script you can add some checks to your NSClient / Nagios or similar monitoring.

#2021-08 www.dxsdata.com
#Checking existence of certain USB devices
#To get the IDs, execute this script with -Debug option, or execute below Get-... command

param(
[switch] $Debug
)

#adjust to your needs
$neededUsbDevices = @(
    [pscustomobject]@{NameFriendly='Dongle1';Id='USB\HASP&1234'}
    [pscustomobject]@{NameFriendly='Dongle2'; Id='USB\HASP&2345'}
    [pscustomobject]@{NameFriendly='Dongle3'; Id='USB\VID_0529&PID_0001&3456'}
    [pscustomobject]@{NameFriendly='Dongle4'; Id='USB\VID_0529&PID_0001&4567'}
)


#$existingUsbDevices = Get-WmiObject Win32_USBControllerDevice | ForEach-Object { [wmi]$_.dependent } | select-Object description,deviceid
$existingUsbDevices = Get-PnpDevice -PresentOnly -Class "USB" | Select-Object FriendlyName,DeviceID

if ($Debug) 
{
    "Debug output enabled. "
    "These devices will be checked: "
    $neededUsbDevices | fl
    "These devices are connected: "
    $existingUsbDevices
    ""
    ""
    "Comparing:"
}

$err = $False;

$output = "";
foreach($device in $neededUsbDevices)
{
    $result = $existingUsbDevices.Where({$_.DeviceID -eq $device.Id})
    $exists = $result.Count -gt 0
    $existsFriendly = If ($exists) {"OK"} Else {"MISSING"}
    $output += $device.NameFriendly + " " + $existsFriendly + ". " #cosmetics for nagios

    if (!$exists) { $err = $True; }
}
$output

$exitcode = if ($err) { 1 } Else { 0 }

if ($Debug) { "Exit code (Nagios Warning = 1, OK = 0) -> " + $exitcode }

exit($exitcode);

Save it into your NSClient’s scripts folder.

Modify nsclient.ini:

; Below [/settings/external scripts/scripts]
check_usb = cmd /c echo scripts\check_usb.ps1; exit($lastexitcode) | powershell.exe -command -

I assume you have several options already enabled, like CheckExternalScripts = 1, allow arguments etc.

Don’t forget to restart your NSClient service.

You might also want to check the result on your Nagios server like:

./check_nrpe -H myserver -c check_usb

 

 

References

https://docs.microsoft.com/en-us/powershell/module/pnpdevice/get-pnpdevice?view=windowsserver2019-ps

https://docs.nsclient.org/howto/external_scripts/[:]