Code Monkey home page Code Monkey logo

orionsdk-python's Introduction

Orion SDK for Python

This project contains a python client for interacting with the SolarWinds Orion API

API Documentation

For documentation about the SolarWinds Orion API, please see the wiki, tools, and sample code (in languages other than Python) in the main OrionSDK project.

Install

pip install orionsdk

Usage

import orionsdk

swis = orionsdk.SwisClient("server", "username", "password")

aliases = swis.invoke('Metadata.Entity', 'GetAliases', 'SELECT B.Caption FROM Orion.Nodes B')

print(aliases)

SSL Certificate Verification

Initial support for SSL certificate valuation was added in 0.0.4. To enable this, you will need to save the self-signed cert to a file. One way of doing this is with OpenSSL:

openssl s_client -connect server:17778

Then add an entry to your hosts file for SolarWinds-Orion and you will be able to verify via doing the following:

import orionsdk
swis = orionsdk.SwisClient("SolarWinds-Orion", "username", "password", verify="server.pem")
swis.query("SELECT NodeID from Orion.Nodes")

Setting Timeout

import orionsdk
import requests

session = requests.Session()
session.timeout = 30 # Set your timeout in seconds
swis = orionsdk.SwisClient("SolarWinds-Orion", "username", "password", verify="server.pem", session=session)
swis.query("SELECT NodeID from Orion.Nodes")

Setting Retry

import orionsdk
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry


def retry_session(retries=3,
                  backoff_factor=0.3,
                  status_forcelist=(500, 502, 504)):
    session = requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist)
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session


swis = orionsdk.SwisClient(
    "SolarWinds-Orion",
    "username",
    "password",
    verify="server.pem",
    session=retry_session())
swis.query("SELECT NodeID from Orion.Nodes")

License

This software is licensed under the Apache License, version 2 ("ALv2"), quoted below.

Copyright © 2015 SolarWinds Worldwide, LLC.  All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.

Related Projects

Solarwinds Interface Traffic Forecaster

SolarwindsInterfaceTrafficPrediction is an example of using the Orion SDK for Python and machine learning techniques to predict network interface traffic.

orionsdk-python's People

Contributors

ashkuren avatar cr41gc avatar danjagnow avatar jjm avatar john-westcott-iv avatar joshclark avatar ministrycork avatar mrxinu avatar oniram22 avatar petr-jancik-swi avatar radek-necas2-sw avatar superadm1n avatar tdanner avatar tomasvrabel avatar tonypnode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

orionsdk-python's Issues

Issue with Updating Custom Properties

The sample code shows this:

swis.update(uri + '/CustomProperties', City='Austin')

But when I:

property = 'City'
value = 'Austin'
props = { property : value }

swis.update(uri + '/CustomProperties', props)

The update fails with:

Traceback (most recent call last):
File "./custom_property_update.py", line 67, in <module>
update_props(hostid, prop, value)
File "./custom_property_update.py", line 43, in update_props
swis.update(uri + '/CustomProperties', {prop:value} )
TypeError: update() takes exactly 2 arguments (3 given)

Can somebody help?

timeout

I experience timeout after 30 seconds, and I tried to modify the client module to increase timeout (passing the arg to requests module:

def _req(self, method, frag, data=None):
resp = requests.request(method, self.url + frag,
data=json.dumps(data, default=_json_serial),
verify=self.verify,
auth=self.credentials,
headers={'Content-Type': 'application/json'},
timeout=500.0)

Perhaps timeout should be exposed to users?
Secondly - my efforts did not work - I assume I need to tweak settings in the webserver..

Connection aborted.', ConnectionResetError(104, 'Connection reset by peer

Orion Platform 2015.1.3

Traceback (most recent call last):
File "/app/netdevops/solar.py", line 19, in
results = swis.query("SELECT TOP 3 NodeID, DisplayName FROM Orion.Nodes")
File "/usr/local/lib/python3.9/site-packages/orionsdk/swisclient.py", line 23, in query
return self._req(
File "/usr/local/lib/python3.9/site-packages/orionsdk/swisclient.py", line 55, in _req
resp = self._session.request(method,
File "/usr/local/lib/python3.9/site-packages/requests/sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.9/site-packages/requests/sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.9/site-packages/requests/adapters.py", line 501, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

ValueError: No Json object could be decoded

Hi All,
I was just testing the water to get some data through Orionsdk.. but i am getting ValueError: No Json Object could be decoded error. below the full code and compelete stackTrace...
Please let me know what the issue is:
import json
import requests
from orionsdk import SwisClient

verify = False
if not verify:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

swis = SwisClient(npm_server, username, password)
print swis.query("SELECT TOP 3 NodeID, DisplayName FROM Orion.Nodes")

StackTrace:
Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\lib\site-packages\orionsdk\swisclient.py", line 24, in query

{'query': query, 'parameters': params}).json()

File "C:\Python27\lib\site-packages\requests\models.py", line 805, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python27\lib\json__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

403 Client Error: Access to Orion.AlertSuppression.SuppressAlerts verb denied

Hi
I'm using the example code try and SuppressAlerts, but I keep getting the error "403 Client Error: Access to Orion.AlertSuppression.SuppressAlerts verb denied".

This is my code:
sw = orionsdk.SwisClient('server', 'username', 'password') uri = sw.query("SELECT Uri FROM Orion.Nodes WHERE NodeID=@node_id", node_id=17918)['results'][0]['Uri'] print( sw.invoke('Orion.AlertSuppression', 'GetAlertSuppressionState', [uri]) ) print( sw.invoke('Orion.AlertSuppression', 'SuppressAlerts', [uri], datetime.datetime.now(), None) )

The example was taken from #34

The exact error:
requests.exceptions.HTTPError: 403 Client Error: Access to Orion.AlertSuppression.SuppressAlerts verb denied. for url: https://solarwinds-orion:17778/SolarWinds/InformationService/v3/Json/Invoke/Orion.AlertSuppression/SuppressAlerts

Performing the action through the gui with the samen user account, will allow me to suppress alerts. Any idea what this could be?

Running SolarWinds 2023.1.

Unable to invoke on Alert Suppression

I am trying to utilize the invoke method to get the alert suppression state, suppress alerts, and resume alerts for a node. When the invoke method gets run it raises an http error:

requests.exceptions.HTTPError: 400 Client Error: Verb Orion.AlertSuppression.ResumeAlerts cannot unpackage parameter 0 with type System.String[] for url: https://orion.servername.com:17778/SolarWinds/InformationService/v3/Json/Invoke/Orion.AlertSuppression/ResumeAlerts

An example that fails is this script below

import orionsdk
import datetime

sw = orionsdk.SwisClient('server', 'username', 'password')
uri = sw.query("SELECT Uri FROM Orion.Nodes WHERE NodeID=@node_id", node_id=1179)['results'][0]['Uri']

# get suppression State fails
sw.invoke('Orion.AlertSuppression', 'GetAlertSuppressionState', uri)

# suppressing alerts fails
sw.invoke('Orion.AlertSuppression', 'SuppressAlerts', uri, datetime.datetime.now(), None)

# resume alerts fails
sw.invoke('Orion.AlertSuppression', 'ResumeAlerts', uri)

I have validate that the username + password I am using allows me to do other things via the API and when I manually paste the URI into SWQL studio doing an invoke on GetAlertSuppressionState it does return data.

Im not sure what I am doing wrong.

SwisClient "SELECT *" Issue

Previously, the SwisClient supported invoking SELECT statements using the '*' wildcard to query all results from a specific table.

Ex.

sw = SwisClient('server', 'user', 'pword')
q = sw.query('SELECT * FROM Orion.Nodes')

This above code returns an error (see attached) that basically says the '*' character cannot be used as input. Has support for this wild card been taken away? I've tried this using python 3.7 and python 2.7.17 and received the same error.
sw_error

Bulk Group creation with dynamic query

Does anyone know the correct syntax for creating dynamic query with a filter using a variable (sitecode) contained in the DNS name:

"filter:/Orion.Nodes[Contains(DNS,sitecode)]"

I can use a string here, not sure how to add a variable

Use any port number if specified to initialize client

The company I work for is currently using this client, but we are providing our certificate on a different port number. So, the only way to fix this issue is to provide a way to insert our own port number to match which port we serve our certificate.

Potential changes: Make changes to pass port_number in with a default value of 17778. Then do a string insertion into the url to specify the port number wanted. The change would be located here:
https://github.com/solarwinds/orionsdk-python/blob/master/orionsdk/swisclient.py#L14 (and line 15)

How to test for SNMP credentials using Rest API

Is there a pythonic way to test SNMP creds through restAPI. If not API, I am fine with any procedure other than manually doing it.

Here is what I am referring to

image

Clicking on TEST would say whether I can connect to device using those credentials.

Please help me, thanks in advance.

Orionsdk swisclient: CPU and memory resource stats and monitoring

Here is a small code snippet that I use to add a node for monitoring:

res = client.create('Orion.Nodes', **props)

nodeid = re.search(r'(\d+)$', res).group(0)

for k,v in custom_props.items():
    client.update(res+'/CustomProperties',**{k: v})

client.invoke('Orion.HardwareHealth.HardwareInfo', 'EnableHardwareHealth', 'N:'+nodeid, 9)

_add_pollers(client, nodeid, 'default')
_add_pollers(client, nodeid, poller_template)

client.invoke('Orion.Nodes', 'PollNow', 'N:'+nodeid )

Even after I invoked HardwareInfo, my CPU and Memory stats are not getting collected.

To be precise, in NPM, when you click the link "list resources" on the node page, it enumerates all the hardware and interfaces details. There were select CPU and memory for stats collection. I want to achieve the same through code.

What am I missing?

SwisClient bulkdelete method not in PyPi

I'm not sure how exactly this happened, but if you look at SwisClient in the .tar.gz in PyPi it doesn't have the bulkdelete method even though the 3.0.0 tag source does have it. Could you reupload the source .tar.gz to PyPi so that bulkdelete exists again? Thanks!

requests.exceptions.HTTPError: 400 Client Error: Update or insert of view or function 'dbo.NCM_Nodes' failed because it contains a derived or constant field.

I am trying to update the following fields in NCM.
uri = 'swis://orion-npm.ad.utah.edu/Orion/NCM.Nodes/NodeID=C8B848D4-EFE0-4386-9079-10057E8B2F9C'
props = {'SNMPLevel': 3, 'SNMPUsername':XXXXX, 'SNMPAuthType':'MD5', 'SNMPAuthPass':'XXXXXX, 'SNMPEncryptType':'DES', 'SNMPEncryptPass':XXXXXX} self.swis.update(uri, **props)

I get the following Error:

requests.exceptions.HTTPError: 400 Client Error: Update or insert of view or function 'dbo.NCM_Nodes' failed because it contains a derived or constant field. for url: https://smg-mp-p01.sys.utah.edu:17778/SolarWinds/InformationService/v3/Json/swis://orion-npm.ad.utah.edu/Orion/NCM.Nodes/NodeID=C8B848D4-EFE0-4386-9079-10057E8B2F9C

Disabling specific sensors via python

Hello,

I'm trying to disable specific hardware sensors using the orionsdk Python module.

I was referencing this (https://thwack.solarwinds.com/product-forums/the-orion-platform/f/orion-sdk/42733/disabling-hardware-health-sensors) and trying to convert the Powershell to its Python equivalent, but I'm getting this error:

requests.exceptions.HTTPError: 400 Client Error: Verb Orion.HardwareHealth.HardwareItemBase.DisableSensors cannot unpackage parameter 0 with type System.Collections.Generic.IEnumerable`1[SolarWinds.HardwareHealth.Common.Models.HardwareHealth.HardwareHealthItemKey] for url: https://xxxxxxx:17778/SolarWinds/InformationService/v3/Json/Invoke/Orion.HardwareHealth.HardwareItem/DisableSensors

Is there an example of disabling a specific hardware sensor using the "DisableSensors" verb under 'Orion.HardwareHealth.HardwareItem'?

xml = f"<array><HardwareHealthItemKey><HardwareInfoID>{hardware_info_id}</HardwareInfoID><HardwareCategoryStatusID>{hardware_category_status_id}</HardwareCategoryStatusID><UniqueName>{unique_name}</UniqueName></HardwareHealthItemKey></array>"
...

swis.invoke('Orion.HardwareHealth.HardwareItem', 'DisableSensors', xml)

Thanks!

SVI showing None for InAveragebps

Weve recently noticed that under an SVI interface, "Vlan10" for example is showing None for InAveragebps, this happens for all our SVIs, OutAveragebps does not have any issues, but all InAveragebps do

Thanks

Sample showing None under SVI

>>> print(query)

SELECT
n.NodeID,
n.NodeName,
n.Interfaces.Name,
n.Interfaces.InterfaceID,
n.Interfaces.Caption AS InterfaceName,
n.Interfaces.Traffic.InAveragebps,
n.Interfaces.Traffic.OutAveragebps,
TOLOCAL(n.Interfaces.Traffic.DateTime) as DateTime
FROM
Orion.Nodes n
INNER JOIN (SELECT
nn.NodeID,
nn.Interfaces.Name,
max(nn.Interfaces.Traffic.DateTime) as most_recent
FROM
Orion.Nodes nn
WHERE
(nn.NodeID = '1895' AND nn.Interfaces.Name = 'Vlan10')
GROUP BY
nn.NodeID,
nn.Interfaces.Name
) most_recents
ON n.NodeID = most_recents.NodeID
AND n.Interfaces.Traffic.DateTime = most_recents.most_recent

>>> results = swis.query(query)
>>> results = results["results"]
>>> results
[{'NodeID': 1895, 'NodeName': 'Edge-01', 'Name': 'Vlan10', 'InterfaceID': 5504, 'InterfaceName': 'Vlan10 · *** VLAN10 ***', 'InAveragebps': None, 'OutAveragebps': 29591578.0, 'DateTime': '2020-06-29T11:33:14.6630000'}]

Sample showing correct values under a regular portI

>>> query="""
... SELECT
... n.NodeID,
... n.NodeName,
... n.Interfaces.Name,
... n.Interfaces.InterfaceID,
... n.Interfaces.Caption AS InterfaceName,
... n.Interfaces.Traffic.InAveragebps,
... n.Interfaces.Traffic.OutAveragebps,
... TOLOCAL(n.Interfaces.Traffic.DateTime) as DateTime
cents
ON n.NodeID = most_recents.NodeID
AND n.Interfaces.Traffic.DateTime = most_recents.most_recent
"""

results = swis.query(query)
results = results["results"]... FROM
... Orion.Nodes n
... INNER JOIN (SELECT
... nn.NodeID,
... nn.Interfaces.Name,
... max(nn.Interfaces.Traffic.DateTime) as most_recent
... FROM
... Orion.Nodes nn
... WHERE
... (nn.NodeID = '1895' AND nn.Interfaces.Name = 'TenGigabitEthernet1/0/2 ')
... GROUP BY
... nn.NodeID,
... nn.Interfaces.Name
... ) most_recents
... ON n.NodeID = most_recents.NodeID
... AND n.Interfaces.Traffic.DateTime = most_recents.most_recent
... """
>>>
>>> results = swis.query(query)

>>> results = results["results"]
>>>
>>> results
[{'NodeID': 1895, 'NodeName': 'Edge-01', 'Name': 'TenGigabitEthernet1/0/2', 'InterfaceID': 6369, 'InterfaceName': 'TenGigabitEthernet1/0/2 · *** L3 - Uplink ***', 'InAveragebps': 28587964.0, 'OutAveragebps': 213409248.0, 'DateTime': '2020-06-29T13:04:34.8300000'}]

Question on Suppress Alerts

Hi,

how can i create schedule to suppress alerts for example suppress the alert from 8pm to 9pm.

thanks,
Ahmad.

IPAM Get next available IP from subnet

If someone already has an example using the IPAM API (via python) to get the next available IP address from a specified subnet, please add, otherwise, I'll start working on it and get a PR in soon.

Unmanage - Input string was not in a correct format

Hi,

no matter how I format the date for the unmanage function i get the same error as per below.

swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, '01-14-2017 00:00:00', '01-14-2017 06:00:00', True)
{u'Message': u'Input string was not in a correct format.', u'ExceptionType': u'System.FormatException', u'FullException': u'System.FormatException: Input string was not in a correct format.\r\n at SolarWinds.InformationService.Verb.VerbExecutor.Invoke(Object hostInstance, Object[] parameters)\r\n at SolarWinds.InformationService.Verb.VerbExecutorContext.Invoke()\r\n at SolarWinds.InformationService.Core.InformationService.Invoke[T](String entity, String verb, Action1 setupParameters, Func2 extractReturnValue)'}

Python error raised from SWIS error should include details

When a call to SWIS throws an error (HTTP 4xx or 5xx), the python client raises an error. In these cases, the SWIS response includes a json-encoded object with some details about the cause of the error. Including these details in the python error object would help users understand and resolve the problem.

Solarwinds Class File

I'm about to submit a pull request for a solarwinds class file I've been working on. It basically let's you supply the IP, username and password for your SolarWinds NPM instance and then has an array of methods you can call to make updates to your system. However the real power of the class is that all of the method calls are done using nothing more than the human readable names that are used throughout the GUI. All of the ID's, URI's, and SQL calls are abstracted out and done behind the scenes. The thought process is that this creates a lower bar for entry into Solarwinds programmability. You are able to get started updating your system programmatically without having to have a detailed knowledge of the inner workings of Solarwinds. What I'm uploading is an initial draft based on some activities we're doing in house. The hope would be to grow the class file over time as additional needs surfaced form the community. Also, given the file is a python class file it's call init.py but should really be placed in a directory called 'solarwinds'. I wasn't sure how to make that happen within the github repository and the rights I have. Feel free to rearrange that.

403 Client Error: Forbidden for url

personal information has been replaced

(orionsdk) [user@linux-user orionsdk]$ cat otest.py 
import orionsdk

swis = orionsdk.SwisClient("SolarWinds-Orion", "user", "password", verify="server.pem")
swis.query("SELECT NodeID from Orion.Nodes")
(orionsdk) [user@linux-user orionsdk]$ python otest.py 
/home/user/orionsdk/lib/python2.7/site-packages/urllib3/connection.py:362: SubjectAltNameWarning: Certificate for solarwinds-orion has no `subjectAltName`, falling back to check for a `commonName` for now. This feature is being removed by major browsers and deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 for details.)
  SubjectAltNameWarning
Traceback (most recent call last):
  File "otest.py", line 8, in <module>
    swis.query("SELECT NodeID from Orion.Nodes")
  File "/home/user/orionsdk/lib/python2.7/site-packages/orionsdk/swisclient.py", line 24, in query
    {'query': query, 'parameters': params}).json()
  File "/home/user/orionsdk/lib/python2.7/site-packages/orionsdk/swisclient.py", line 59, in _req
    resp.raise_for_status()
  File "/home/user/orionsdk/lib/python2.7/site-packages/requests/models.py", line 940, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://solarwinds-orion:17778/SolarWinds/InformationService/v3/Json/Query

any idea what I need to do to address this issue?

Creating Alerts?

Is there or will there be a way to create alerts and application monitors using this python SDK or is there another one that does this?

groups.py Custom Properties filter

When attempting to add group members in the manner below, Site being a node custom property, the filter returns all nodes in the system, and all nodes are added to the group.

group members

[
{'Name': site, 'Definition': "filter:/Orion.Nodes[Site={0}]".format(site)},
]

When I look at the dynamic query in the GUI I see that the conditions are set for Address, which is another custom property, is, then the value for my site variable. I am not sure why this matches all nodes in the system.

Any insight into how I might be able to filter with custom properties would be greatly appreciated.

about Orion(v2) and SSLError

I try to connect orion use python2 but response error message:

code:

import requests
from orionsdk import SwisClient
import orionsdk

npm_server = '192.168.0.100'
username = 'admin'
password = 'password'

verify = False
if not verify:
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


swis = SwisClient(npm_server, username, password)

print("Query Test:")
results = swis.query("SELECT Uri From Orion.Nodes Where Nodeid=@id",id=1)

uri=results['results'][0]['Uri']
print(uri)

reponse:

Query Test:
Traceback (most recent call last):
  File "/Users/guest_mac/python_code/solarwinds/test.py", line 24, in <module>
    results = swis.query("SELECT Uri From Orion.Nodes Where Nodeid=@id",id=1)
  File "/Library/Python/2.7/site-packages/orionsdk/swisclient.py", line 24, in query
    {'query': query, 'parameters': params}).json()
  File "/Library/Python/2.7/site-packages/orionsdk/swisclient.py", line 50, in _req
    headers={'Content-Type': 'application/json'})
  File "/Library/Python/2.7/site-packages/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 506, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='192.168.0.100', port=17778): Max retries exceeded with url: /SolarWinds/InformationService/v3/Json/Query (Caused by SSLError(SSLEOFError(8, u'EOF occurred in violation of protocol (_ssl.c:590)'),))

where i the problem any how to fix

SolarWinds Duplicate ICMP Device Listings

ICMP Devices we've added into SW using Orionsdk-python are listed 2x under Manage Nodes.
Here are the details:

  1. ICMP devices only
  2. Edit Resources shows Polling Method is ICMP, however, if you select SNMP the community string is pre-populated with "public"
  3. ICMP devices that are discovered using Add Node are not listed 2x and if you select SNMP, the string field is blank.
  4. The devices are listed 2x only under Manage Nodes + both entries have the same Node ID.

As far as I can tell, these devices are not listed 2x anywhere else; i.e, not when executing a search, not in the All Nodes Summary on the homepage, not in reports, etc...

Has anyone else seen this type of issue?

thanks,
LM

OrionSDK not permanently setting interface status on Node

Ever since upgrading to 2019.4, my Python script that sets interfaces on a node that are in the "Down" state to the "Unplugged" state isn't working. The script will run and the Down interfaces will be transitioned to the Unplugged state, but will immediately transition back to the Down state after only a few seconds.

Unable to get resources list of a node

Below is the script that I tried to get resources list of a node:


    jobid = swis.invoke('Orion.Nodes', 'ScheduleListResources',NodeID)
    print(jobid)

    time.sleep(60)
    
    while True:
        results = swis.invoke('Orion.Nodes', 'GetScheduledListResourcesStatus', jobid,NodeID)
        print(results)
        if(results=='ReadyForImport'):
            break

    results = swis.invoke('Orion.Nodes', 'ImportListResourcesResult', jobid,NodeID)
    print(results)

Error:

requests.exceptions.HTTPError: 400 Client Error: Could not load file or assembly 'SolarWinds.Interfaces.Discovery.Strings, Version=3.5.0.638, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. for url: https://solarwinds_url:17778/SolarWinds/InformationService/v3/Json/Invoke/Orion.Nodes/ImportListResourcesResult

Custom Property of Date/Time type does not accept python datetime with microsecond resolution

Hello,

Python version:
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32

I am trying to set current datetime into custom property of node:

import orionsdk
from datetime import datetime
swis = orionsdk.SwisClient('hostname', 'username', 'password')
uri = 'swis://{hostname}/Orion/Orion.Nodes/NodeID={id}'
swis.update(
    uri + '/CustomProperties',
    LastUpdated=datetime.now(),
)

This produces following HTTP request:

send: b'
	POST /SolarWinds/InformationService/v3/Json/swis://{hostname}/Orion/Orion.Nodes/NodeID={node_id}/CustomProperties HTTP/1.1
	Host: {hostname}:17778
	User-Agent: python-requests/2.21.0
	Accept-Encoding: gzip, deflate
	Accept: */*
	Connection: keep-alive
	Content-Type: application/json
	Content-Length: 52
	Authorization: Basic xxxxxxxxxxxx=
'
send: b'{"LastUpdated": "2019-01-11T15:38:24.394284"}'

Response:

reply: 'HTTP/1.1 400 Bad Request\r\n'
header: Content-Length: 2841
header: Content-Type: application/json
header: Server: Microsoft-HTTPAPI/2.0
header: Date: Fri, 11 Jan 2019 14:38:24 GMT

requests.exceptions.HTTPError: 400 Client Error: Conversion failed when converting date and/or time from character string. for url: https://{hostname}:17778/SolarWinds/InformationService/v3/Json/swis://{hostname}/Orion/Orion.Nodes/NodeID={node_id}/CustomProperties

Workaround:

import orionsdk
from datetime import datetime
swis = orionsdk.SwisClient('hostname', 'username', 'password')
uri = 'swis://{hostname}/Orion/Orion.Nodes/NodeID={id}'
swis.update(
    uri + '/CustomProperties',
    LastUpdated=datetime.now().replace(microsecond=0),
)

HTTP Connection Issue: Authentication Failed

Max retries exceeded with url: /SolarWinds/InformationService/v3/Json/Query (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000018018C5C760>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

Fetching this issue when trying to query any thing from the API. Please help!

Sample for Adding Agent using the python SDK

What is the best way to install agent (add agent) to a newly created VM in the network?
Tried Orion.AgentManagement.Agent.Deploy but not fruitful. Is there any example somewhere?

Method1:

props = {
        "Name": "<AGENTNAME>",
        "Hostname": "<HOSTNAME>",
        "DNSName": "<DNSNAME>",
        "IP": "<IP>",
        "OSVersion": "<OS Version>",
        "PollingEngineId": 9,
        "ConnectionStatus": 0,
        "ConnectionStatusMessage": "Initial API insertion - connection pending",
        "AgentStatus": 0,
        "AgentStatusMessage": "Unknown",
        "Mode": 0,
        "AutoUpdateEnabled": True
    }
    
response = swis.invoke('Orion.AgentManagement.Agent', 'Deploy', **props)


Failed with:
Traceback (most recent call last):
File "./add_agent.py", line 52, in
main()
File "./add_agent.py", line 45, in main
response = swis.invoke('Orion.AgentManagement.Agent', 'Deploy', **props)
TypeError: invoke() got an unexpected keyword argument 'Name'

Method2:

response = swis.invoke('Orion.AgentManagement.Agent', 'Deploy', 9, "<AGENT_NAME>", "<HOST_NAME>", "<DNSName>",
                        "<IP>","<OSVersion>", "<PolingEngineID>","<AgentStatus>0")

Failed with:
_Traceback (most recent call last):
File "./add_agent.py", line 53, in
main()
File "./add_agent.py", line 46, in main
"10.201.16.11","7.7", "9","0")
File "/usr/lib/python2.7/site-packages/orionsdk/swisclient.py", line 31, in invoke
"Invoke/{}/{}".format(entity, verb), args).json()
File "/usr/lib/python2.7/site-packages/orionsdk/swisclient.py", line 63, in req
resp.raise_for_status()
File "/usr/lib/python2.7/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Agent '"<AGENT_NAME>' must be assigned to existing polling engine for url: https://solarwindsEndpint:17778/SolarWinds/InformationService/v3/Json/Invoke/Orion.AgentManagement.Agent/Deploy

using SDK Python to find ACL

Hi,
Is there a method utilising the SDK to find which devices have a certain ACL, for example access-list 101?
Thanks

400 Client Error: Specified cast is not valid

Hi Guys,

Im getting the following error when trying use the Python class to add a node to NPM that uses SNMPv3;

[mw@ansible-001 orion]$ python add_node.py
Add an SNMP v3 node:
/usr/lib/python2.7/site-packages/requests/packages/urllib3/connection.py:340: SubjectAltNameWarning: Certificate for solarwinds-orion has no `subjectAltName`, falling back to check for a `commonName` for now. This feature is being removed by major browsers and deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 for details.)
  SubjectAltNameWarning
Adding node 10.116.26.80... Traceback (most recent call last):
  File "add_node.py", line 138, in <module>
    main()
  File "add_node.py", line 96, in main
    results = swis.create('Orion.Nodes', **Orion_Nodes)
  File "/usr/lib/python2.7/site-packages/orionsdk/swisclient.py", line 34, in create
    "Create/" + entity, properties).json()
  File "/usr/lib/python2.7/site-packages/orionsdk/swisclient.py", line 59, in _req
    resp.raise_for_status()
  File "/usr/lib/python2.7/site-packages/requests/models.py", line 909, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Specified cast is not valid. for url: https://solarwinds-orion:17778/SolarWinds/InformationService/v3/Json/Create/Orion.Nodes

This is my python script, its just to get a feel for the NPM API and this Python class:

[me@ansible-001 orion]$ cat add_node.py
from __future__ import print_function
import re
import requests
from orionsdk import SwisClient


def main():
   npm_server = 'SolarWinds-Orion'
   username = 'sw-user'
   password = 'sw-pass'


   swis = SwisClient(npm_server, username, password, verify="SolarWinds-Orion.pem")

   # Only need one of [DisplayName, Caption, NodeName]
   Orion_Nodes = {
      'DisplayName': "cpe",
      'Description': "cpe",
      'NodeDescription': "my cpe",
      'Location': "Lab",
      'UnManaged': False,
      'Allow64BitCounters': True,
      'ObjectSubType': "SNMP",
      'EngineID': 1,
      'IPAddress': "10.116.26.80",
      'SNMPVersion': '3',
      'SNMPV3Username': "snmpv3-user",
      'SNMPV3PrivMethod': "AES128",
      'SNMPV3PrivKeyIsPwd': True,
      'SNMPV3PrivKey': "snmpv3-priv-key",
      'SNMPV3AuthKey': "snmpv3-auth-key",
      'SNMPV3AuthMethod': "MD5",
      'SNMPV3AuthKeyIsPwd': True
   }

   print("Add an SNMP v3 node:")
   print("Adding node {}... ".format(Orion_Nodes['IPAddress']), end="")
   results = swis.create('Orion.Nodes', **Orion_Nodes)
   print("DONE!")

if __name__ == '__main__':
   main()

This node is actually added to SNMP however all the SNMPv3 details are missing, as per this screenshot:

snmpv3

This is on Orion Platform 2017.1, NPM 12.1, I'm using Python 2.7.5. I can add the device manually through the web GUI using SNMPv3 without issue. I can also add the device using SNMP v2c via the GUI and API. It is just SNMPv3 via the API that is not working.

I can open a support case on the SW site too if that helps?

Please let me know what further info I can provide to help diagnose this issue.

Interface operation and admin status are wrong

When using DiscoverInterfacesOnNode verb i'm getting all interfaces with ifOperStatus = 4 and ifAdminStatus = 0 regardless if the interface is up or not. Can you please correct that

snmp-testing

Hi, this is not an issue, just a question that I can't seem to find it anywhere. Is there a way to test the assigned snmp-credentials to a node are correct? Just like the 'test' button on the "Edit Node" section.
Thank you.

SNMPv3 RW Credentials

I'm trying to automate how we interact with Solarwinds in regards to adding nodes, updating nodes, etc... I've created a python Script that successfully adds a node and fills in the SNMPv3 properties in the "Edit Node" section within the created node. Does the syntax exist to also fill in the RW SNMPv3 properties in the "Edit Node" section?

I looked at the "def add_node_using_snmp_v3" within solarwinds.py and I don't see anything within node properties for RW, and anytime I add RW to the properties in my configuration, I get "requests.exceptions.HTTPError: 400 Client Error: Invalid column name 'SNMPv3RWUsername'," for example. I've also tried "RWUsername," but I always get the same error.

I'm presuming the column headers don't exist yet, but I'd be grateful if anyone knows how to do it because if I can't fill in the RW portion, there really isn't any point in automating this yet.

If my full code is needed, I can provide it, but it just follows the "def add_node_using_snmp_v3" Thanks!

SettingValue(credentialID) is not getting updated

I am trying to add a node using rest api, soon after adding the node trying to change the credentialID using the below code

prop = {
"NodeID": nodeid, 
"SettingName": "ROSNMPCredentialID",        
"SettingValue": credentialID     
}
result = swis.create("Orion.NodeSettings", **prop)

but i see 2 credentialID's for single nodeID in "Orion.NodeSettings" .

Please let me know if there is any solution to get rid of earlier credentialID

PollNode issues Fault

swis.invoke('Orion.Nodes', 'PollNow', 'N' + nodeid)

{'Message': 'ProvideFault failed, check fault information.', 'ExceptionType': 'System.ServiceModel.FaultException1[[SolarWinds.Orion.Core.Common.CoreFaultContract, SolarWinds.Orion.Channels, Version=10001.1.1.183, Culture=neutral, PublicKeyToken=null]]', 'FullException': 'System.ServiceModel.FaultException1[SolarWinds.Orion.Core.Common.CoreFaultContract]: ProvideFault failed, check fault information. (Fault Detail is equal to SolarWinds.Orion.Core.Common.CoreFaultContract(Unknown): System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: N3685\r\nParameter name: entityIdentifier (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:\nSystem.ArgumentOutOfRangeException: N3685\r\nParameter name: entityIdentifier\n at SolarWinds.Collector.Contract.Entity.DecomposeIdentifier(String entityIdentifier, String& netObjectType, Int32& id)\r\n at SolarWinds.Collector.Repository.PollingDescriptionStoreInMemory.d__c.MoveNext()\r\n at SolarWinds.Collector.PollingController.PollingController.ResolveConditionRecursive(JobExecutionCondition condition, PollInformation pollInformation, UpdatePollingContextBehavior behavior)\r\n at SolarWinds.Collector.PollingController.PollingController.JobNow(JobExecutionCondition condition, PollInformation pollInformation)\r\n at SolarWinds.Collector.PollingController.PollingController.PollNow(String entityI...).'}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.