lordmilko / PrtgAPI

C#/PowerShell interface for PRTG Network Monitor
MIT License
305 stars 38 forks source link

Question: Create Device with Template.. No AutoDiscovery #205

Closed JRAndreassen closed 3 years ago

JRAndreassen commented 3 years ago

Hi @lordmilko,

I'm creating a device, assigning templates to it and then set the SNMP Creds...

  $newDeviceParam = New-DeviceParameters -Name $DevName -Host $DevHost
  $tmp = GetPRTGTemplate -TemplateName "Bahh-humbug"
    if ($tmp) {
        $newDeviceParam.DeviceTemplates += $tmp
        $haveTemplates = $true
    }
$device = $TgtGrp | Add-Device -Parameters $newDeviceParam 
...
  if ($device) {
    $propParams = @{}
    ... 
    if ($communityStr) }
        $propParams  = @{
            SNMPVersion = 'v2c'
            SNMPCommunityStringV2 = $communityStr
        }
     }
    if($propParams -and $propParams.Length -gt 0) {
        $device | Set-ObjectProperty @propParams
    }
}

The issue is... The auto Discovery starts before the SNMP Parameters are set... Which means there is nothing discovered.

There is no way, that I found to, pass the SNMP Creds in the DeviceParameters..

PS C:\Development\Customers\Otava> New-DeviceParameters -Name 'Junk' -Host '127.0.0.1'  

Host                  : 127.0.0.1
IPVersion             : IPv4
AutoDiscoveryMode     : Manual
AutoDiscoverySchedule : Once
DeviceTemplates       :
Name                  : Junk
Tags                  :
Cookie                : False

I could not find a way to set the templates list in Set-Options

PS C:\Development\Customers\Otava> $device | get-ObjectProperty  

IPVersion                   : IPv4
Host                        : Junker
Hostv4                      : Junker
Hostv6                      :
ServiceUrl                  : https://
ParentTags                  :
AutoDiscoveryMode           : Manual
AutoDiscoverySchedule       : Once
Active                      : True
InheritLocation             : True
Location                    :
Coordinates                 :
InheritWindowsCredentials   : True
WindowsDomain               :
WindowsUserName             :
HasWindowsPassword          : False
InheritLinuxCredentials     : True
LinuxUserName               :
LinuxLoginMode              : Password
HasLinuxPassword            : False
HasLinuxPrivateKey          : False
WbemProtocolMode            : HTTPS
WbemPortMode                : Automatic
WbemPort                    : 5989
SSHPort                     : 22
SSHElevationMode            : RunAsUser
SSHElevationSuUser          :
SSHElevationSudoUser        :
HasSSHElevationPassword     : False
SSHEngine                   : Default
InheritVMwareCredentials    : True
VMwareUserName              :
HasVMwarePassword           : False
VMwareProtocol              : HTTPS
VMwareSessionMode           : ReuseSession
InheritSNMPCredentials      : True
SNMPVersion                 : v2c
SNMPCommunityStringV1       : public
SNMPCommunityStringV2       : public
SNMPv3AuthType              : MD5
SNMPv3UserName              :
HasSNMPv3Password           : False
SNMPv3EncryptionType        : DES
HasSNMPv3EncryptionKey      : False
SNMPv3Context               :
SNMPPort                    : 161
SNMPTimeout                 : 5
InheritDBCredentials        : True
DBPortMode                  : Automatic
DBPort                      :
DBAuthMode                  : Windows
DBUserName                  :
HasDBPassword               : False
DBTimeout                   : 60
InheritAmazonCredentials    : True
AmazonAccessKey             :
HasAmazonSecretKey          : False
InheritWindowsCompatibility : True
WmiDataSource               : WMI
WmiTimeoutMethod            : OnePointFiveTimesInterval
WmiTimeout                  : 60
InheritSNMPCompatibility    : True
SNMPDelay                   : 0
SNMPRetryMode               : Retry
SNMPOverflowMode            : Handle
SNMPZeroValueMode           : Ignore
SNMPCounterMode             : Use64BitIfAvailable
SNMPRequestMode             : MultiGet
SNMPPortNameTemplate        : ([port]) [ifalias] [ifsensor]
SNMPPortNameUpdateMode      : Manual
SNMPPortIdMode              : Automatic
SNMPInterfaceStartIndex     : 0
SNMPInterfaceEndIndex       : 0
Name                        : vOskarVC-67
Tags                        : {au, device_type_virtual, device_vmware, host_not_accessible...}
Priority                    : Three
InheritProxy                : True
ProxyAddress                :
ProxyPort                   : 8080
ProxyUser                   :
HasProxyPassword            : False
InheritInterval             : True
Interval                    : 00:01:00
IntervalErrorMode           : OneWarningThenDown
InheritDependency           : False
Schedule                    : None
MaintenanceEnabled          : False
MaintenanceStart            : 3/10/2021 2:31:52 PM
MaintenanceEnd              : 3/10/2021 2:31:52 PM
DependencyType              : Object
DependentObjectId           : 91529
DependencyDelay             : 0
InheritChannelUnit          : True
BandwidthVolumeUnit         : KByte
BandwidthSpeedUnit          : Kbit
BandwidthTimeUnit           : Second
MemoryUsageUnit             : MByte
DiskSizeUnit                : MByte
FileSizeUnit                : Byte

I appreciate any insight... Thanks JR

lordmilko commented 3 years ago

Hi @lordmilko,

PrtgAPI does not currently support specifying parameters such as these at the time of device creation; as a workaround, rather than specifying the device templates in the parameters specified to Add-Device, I would recommend

  1. Simply adding the device without specifying to perform an auto-discovery
  2. Adding the additional configuration settings to the device with Set-ObjectProperty
  3. Manually initiating an auto-discovery via Start-AutoDiscovery. Any device templates you specify to Start-AutoDiscovery will be saved on the device for next time you run an auto-discovery, so the effect is exactly the same as if you specified these device templates at the exact moment of device creation instead

Regards, lordmilko

JRAndreassen commented 3 years ago

That works... Thanks JR

JRAndreassen commented 3 years ago

@lordmilko ,

The Discovery works..., but it seems the list is not saved...

        if($DeviceTemplateNames -and ($DeviceTemplateNames.Length -gt 0)) {
            $device | Start-AutoDiscovery -TemplateName $DeviceTemplateNames
        }

Bug or feature ?

Is there another way to set the templates, short of using the RawParameter

Thanks again JR

lordmilko commented 3 years ago

Hi @JRAndreassen,

I had observed in previous versions of PRTG when you run an auto-discovery with a specified list of device templates they would be saved; I can see in the latest version of PRTG however that no longer appears to be the case (even if you select to do an auto-discovery in the PRTG UI with a specified set of templates they aren't saved). I don't know whether that's a bug or not in PRTG itself, but in the meantime that is simply the functionality we have to deal with.

The only other option here would be to manually inject the parameters for modifying the SNMP parameters into the NewDeviceParameters specified at the time of device creation.

If you do $newDeviceParam.GetParameters()["Custom"] you will get the internal list PrtgAPI stores the parameters in

PS C:\> $newDeviceParam.GetParameters()["Custom"]

Name               Value     ParameterType
----               -----     -------------
name_              foo         SingleValue
host_              127.0.0.1   SingleValue
ipversion_         0           SingleValue
discoverytype_     2           SingleValue
discoveryschedule_ 0           SingleValue

You can technically add any additional parameters you like to this list, and they will be included when you add the device

You can view the names and values of these raw parameters if you specify -Verbose to Set-ObjectProperty (note that -Verbose will show the HTML encoded values of any special characters in these properties, so you will need to decode these first)

You can then add any desired parameters as so:

$newDeviceParam.GetParameters()["Custom"].Add((New-Object PrtgAPI.Parameters.CustomParameter "foo_","bar"))

Note that this is unsupported behavior, and indeed the GetParameters method will likely be changing in PrtgAPI 0.10, but this should serve as a sufficient workaround for now

lordmilko commented 3 years ago

A better idea (which should be a bit easier) might be to define your own custom NewDeviceParameters type that specifies all the additional parameters you're interested in

ipmo prtgapi
$path = (gmo prtgapi).path -replace "\.PowerShell",""

Add-Type -TypeDefinition @"
using PrtgAPI;
using PrtgAPI.Parameters;

public class NewDeviceParametersEx : NewDeviceParameters
{
    public NewDeviceParametersEx(string name, string host = null) : base(name, host)
    {
        SetCustomParameter(ObjectProperty.SNMPCommunityStringV1, "mystr");
    }
}
"@ -ReferencedAssemblies $path -WarningAction SilentlyContinue

If you then create an instance of your custom parameters type, you'll see that the additional parameters have been added

C:\> $params = New-Object NewDeviceParametersEx("foo", "foo.contoso.local")
C:\> $params.GetParameters()["Custom"]

Name               Value             ParameterType
----               -----             -------------
name_              foo                 SingleValue
host_              foo.contoso.local   SingleValue
ipversion_         0                   SingleValue
discoverytype_     0                   SingleValue
discoveryschedule_ 0                   SingleValue
snmpcommv1_        mystr               SingleValue

To avoid hardcoding these parameters in the C# constructor, you can either add additional parameters to the constructor, or add full blown Properties to make getting/setting properties even easier

You can get an idea as to how this can be done by looking at the source of NewDeviceParameters. You can also see that NewObjectParameters defines a number of helpful methods for adding/retrieving ObjectProperty values from the underlying parameter collection

JRAndreassen commented 3 years ago

@lordmilko ,

That should probably work.... Though, it would be handy to have all the parameters available.. Or be able to pass in ObjectProperty... Then loop through the list, Not sure what that looks like in c#..

public class NewDeviceParametersEx : NewDeviceParameters
{
    public NewDeviceParametersEx(ObjectProperty props, string name, string host = null) : base(name, host)
    {
        foreach(prop in props){
             if (prop.value != null) {
                 SetCustomParameter(prop.key, prop.value);
             }
        }
    }
}
lordmilko commented 3 years ago

Since the whole issue we're having is that Start-AutoDiscovery no longer automatically applies the device templates you wish to use, we can instead apply these templates ourselves using Set-ObjectProperty and then run the auto-discovery manually when we are ready


# Add the device
$device = Get-Probe | Add-Device "dc-1"

# Set the SNMP properties as required
# <implement this>

# Add the device templates

$types = get-devicetemplate *rdp*

$device | Set-ObjectProperty -RawParameters @{
    discoverytype_ = 2
    devicetemplate__check = $types
    devicetemplate_ = 1
} -Force -Verbose

# Start an auto-discovery
$device | Start-AutoDiscovery
JRAndreassen commented 3 years ago

Quite... If the raw can take the output from get-devicetemplate directly... that should work nicely...

xasz commented 2 years ago

@JRAndreassen Could you resolve this issue? @lordmilko Do you know anything have changed.

We currently use PRTG Version 21.4.73.1656+. I am trying to add a Template and "Planned" Autodiscovery to an existing device. My plan is to let PRTG trigger to Rescan a Template weekly. I could let my script run weekly and start the process, but as there is already a build in option in prtg, i want to use it. As @JRAndreassen already mentioned, i did not find to manipulte the "Selected Templates" in the Properties via Get-ObjectProperty.

The are these 2 option, which i can manipulate:

AutoDiscoveryMode           : AutomaticTemplate
AutoDiscoverySchedule       : Weekly

But not the selected templates it selfed, i tested something like this:

$hpetemplate = Get-Devicetemplate "APIv2_HPEILO.odt"
            $device | Set-ObjectProperty -RawParameters @{
                discoverytype_ = 2
                devicetemplate__check = $hpetemplate
                devicetemplate_ = 1
            } -Force -Verbose
            #AutoDiscoveryMode and AutoDiscoverySchedule works
            #$prtgDevice | Set-ObjectProperty -Property AutoDiscoveryMode -Value AutomaticTemplate
            #$prtgDevice | Set-ObjectProperty -Property AutoDiscoverySchedule -Value Weekly
            $prtgDevice | Start-AutoDiscovery

But whatever i do, there is no templated selected in the ui and it does the "default" search, want i do not want :) image I did not find anything documentation on the paessler site ( but that's probably me, not them)

Goal would be this: image

And Idea's or working examples? @lordmilko if you think this should be a new issue i will create one, but thought it is quite the same.

Thank you xasz

xasz commented 2 years ago

Ok, sorry - Just ignore it. I double checked serveral times and still had an typo. Here is working code, if anyone does need it:

     Write-Debug "Autodiscover auf Basis von ""APIv2_HPEILO.odt"" gestartet"
            $hpetemplate = Get-Devicetemplate "APIv2_HPEILO.odt"
            $prtgDevice | Set-ObjectProperty -RawParameters @{
                discoverytype_ = 2 # Ausgewählte Templates
                devicetemplate__check = $hpetemplate
                devicetemplate_ = 1
                discoveryschedule_ = 3 #1 = stündlich, 2 = täglich, 3 = Wöchentlich
            } -Force -Verbose
            $prtgDevice | Start-AutoDiscovery