def run(job=None, *args, **kwargs): # Disable SSL errors verify = False if not verify: requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # Get SolarWinds ConnectionInfo solarwinds = ConnectionInfo.objects.get(name='SolarWinds') swis = SwisClient(solarwinds.ip, solarwinds.username, solarwinds.password) if not solarwinds: return "FAILURE", "", "Missing required SolarWinds connection info. (Admin -> Connection Info -> New Connection Info)" # Get Server Info server = job.server_set.first() # Find the Uri you want to delete based on a SWQL query results = swis.query("select ipaddress, caption, uri from orion.nodes where ipaddress = '{}'".format(server.ip)) # Use as needed if len(results['results']) > 1: print('Refine your search. Found more than one node matching that criteria.') elif len(results['results']) == 1: print("Deleting {}".format(results['results'][0]['ipaddress'])) response = swis.delete(results['results'][0]['uri']) print("Done") else: print("Nothing to delete from SolarWinds") return "","",""
def main(): npm_server = 'localhost' username = '******' password = '' swis = SwisClient(npm_server, username, password) print("Discover and add interfaces:") results = swis.invoke('Orion.NPM.Interfaces', 'DiscoverInterfacesOnNode', 1) # use the results['DiscoveredInterfaces'] for all interfaces # or get a subset of interfaces using a comprehension like below eth_only = [ x for x in results['DiscoveredInterfaces'] if x['Caption'].startswith('eth') ] print(eth_only) results2 = swis.invoke( 'Orion.NPM.Interfaces', 'AddInterfacesOnNode', 1, # use a valid nodeID! eth_only, 'AddDefaultPollers') print(results2)
def do_allocate_ip(self, auth_credentials, cert): username = auth_credentials["privateKeyId"] password = auth_credentials["privateKey"] hostname = self.inputs['endpoint']['endpointProperties']['hostName'] global swis swis = SwisClient(hostname, username, password) requests.packages.urllib3.disable_warnings() allocation_result = [] try: resource = self.inputs["resourceInfo"] for allocation in self.inputs["ipAllocations"]: allocation_result.append( allocate(resource, allocation, self.context, self.inputs["endpoint"])) except Exception as e: try: rollback(allocation_result) except Exception as rollback_e: logging.error( f"Error during rollback of allocation result {str(allocation_result)}" ) logging.error(rollback_e) raise e assert len(allocation_result) > 0 return {"ipAllocations": allocation_result}
def do_get_ip_ranges(self, auth_credentials, _): """ Main function. Get inputs, create connection with IPAM server, execute operation and prepare results """ username = auth_credentials["privateKeyId"] password = auth_credentials["privateKey"] ignore_ssl_warning = self.inputs["endpoint"]["endpointProperties"] \ ["ignoreSslWarning"].lower() == "true" if ignore_ssl_warning: requests.packages.urllib3.disable_warnings(InsecureRequestWarning) swis = SwisClient(self.inputs["endpoint"]["endpointProperties"] \ ["hostName"], username, password) page_token = self.inputs['pagingAndSorting'].get('pageToken', None) max_results = self.inputs['pagingAndSorting'].get('maxResults', 25) dns_servers = get_input_property(self.inputs, "SolarWinds.dnsServers") dns_domain = get_input_property(self.inputs, "SolarWinds.dnsDomain") ranges, next_page_token = collect_ranges(swis, page_token, max_results, \ dns_servers, dns_domain) result = {"ipRanges": ranges} if next_page_token is not None: result["nextPageToken"] = next_page_token return result
def run(job=None, *args, **kwargs): # Disable SSL errors verify = False if not verify: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # Get SolarWinds ConnectionInfo solarwinds = ConnectionInfo.objects.get(name='SolarWinds') swis = SwisClient(solarwinds.ip, solarwinds.username, solarwinds.password) if not solarwinds: return "FAILURE", "", "Missing required SolarWinds connection info. (Admin -> Connection Info -> New Connection Info)" # Get Server Info server = job.server_set.first() hostname = "{}.{}".format(server.hostname, server.env_domain) #ip_address = server.ip # Query Solarwinds for the FQDN & IP job.set_progress("Checking if hostname '{}' is already in SolarWinds".format(hostname)) hostname_results = swis.query("select n.ipaddress, n.nodename from orion.nodes n where nodename = '{}'".format(hostname)) #ip_results = swis.query("select n.ipaddress, status from orion.nodes n where status=2 and ipaddress ='{}'".format(ip_address)) #if len(hostname_results) | len(ip_results) > 0: if len(hostname_results.values()[0]) > 0: return 'FAILURE', '', "Found hostname '{}' in Solarwinds.".format(hostname) else: job.set_progress("'{}' not found in Solarwinds.".format(hostname)) return "","",""
def do_get_ip_ranges(self, auth_credentials, cert): username = auth_credentials["privateKeyId"] password = auth_credentials["privateKey"] hostname = self.inputs["endpoint"]["endpointProperties"]["hostName"] requests.packages.urllib3.disable_warnings() swis = SwisClient(hostname, username, password) result_ranges = [] qResult = swis.query( "SELECT DISTINCT GroupID AS id, FriendlyName AS name, Address AS addressSpaceId, CIDR AS subnetPrefixLength, Comments AS description, i.CustomProperties.Gateway as gatewayAddress, i.CustomProperties.DNS_Servers as dnsServers, i.CustomProperties.Site_ID AS siteId FROM IPAM.GroupNode i WHERE GroupTypeText LIKE 'Subnet' AND i.CustomProperties.VRA_Range = TRUE" ) for range in qResult['results']: logging.info(f"Found subnet: {str(range['name'])}") network = ipaddress.ip_network( str(range['addressSpaceId']) + '/' + str(range['subnetPrefixLength'])) range['ipVersion'] = 'IPv' + str(network.version) range['startIPAddress'] = str(network[10]) range['endIPAddress'] = str(network[-6]) range['dnsServerAddresses'] = [ server.strip() for server in str(range['dnsServers']).split(',') ] range['tags'] = [{"key": "Site", "value": range['siteId']}] result_ranges.append(range) result = {"ipRanges": result_ranges} return result
def do_validate_endpoint(self, auth_credentials, _): """ Main function. Get inputs, create connection with IPAM server, execute test request and prepare results """ try: username = auth_credentials["privateKeyId"] password = auth_credentials["privateKey"] ignore_ssl_warning = self.inputs["endpointProperties"] \ ["ignoreSslWarning"].lower() == "true" if ignore_ssl_warning: requests.packages.urllib3.disable_warnings(InsecureRequestWarning) swis = SwisClient(self.inputs["endpointProperties"]["hostName"], \ username, password) logging.info("Start testing endpoint") query = """SELECT TOP 3 NodeID, DisplayName FROM Orion.Nodes WHERE DisplayName='test_request' """ response = swis.query(query) logging.info("Received the following response: %s", str(response)) if response: return {"message": "Validated successfully", "statusCode": "200"} except Exception as error: logging.error("Unexpected exception: %s", str(error)) raise error #return self._build_error_response("5000", str(error)) return None
def main(): npm_server = 'localhost' username = '******' password = '' swis = SwisClient(npm_server, username, password) ip = '10.199.252.6' data = swis.query('SELECT NodeID FROM Cirrus.Nodes WHERE AgentIP = @ip', ip=ip)['results'] nodeId = data[0]['NodeID'] script = 'show clock' swis.invoke('Cirrus.ConfigArchive', 'Execute', [nodeId], script, username) transferId = '{{{0}}}:{1}:ExecuteScript'.format(nodeId, username) status = 'Queued' while status != 'Complete' and status != 'Error': sleep(1) data = swis.query('SELECT T.Status, T.Error FROM Cirrus.TransferQueue T WHERE T.TransferID=@transfer', transfer=transferId)['results'] status = data[0]['Status'] data = swis.query('SELECT T.Log FROM Cirrus.TransferQueue T WHERE T.TransferID=@transfer', transfer=transferId)['results'] output = data[0]['Log'] print(output)
def main(): global __SWIS__ module = AnsibleModule( argument_spec=dict(hostname=dict(required=True), username=dict(required=True, no_log=True), password=dict(required=True, no_log=True), state=dict(required=True, choices=['update']), node_id=dict(required=False), caption=dict(required=False), env=dict(required=False), fisma=dict(required=False), project_lead=dict(required=False), sme=dict(required=False))) options = { 'hostname': module.params['hostname'], 'username': module.params['username'], 'password': module.params['password'] } __SWIS__ = SwisClient(**options) try: __SWIS__.query('SELECT Uri FROM Orion.Environment') except Exception as e: module.fail_json( msg= "Failed to query Orion. Check Hostname, Username, and Password : {0}" .format(str(e))) if module.params['state'] == 'update': _custom_props(module)
def main(): npm_server = '10.200.21.19' username = '******' password = '******' swis = SwisClient(npm_server, username, password) print("Add an SNMP v2c node:")
def __init__(self): fields = { "nodename": {"required": True, "type": "str"}, "ip_address": {"required": True, "type": "str"}, "device_func": {"default": "", "type": "str"}, "action": {"required": True, "type": "str"}, } module = AnsibleModule(argument_spec=fields) """Check if module exists before importing""" try: imp.find_module('orionsdk') from orionsdk import SwisClient except ImportError: module.fail_json(msg="'orionsdk' not found. Is the module installed?") module.exit_json(changed=True) SW_Server = 'solarwinds.nj01' SW_User = '******' SW_Passwd = 'SOLAR_5689!' self.swis = SwisClient(SW_Server, SW_User, SW_Passwd) self.node = module.params['nodename'] self.ipaddr = module.params['ip_address'] self.action = module.params['action'] self.devfunc = module.params['device_func'] self.module = module requests.packages.urllib3.disable_warnings()
def client(self): verify = os.getenv('APIALCHEMY_SOLARWINDS_SSL_VERIFY', 'true').lower() == 'true' if not verify: urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) return SwisClient(*self._conn_params.values(), verify=verify)
def do_allocate_ip(self, auth_credentials, _): """ Main function. Get inputs, create connection with IPAM server, execute operation and prepare results """ username = auth_credentials["privateKeyId"] password = auth_credentials["privateKey"] ignore_ssl_warning = self.inputs["endpoint"]["endpointProperties"] \ ["ignoreSslWarning"].lower() == "true" if ignore_ssl_warning: requests.packages.urllib3.disable_warnings(InsecureRequestWarning) swis = SwisClient(self.inputs["endpoint"]["endpointProperties"] \ ["hostName"], username, password) allocation_result = [] try: #resource = self.inputs["resourceInfo"] for allocation in self.inputs["ipAllocations"]: allocation_result.append(allocate(swis, allocation)) except Exception as error: try: rollback(swis, allocation_result) except Exception as rollback_e: logging.error("Error in IP deallocation %s", str(allocation_result)) logging.error(rollback_e) raise error assert len(allocation_result) > 0 return { "ipAllocations": allocation_result }
def do_validate_endpoint(self, auth_credentials, cert): username = auth_credentials["privateKeyId"] password = auth_credentials["privateKey"] hostname = self.inputs["endpointProperties"]["hostName"] swis = SwisClient(hostname, username, password) requests.packages.urllib3.disable_warnings() try: response = swis.invoke( 'Metadata.Entity', 'GetAliases', 'SELECT B.Caption FROM Orion.Nodes B' ) if response != "": return { "message": "Validated successfully" } else: raise Exception("Failed to connect") except Exception as e: """ In case of SSL validation error, a InvalidCertificateException is raised. So that the IPAM SDK can go ahead and fetch the server certificate and display it to the user for manual acceptance. """ # if "SSLCertVerificationError" in str(e) or "CERTIFICATE_VERIFY_FAILED" in str(e) or 'certificate verify failed' in str(e): # raise InvalidCertificateException("certificate verify failed", self.inputs["endpointProperties"]["hostName"], 443) from e raise e
def main(): npm_server = 'localhost' username = '******' password = '' swis = SwisClient(npm_server, username, password) print("Add an SNMP v2c node:") # fill these in for the node you want to add! ip_address = '127.0.0.1' community = 'public' # set up property bag for the new node props = { 'IPAddress': ip_address, 'EngineID': 1, 'ObjectSubType': 'SNMP', 'SNMPVersion': 2, 'Community': community, 'DNS': '', 'SysName': '' } print("Adding node {}... ".format(props['IPAddress']), end="") results = swis.create('Orion.Nodes', **props) print("DONE!") # extract the nodeID from the result nodeid = re.search(r'(\d+)$', results).group(0) pollers_enabled = { 'N.Status.ICMP.Native': True, 'N.Status.SNMP.Native': False, 'N.ResponseTime.ICMP.Native': True, 'N.ResponseTime.SNMP.Native': False, 'N.Details.SNMP.Generic': True, 'N.Uptime.SNMP.Generic': True, 'N.Cpu.SNMP.HrProcessorLoad': True, 'N.Memory.SNMP.NetSnmpReal': True, 'N.AssetInventory.Snmp.Generic': True, 'N.Topology_Layer3.SNMP.ipNetToMedia': False, 'N.Routing.SNMP.Ipv4CidrRoutingTable': False } pollers = [] for k in pollers_enabled: pollers.append({ 'PollerType': k, 'NetObject': 'N:' + nodeid, 'NetObjectType': 'N', 'NetObjectID': nodeid, 'Enabled': pollers_enabled[k] }) for poller in pollers: print(" Adding poller type: {} with status {}... ".format( poller['PollerType'], poller['Enabled']), end="") response = swis.create('Orion.Pollers', **poller) print("DONE!")
def main(): module = AnsibleModule(argument_spec=dict( api_url=dict(required=True, default=None), username=dict(required=True, default=None), password=dict(required=True, default=None, no_log=True), subnet=dict(required=True), validate_certs=dict(required=False, default=True)), required_together=[['username', 'password']], supports_check_mode=False) api_url = module.params['api_url'] username = module.params['username'] password = module.params['password'] subnet = module.params['subnet'] validate_certs = module.params['validate_certs'] requests.packages.urllib3.disable_warnings(InsecureRequestWarning) client = SwisClient(api_url, username, password, verify=validate_certs) query = "SELECT TOP 255 I.DisplayName FROM IPAM.IPNode I WHERE Status=2 AND I.Subnet.DisplayName Like '{}%'".format( subnet) response = client.query(query) available_ip_addresses = [ ip_node['DisplayName'] for ip_node in response['result'] ] module.exit_json(changed=True, available_ip_addresses=available_ip_addresses)
def main(): # Connect to SWIS server = 'localhost' username = '******' password = '' swis = SwisClient(server, username, password) # Disable/Enable CBQoS Sources node_caption = 'My testing router' query_results = swis.query( 'SELECT NodeID FROM Orion.Nodes WHERE Caption = @nodecaption_par', nodecaption_par=node_caption) node_id = query_results['results'][0]['NodeID'] query_results = swis.query( 'SELECT Uri FROM Orion.Netflow.CBQoSSource WHERE NodeID = @nodeid_par', nodeid_par=node_id) enabled_flag = False # Change this value to True if you want to enable sources props = {'Enabled': enabled_flag} for row in query_results['results']: swis.update(row['Uri'], **props) # Print results query_results = swis.query( 'SELECT CBQoSSourceID FROM Orion.Netflow.CBQoSSource WHERE NodeID = @nodeid_par and Enabled = @enabled_par', nodeid_par=node_id, enabled_par=enabled_flag) print( 'Changed enabled status to {0} for {1} CBQoS sources for node with ID {2}' .format(enabled_flag, len(query_results['results']), node_id))
def solarwinds_query(npm_server, username, 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) node_results = swis.query("SELECT IPAddress from Orion.Nodes n where n.Vendor = 'Cisco'") return node_results
def __init__(self): with open('/path/to/creds.json') as credentials: self.creds = json.load(credentials) self.npm_server = 'x.x.x.x' # Your server that's running Solarwinds self.username = self.creds['sw_username'] self.password = self.creds['sw_password'] requests.packages.urllib3.disable_warnings() self.swis = SwisClient(self.npm_server, self.username, self.password)
def __init__(self, user, pwd, url): self._user = user self._pwd = pwd self.auth = (self._user, self._pwd) if re.search('http://(.+)', url): stripped = re.search('http://(.+)', url) url = stripped.group(1) self._swis = SwisClient(url, user, pwd)
def main(): npm_server = 'localhost' username = '******' password = '' swis = SwisClient(npm_server, username, password) print("Invoke Test:") aliases = swis.invoke('Metadata.Entity', 'GetAliases', 'SELECT B.Caption FROM Orion.Nodes B') print(aliases)
def __init__(self): # start the connection self.server = 'server fqdn or ip' self.username = '******' self.password = '******' self.con = SwisClient(self.server,self.username,self.password) requests.packages.urllib3.disable_warnings()
def connect(self): """ Connect to the Orion server listed in the config. """ self.client = SwisClient(self.config['orion_host'], self.config['orion_user'], self.config['orion_password']) return self.config['orion_label']
def main(): npm_server = 'localhost' username = '******' password = '' swis = SwisClient(npm_server, username, password) print("Query Test:") results = swis.query("SELECT Uri FROM Orion.Nodes WHERE NodeID=@id", id=1) # set valid NodeID! uri = results['results'][0]['Uri'] print(uri)
def connect(self, platform): """ Connect to an Orion platform from the packs config.yaml. """ try: self.client = SwisClient( self.config['orion'][platform]['host'], self.config['orion'][platform]['user'], self.config['orion'][platform]['password']) except KeyError: raise ValueError("Orion host details not in the config.yaml")
def main(): npm_server = 'localhost' username = '******' password = '' AlertID = 1 #AlertID for which we export data in xml file. swis = SwisClient(npm_server, username, password) results = swis.invoke('Orion.AlertConfigurations', 'Export', AlertID) print(results) with open('out.xml', 'w') as f: f.write(results)
def main(): hostname = 'localhost' username = '******' password = '' swis = SwisClient(hostname, username, password) results = swis.query('SELECT TOP 1 NodeID FROM Orion.Nodes') interfaceId = results['results'][0]['NodeID'] netObjectId = 'N:{}'.format(interfaceId) now = datetime.utcnow() tomorrow = now + timedelta(days=1) swis.invoke('Orion.Nodes', 'Unmanage', netObjectId, now, tomorrow, False)
def setAllTargetGroups(): #get all nodes from target server to create index for URI swis = SwisClient(TargetServer['ip'], TargetServer['username'], TargetServer['password'], TargetServer['verify']) results = swis.query("SELECT Name, Uri FROM Orion.Container") try: for row in results['results']: TargetGroups.append({row['Name']:row['Uri']}) return TargetGroups except(KeyError): try: print results['Message'] except(KeyError): print "Error"
def main(): npm_server = 'localhost' username = '******' password = '' importfile = 'out.xml' #file which contain AlertConfiguration in xml format. swis = SwisClient(npm_server, username, password) with open(importfile, 'r') as f: alert = f.read() results = swis.invoke('Orion.AlertConfigurations', 'Import', alert) print(results)
def __init__(self, *args, verify=settings.ORION_VERIFY_SSL_CERT): """ :arg args: (host, user, password) for the orion server this is not the cleanest implementation because we are not doing any error checking. OTOH, this is not exactly aiming for production quality but for expediency """ if not args: args = SRC_DEFAULTS self.orion_connection = SwisClient(*args, verify=verify)