def __init__(self): self.username = getpass.getpass() self.password = getpass.getpass() self.DB = orionsdk.SwisClient("172.16.3.57", self.username, self.password) self.Command = "show interfaces status" self.SettupXL() self.SWData = self.GetData()
def connect(self): config_details = config('config.ini', 'orion') hostname = config_details['host'] username = config_details['user'] password = config_details['pass'] conn = orionsdk.SwisClient(hostname, username, password) return conn
def callback(): print "Starting to pipe Data ORION --> Influxdb" mostRecent = 0 #====================================MAIN WORK================================================== if "DateTime" not in SQL: print "Please Insert DateTime to the Query for TimeSeries Data" sys.exit() client = InfluxDBClient(influxdb, dbport, dbID, dbPass, dbName) client.create_database(dbName) #open InfluxDB server to connect while (True): #turn of the Certificate warning start_time = time.time() requests.packages.urllib3.disable_warnings() #getting query done. Prefer input as the locahost name rather than dynamic IP address. swis = orionsdk.SwisClient(SolarWinds, SWID, SWPass) try: data = swis.query(SQL) except: print ("SolarWinds ID or Pass is wrong") sys.exit() #preparing to get the titles and table name SQL_temp = SQL SQL_temp = SQL_temp.replace(',','') values = SQL_temp.split( ) leng = len(values) #this loop is to get the title of each entry for x in range( 1, (leng-2)): values[x] #this line is to get the name of the table measurement = values[leng -1] data_str = json.dumps(data) data_list = ast.literal_eval(data_str)["results"] data_arr = json.loads(data_str) rowsTitle = data_arr["results"] L = [] #mostRecent = getRecentDateInflux(client) #potential Performance Issue for i in range(len(rowsTitle)-1,-1,-1): if (convertUnixTime(rowsTitle[i]['DateTime']) < mostRecent): print "Database is Up-To-Date" break #if (mostRecent != 0): # print "Most Update Datapoint is " + str(convertToUTC(mostRecent)) onePoint=submitPoint(rowsTitle,measurement,i) L.append(onePoint) client.write_points(L) print "Run time " + str((time.time()-start_time)) print "Executing again in " + str(t)+ " seconds\n\n\n" time.sleep(t);
def callback(): print "Starting to pipe Data ORION --> Influxdb" if "DateTime" not in SQL: print "Please Insert DateTime to the Query for TimeSeries Data" sys.exit() #open InfluxDB server to connect try: client = InfluxDBClient(influxdb, dbport, dbID, dbPass, dbName) client.create_database(dbName) except: print("InfluxDb server/port/ID or Pass is wrong") sys.exit() latestPointSW = {} while (True): #turn of the Certificate warning start_time = time.time() requests.packages.urllib3.disable_warnings() #getting query done. Prefer input as the locahost name rather than dynamic IP address. swis = orionsdk.SwisClient(SolarWinds, SWID, SWPass) try: data = swis.query(SQL) except: print("SolarWinds ID or Pass is wrong") sys.exit() #preparing to get the titles and table name SQL_temp = SQL SQL_temp = SQL_temp.replace(',', '') #this line is to get the name of the table measurement = getMeasurement(SQL_temp) data_str = json.dumps(data) data_arr = json.loads(data_str) rowsTitle = data_arr["results"] L = [] for i in range(0, len(rowsTitle) - 1): onePoint = submitPoint(rowsTitle, measurement, i) #Check to see which is the latest point posting to InfluxDB if (cmp(latestPointSW, onePoint) == 0): print "Database is Up-To-Date" break L.append(onePoint) if not L: p = 1 #useless code, just for syntax purpose else: latestPointSW = L[0] client.write_points(L) print "Run time " + str((time.time() - start_time)) print "Executing again in " + str(t) + " seconds\n\n\n" time.sleep(t)
def callback(): print "thread started" t = 0.1 t = t * 60 mostRecent = 0 #====================================MAIN WORK================================================== start_time = time.time() if "DateTime" not in SQL: sys.exit("Please Insert DateTime to the Query for TimeSeries Data") while (True): #turn of the Certificate warning requests.packages.urllib3.disable_warnings() #getting query done. Prefer input as the locahost name rather than dynamic IP address. swis = orionsdk.SwisClient(SolarWinds, SWID, SWPass) data = swis.query(SQL) #preparing to get the titles and table name SQL_temp = SQL SQL_temp = SQL_temp.replace(',', '') values = SQL_temp.split() leng = len(values) #this loop is to get the title of each entry for x in range(1, (leng - 2)): values[x] #this line is to get the name of the table measurement = values[leng - 1] data_str = json.dumps(data) data_list = ast.literal_eval(data_str)["results"] data_arr = json.loads(data_str) rowsTitle = data_arr["results"] L = [] #open InfluxDB server to connect client = InfluxDBClient(influxdb, dbport, dbID, dbPass, dbName) client.create_database(dbName) mostRecent = getRecentDateInflux(client) for i in range(len(rowsTitle) - 1, -1, -1): if (convertUnixTime(rowsTitle[i]['DateTime']) < mostRecent): print "database is Updated" break print i onePoint = submitPoint(rowsTitle, measurement, i) L.append(onePoint) client.write_points(L) print(time.time() - start_time) print "executing again in " + str(t) + " seconds" time.sleep(t)
def orion_init(): """ Prompts for Orion credentials and returns a SwisClient object """ global orion_server global orion_username global orion_password if not orion_username: default_username = getuser() orion_username = raw_input('Orion username [' + default_username + ']: ') or default_username if not orion_password: orion_password = getpass('Orion password: '******'SolarWinds-Orion', orion_username, orion_password, verify='server.pem')
t = t * 60 #check for the latest entry in influxdb table mostRecent = 0 #====================================MAIN WORK================================================== start_time = time.time() if "DateTime" not in SQL: sys.exit("Please Insert DateTime to the Query for TimeSeries Data") client = InfluxDBClient(influxdb, dbport, dbID, dbPass, dbName) client.create_database(dbName) while (True): #turn of the Certificate warning requests.packages.urllib3.disable_warnings() #getting query done. Prefer input as the locahost name rather than dynamic IP address. swis = orionsdk.SwisClient(SolarWinds, SWID, SWPass) data = swis.query(SQL) #preparing to get the titles and table name SQL_temp = SQL SQL_temp = SQL_temp.replace(',', '') values = SQL_temp.split() leng = len(values) #this loop is to get the title of each entry for x in range(1, (leng - 2)): values[x] #this line is to get the name of the table measurement = values[leng - 1] data_str = json.dumps(data)
def initialiseIPAM(IPAM_HOST,IPAM_USER,IPAM_PW): swis = orionsdk.SwisClient(IPAM_HOST,IPAM_USER,IPAM_PW)
def createIPAM(): # Get credentials for IPAM and assign to orion SDK swisclient login print("Input IPAM credentials. UPSport username and password.") username = input("username: "******"test-UPS-0111.UPS.int", "UPS\\" + str(username), str(password)) for vlanID, vlanNameSub in vlans.items(): vlanName, subnet = vlanNameSub.split(",") subnet, mask = subnet.split('/') splitOctets = subnet.split('.') subnetBlock = '.'.join(subnet.split('.')[:-2]) if envList[envNr] == "DEV": if subnetBlock == "192.248": pID = 832 elif subnetBlock == "192.249": pID = 949 elif subnetBlock == "192.251": pID = 3449 elif subnetBlock == "192.252": pID = 952 elif subnetBlock == "192.253": pID = 992 elif subnetBlock == "192.254": pID = 994 elif subnetBlock == "192.168": pID = 997 else: print("Subnet range specified is not in DEV domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.19.254.40', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', } elif envList[envNr] == "NDC": if subnetBlock == "192.225": pID = 3960 else: print("Subnet range specified is not in NDC domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, # 'DisableNeighborScanning': False, # 'NeighborScanAddress': '***', # 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', # 'Primary_DNS':'*****', # 'Secondary_DNS':'*****', # 'Nessus_Asset_Range':str(subnet + "/" + mask), # 'Nessus_Asset_List':'IPAM-*****', } elif envList[envNr] == "FCN" or envList[envNr] == "FEN": if subnetBlock == "192.192": pID = 3436 elif subnetBlock == "192.193": pID = 3437 elif subnetBlock == "192.194": pID = 4017 elif subnetBlock == "192.30": pID = 773 else: print("Subnet range specified is not in FCN domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.19.254.120', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', 'Primary_DNS':'192.192.0.11', 'Secondary_DNS':'192.192.0.12', 'Nessus_Asset_Range':str(subnet + "/" + mask), 'Nessus_Asset_List':'IPAM-LIST-NETWORK', } elif envList[envNr] == "RYC": if subnetBlock == "192.28": pID = 4243 elif subnetBlock == "201.46": pID = 1647 elif subnetBlock == "62.62": pID = 1032 elif subnetBlock == "202.46": pID = 817 else: print("Subnet range specified is not in RYC domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, # 'DisableNeighborScanning': False, # 'NeighborScanAddress': '***', # 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', } elif envList[envNr] == "RPC": if subnetBlock == "192.0": pID = 1085 elif subnetBlock == "192.1": pID = 1087 elif subnetBlock == "192.3": pID = 3975 elif subnetBlock == "192.46": pID = 1644 elif subnetBlock == "192.240": pID = 1115 elif subnetBlock == "192.241": pID = 1165 elif subnetBlock == "192.242": pID = 1167 elif subnetBlock == "192.243": pID = 1170 else: print("Subnet range specified is not in RPC domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.19.254.20', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', 'Primary_DNS':'192.1.13.11', 'Secondary_DNS':'192.1.13.12', 'Nessus_Asset_Range':str(subnet + "/" + mask), 'Nessus_Asset_List':'IPAM-CORE-NETWORK', } elif envList[envNr] == "SPO": if subnetBlock == "192.128": pID = 1243 elif subnetBlock == "192.191": pID = 1240 elif subnetBlock == "150.50": pID = 1642 elif subnetBlock == "159.46": pID = 1187 elif subnetBlock == "192.168": pID = 1201 else: print("Subnet range specified is not in SPO domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.19.254.110', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', 'Primary_DNS':'192.128.41.11', 'Secondary_DNS':'192.128.41.12', 'Nessus_Asset_Range':str(subnet + "/" + mask), 'Nessus_Asset_List':'IPAM-CENTRE-NETWORK', } elif envList[envNr] == "DMZ": if subnetBlock == "192.20": pID = 1659 elif subnetBlock == "192.224": pID = 1605 elif subnetBlock == "192.64": pID = 1381 elif subnetBlock == "192.65": pID = 1623 elif subnetBlock == "192.66": pID = 1619 elif subnetBlock == "192.67": pID = 3971 elif subnetBlock == "192.68": pID = 3973 elif subnetBlock == "192.69": pID = 4185 elif subnetBlock == "192.70": print("No subnets exist in this folder at present, please add this one manually to IPAM and inform script admin.") elif subnetBlock == "192.91": pID = 1656 elif subnetBlock == "192.17": pID = 3482 elif subnetBlock == "192.168": pID = 1467 else: print("Subnet range specified is not in DMZ domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.19.254.60', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', # 'Primary_DNS':'***', # 'Secondary_DNS':'***', 'Nessus_Asset_Range':str(subnet + "/" + mask), 'Nessus_Asset_List':'IPAM-DMZ-NETWORK', } elif envList[envNr] == "AZP": if subnetBlock == "192.100": pID = 1052 elif subnetBlock == "192.96": pID = 1042 elif subnetBlock == "192.98": pID = 1059 elif subnetBlock == "192.99": pID = 1066 elif subnetBlock == "192.168": pID = 1635 else: print("Subnet range specified is not in AZP domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.100.47.129', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', # 'Primary_DNS':'***', # 'Secondary_DNS':'***', # 'Nessus_Asset_Range':str(subnet + "/" + mask), # 'Nessus_Asset_List':'***', } elif envList[envNr] == "RND": if subnetBlock == "192.29": pID = 3416 else: print("Subnet range specified is not in RND domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.100.47.129', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', # 'Primary_DNS':'***', # 'Secondary_DNS':'***', # 'Nessus_Asset_Range':str(subnet + "/" + mask), # 'Nessus_Asset_List':'***', } elif envList[envNr] == "UPS": if subnetBlock == "192.16": pID = 301 elif subnetBlock == "192.19": pID = 351 else: print("Subnet range specified is not in UPS domain, please check your information, exiting.") sys.exit(0) prSPO = { 'FriendlyName': str(subnet + "/" + mask), 'Comments': str(vlanName), 'ScanInterval': 60, 'DisableNeighborScanning': False, 'NeighborScanAddress': '192.19.254.30', 'NeighborScanInterval': 60, 'VLAN': str(vlanID), 'Location':'Belfast', } customPrSPO = { 'Country_City':'Belfast HQ', 'Primary_DNS':'192.16.62.11', 'Secondary_DNS':'192.16.62.12', 'Nessus_Asset_Range':str(subnet + "/" + mask), 'Nessus_Asset_List':'IPAM-UPS-NETWORK', } #Create Subnet and move under correct folder results = swis.invoke('IPAM.SubnetManagement', 'CreateSubnet', str(subnet), int(mask)) results = swis.query("SELECT TOP 10 Uri FROM IPAM.Subnet WHERE Address='" + str(subnet) + "'""") uriSubnet = results['results'][0]['Uri'] results = swis.update("" + str(uriSubnet) + "", ParentId=int(pID), **prSPO) #Update Subnet Custom Properties - results = swis.query("SELECT TOP 10 SubnetId FROM IPAM.Subnet WHERE Address='" + str(subnet) + "'""") #find new subnet subnetId = results['results'][0]['SubnetId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.GroupNodeDisplayCustomProperties/GroupId=" + str(subnetId) + "/CustomProperties", **customPrSPO) #create GCP results = swis.invoke('IPAM.SubnetManagement', 'ChangeDisableAutoScanning', str(subnetId), True) #create GCP # # IP ALLOCATE section fwPrefix = { "RPC":"FO", "SPO":"FE", "DMZ":"FD", "DEV":"FR", "AZP":"FP", "UPS":"FS", "FCN":"CN", "FEN":"CN", "NDC":"DC", "RYC":"N/A" } subnetBlock = '.'.join(subnet.split('.')[:-1]) if mask == '16' or mask == '17' or mask == '18' or mask == '19' or mask == '20' or mask == '21' or mask == '22' or mask == '23' or mask == '24' and envList[envNr] != "RYC": #SET VIP results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetBlock) + ".10""'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", DnsBackward = str(fwPrefix[envList[envNr]]) + '-VIP-VLAN' + str(vlan), Alias = str(fwPrefix[envList[envNr]]) + '-VIP-VLAN' + str(vlan), Status = '1', SysName = 'Checkpoint Firewall', SkipScan = True, Comments = str(fwPrefix[envList[envNr]]) + '-VIP-VLAN' + str(vlan)) #Set Gateway IP in settings results = swis.query("SELECT TOP 10 SubnetId FROM IPAM.Subnet WHERE Address='" + str(subnet) + "'""") #find new subnet subnetId = results['results'][0]['SubnetId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.GroupNodeDisplayCustomProperties/GroupId=" + str(subnetId) + "/CustomProperties", Gateway_IP=str(subnetBlock) + ".10") #create GCP #SET PHYSICAL IP 1 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetBlock) + ".5""'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", DnsBackward = str(fwPrefix[envList[envNr]]) + '-1-VLAN' + str(vlan), Alias = str(fwPrefix[envList[envNr]]) + '-1-VLAN' + str(vlan), Status = '1', SysName = 'Checkpoint Firewall', SkipScan = True, Comments = str(fwPrefix[envList[envNr]]) + '-1-VLAN' + str(vlan)) #SET PHYSICAL IP 2 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetBlock) + ".6""'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", DnsBackward = str(fwPrefix[envList[envNr]]) + '-2-VLAN' + str(vlan), Alias = str(fwPrefix[envList[envNr]]) + '-2-VLAN' + str(vlan), Status = '1', SysName = 'Checkpoint Firewall', SkipScan = True, Comments = str(fwPrefix[envList[envNr]]) + '-2-VLAN' + str(vlan)) i = 1 while i < 5: #SET ReSUBved IP 1 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetBlock) + "." + str(i) + "'") ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", Alias = 'Reserved', Status = '4', SysName = 'SSP', SkipScan = True, Comments = 'Reserved') i += 1 e = 7 while e < 10: #SET ReSUBved IP 1 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetBlock) + "." + str(e) + "'") ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", Alias = 'Reserved', Status = '4', SysName = 'SSP', SkipScan = True, Comments = 'Reserved') e += 1 i = 0 lastOctet = int(splitOctets[3]) subnetSlice = '.'.join(subnet.split('.')[:-1]) if mask == '25' or mask == '26' or mask == '27' or mask == '28' or mask == '29' and envList[envNr] != "RYC": #SET VIP results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetSlice) + "." + str(lastOctet + (i + 1)) + "'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", DnsBackward = str(fwPrefix[envList[envNr]]) + '-VIP-VLAN' + str(vlan), Alias = str(fwPrefix[envList[envNr]]) + '-VIP-VLAN' + str(vlan), Status = '1', SysName = 'Checkpoint Firewall', SkipScan = True, Comments = str(fwPrefix[envList[envNr]]) + '-VIP-VLAN' + str(vlan)) #Set Gateway IP in settings results = swis.query("SELECT TOP 10 SubnetId FROM IPAM.Subnet WHERE Address='" + str(subnet) + "'""") #find new subnet subnetId = results['results'][0]['SubnetId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.GroupNodeDisplayCustomProperties/GroupId=" + str(subnetId) + "/CustomProperties", Gateway_IP=str(subnetSlice) + "." + str(lastOctet + (i + 1))) #create GCP #SET PHYSICAL IP 1 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetSlice) + "." + str(lastOctet + (i + 2)) + "'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", DnsBackward = str(fwPrefix[envList[envNr]]) + '-1-VLAN' + str(vlan), Alias = str(fwPrefix[envList[envNr]]) + '-1-VLAN' + str(vlan), Status = '1', SysName = 'Checkpoint Firewall', SkipScan = True, Comments = str(fwPrefix[envList[envNr]]) + '-1-VLAN' + str(vlan)) #SET PHYSICAL IP 2 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetSlice) + "." + str(lastOctet + (i + 3)) + "'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", DnsBackward = str(fwPrefix[envList[envNr]]) + '-2-VLAN' + str(vlan), Alias = str(fwPrefix[envList[envNr]]) + '-2-VLAN' + str(vlan), Status = '1', SysName = 'Checkpoint Firewall', SkipScan = True, Comments = str(fwPrefix[envList[envNr]]) + '-2-VLAN' + str(vlan)) #SET ReSUBved IP 1 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetSlice) + "." + str(lastOctet + (i + 4)) + "'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", Alias = 'Reserved', Status = '4', SysName = 'SSP', SkipScan = True, Comments = 'Reserved') #SET ReSUBved IP 2 results = swis.query("SELECT TOP 10 IpNodeId FROM IPAM.IPNode WHERE IPAddress='" + str(subnetSlice) + "." + str(lastOctet + (i + 5)) + "'") #find IP Uri ipNodeID = results['results'][0]['IpNodeId'] results = swis.update("swis://dev-ipam-0001.development.int/Orion/IPAM.IPNode/IpNodeId=" + str(ipNodeID) + "", Alias = 'Reserved', Status = '4', SysName = 'SSP', SkipScan = True, Comments = 'Reserved') return 0
def swisconnect(self, npm_server, username, password): swis = orionsdk.SwisClient(npm_server, username, password) return swis
import orionsdk swis = orionsdk.SwisClient("solarwinds-server", "username", "password") # This query was made to select the model numbers and IP addresses of every Cisco and Juniper device in the network devices = swis.query( "Select n.IPAddress, j.JnxContentsSerialNo, c.Model FROM Orion.Nodes n INNER JOIN NCM.Nodes AS x ON n.NodeID = x.CoreNodeID RIGHT JOIN NCM.EntityPhysicalJuniper AS j ON x.NodeID = j.NodeID RIGHT JOIN NCM.EntityPhysical AS c ON x.NodeID = c.NodeID" ) print(devices)
""" Query solarwinds NCM based on device type or other criteria, parse config, extract required data """ import re import ipaddress import sys from os import environ import orionsdk import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) swis=orionsdk.SwisClient(environ['SW_SERVER'],environ['SW_USER'],environ['SW_PASS']) device_types=['vg0','ir0','er0'] devices=[] for device_type in device_types: result=swis.query(f"select SysName from NCM.Nodes where SysName like '%{device_type}%'") devices.extend([x['SysName'] for x in result['results']]) for device in devices: cfgs=swis.query(f"select A.NodeID,A.SysName,B.Config from NCM.Nodes A INNER JOIN Cirrus.ConfigArchive B on A.NodeID=B.NodeID where A.SysName='{device}' ORDER BY B.DownloadTime") cfgs=cfgs['results'][-1]['Config'] cfg=re.findall(r'ipv4\s(\d.+)\r',cfgs)
parsed_yaml = yaml.safe_load(file_contents) return parsed_yaml # Read config CONFIG = _read_yaml_file("./config/config.yaml") # Establish SolarWinds connection if not CONFIG["npm_user"]: USER = getpass.getuser() CONFIG["npm_user"] = input("Orion username [{}]: ".format(USER)) or USER if not CONFIG["npm_pass"]: CONFIG["npm_pass"] = getpass.getpass("Orion password: "******"npm_verify_cert"]: requests.packages.urllib3.disable_warnings(InsecureRequestWarning) SWIS = orionsdk.SwisClient(CONFIG["npm_server"], CONFIG["npm_user"], CONFIG["npm_pass"]) # Initialize jinja2 ENV = Environment(loader=FileSystemLoader(CONFIG["template_dir"])) def get_manual_iface(manual_iface, node_class): """ Returns standardized interface dict based on manual_iface """ iface_dict = { "node_id": "manual", "node_uri": None, "node_name": None, "node_addr": None, "node_fqdn": None, "node_class": node_class, "iface_id": "manual",
if 'Shutdown at' in response.result: return True else: return False conn.close() except: logging.warning("Couldn't reboot switch {}".format(switch_ip)) print("Couldn't reboot switch {}".format(switch_ip)) return False session = requests.Session() session.timeout = 30 # Set your timeout in seconds logging.info("Connecting to Solarwinds") swis = orionsdk.SwisClient("SolarWinds-Orion", solarwinds_username, solarwinds_password, verify=False, session=session) logging.info("Getting switches that need to reboot") nodes = swis.query("SELECT NodeID, Caption, IPAddress, Status, Nodes.CustomProperties.jun_bootpart FROM Orion.Nodes WHERE Nodes.CustomProperties.jun_bootpart LIKE 'backup%'") switches = nodes['results'] logging.debug(switches) dict_switches = [] for switch in switches: if rebootPrimary(switch['IPAddress']): dict_switch = { "Switchname": switch['Caption'], "IP-address": switch['IPAddress'], "Status": "Scheduled reboot at 22:00" }
def new_adress(request, gatuadress, shortname, popularnamn, verksamhet, postnummer, ekahau_file = None): logging.info('Create new adress: {}'.format(gatuadress)) # Check for required variables if google_api_key == '': print('Please provide your Google API key as google_api_key') logging.error('Please provide your Google API key as google_api_key') sys.exit(1) elif mist_api_token == '': print('Please provide your Mist API token as mist_api_token') logging.error('Please provide your Mist API token as mist_api_token') sys.exit(1) elif org_id == '': print('Please provide your Mist Organization UUID as org_id') logging.error('Please provide your Mist Organization UUID as org_id') sys.exit(1) # Establish Mist session admin = Admin(mist_api_token) sitegroup_lookup = {} #Kolla verksamheter sitegroups_url = "{}/orgs/{}/sitegroups".format(base_url, org_id) sitegroups_result = requests.get(sitegroups_url, headers=headers) sitegroups = json.loads(sitegroups_result.text) #Kolla sites for dubletter sites_url = "{}/orgs/{}/sites".format(base_url, org_id) sites_result = requests.get(sites_url, headers=headers) sites = json.loads(sites_result.text) # Variables site_id = None site_address = "{}, {}, {}".format(gatuadress, postalcode_cleanup( postnummer), config['mist']['config']['country']) site_verksamhet = '' site_exists = False for site in sites: if site['name'] == "{} ({})".format(gatuadress, shortname): print("Site {} ({}) already exists".format( gatuadress, shortname)) logging.info("Site {} ({}) already exists".format( gatuadress, shortname)) print('\n\n==========\n\n') site_exists = True if site_exists: messages.error(request, 'Adressen finns redan!') return False sitegroup_json = { 'name': "{}".format(verksamhet) } #Check if site group name is existing for sitegroup in sitegroups: if sitegroup['name'] == verksamhet: site_verksamhet = sitegroup['id'] if not site_verksamhet: print('Calling the Mist Create Sitegroup API...') logging.info('Calling the Mist Create Sitegroup API...') result = admin.post('/orgs/' + org_id + '/sitegroups', sitegroup_json) if result == False: print('Failed to create sitegroup {}'.format(verksamhet)) logging.warning( 'Failed to create sitegroup {}'.format(verksamhet)) print('\n\n==========\n\n') site_verksamhet = result['id'] print('\n\n==========\n\n') #Takes the field from the excel-file and create the site from that site = { 'name': "{} ({})".format(gatuadress, shortname), "sitegroup_ids": [ "{}".format(site_verksamhet) ], "notes": "{}, {}".format(popularnamn, shortname), "rftemplate_id": "{}".format(config['mist']['config']['rftemplate_id']) } # Provide your Site Setting. #Modify if anything you need is missing otherwise change in config.yaml will work best # Example can be found here: https://api.mist.com/api/v1/docs/Site#site-setting ''' ie: { 'rtsa': { 'enabled': True }, # Enable vBLE Engagement 'auto_upgrade': { 'enabled': False }, # Disable Auto Upgrade 'rogue': { 'honeypot_enabled': True # Enable Honeypot APs 'enabled': True, # Enable Rogue and Neighbor APs 'min_rssi': -80, # Minimum Neighbor RSSI Threshold -80 } } ''' site_setting = { "auto_upgrade": { "enabled": config['mist']['config']['auto_upgrade']['enabled'], "version": config['mist']['config']['auto_upgrade']['version'], "time_of_day": config['mist']['config']['auto_upgrade']['time_of_day'], "custom_versions": { "AP32": config['mist']['config']['auto_upgrade']['custom_versions']['AP32'], "AP32E": config['mist']['config']['auto_upgrade']['custom_versions']['AP32E'], "AP33": config['mist']['config']['auto_upgrade']['custom_versions']['AP33'], "AP43": config['mist']['config']['auto_upgrade']['custom_versions']['AP43'], "AP43E": config['mist']['config']['auto_upgrade']['custom_versions']['AP43E'] }, "day_of_week": config['mist']['config']['auto_upgrade']['day_of_week'] }, "rtsa": { "enabled": config['mist']['config']['rtsa']['enabled'], "track_asset": config['mist']['config']['rtsa']['track_asset'], "app_waking": config['mist']['config']['rtsa']['app_waking'] }, "led": { "enabled": config['mist']['config']['led']['enabled'], "brightness": config['mist']['config']['led']['brightness'] }, "wifi": { "enabled": config['mist']['config']['wifi']['enabled'], "locate_unconnected": config['mist']['config']['wifi']['locate_unconnected'], "mesh_enabled": config['mist']['config']['wifi']['mesh_enabled'], "detect_interference": config['mist']['config']['wifi']['detect_interference'] }, "wootcloud": config['mist']['config']['wootcloud'], "skyatp": { "enabled": config['mist']['config']['skyatp']['enabled'], "send_ip_mac_mapping": config['mist']['config']['skyatp']['send_ip_mac_mapping'] }, "persist_config_on_device": config['mist']['config']['persist_config_on_device'], "engagement": { "dwell_tags": { "passerby": config['mist']['config']['engagement']['dwell_tags']['passerby'], "bounce": config['mist']['config']['engagement']['dwell_tags']['bounce'], "engaged": config['mist']['config']['engagement']['dwell_tags']['engaged'], "stationed": config['mist']['config']['engagement']['dwell_tags']['stationed'] }, "dwell_tag_names": { "passerby": config['mist']['config']['engagement']['dwell_tag_names']['passerby'], "bounce": config['mist']['config']['engagement']['dwell_tag_names']['bounce'], "engaged": config['mist']['config']['engagement']['dwell_tag_names']['engaged'], "stationed": config['mist']['config']['engagement']['dwell_tag_names']['stationed'] }, "hours": { "sun": config['mist']['config']['engagement']['hours']['sun'], "mon": config['mist']['config']['engagement']['hours']['mon'], "tue": config['mist']['config']['engagement']['hours']['tue'], "wed": config['mist']['config']['engagement']['hours']['wed'], "thu": config['mist']['config']['engagement']['hours']['thu'], "fri": config['mist']['config']['engagement']['hours']['fri'], "sat": config['mist']['config']['engagement']['hours']['sat'] } }, "analytic": { "enabled": config['mist']['config']['analytic']['enabled'] }, "rogue": { "min_rssi": config['mist']['config']['rogue']['min_rssi'], "min_duration": config['mist']['config']['rogue']['min_duration'], "enabled": config['mist']['config']['rogue']['enabled'], "honeypot_enabled": config['mist']['config']['rogue']['honeypot_enabled'], "whitelisted_bssids": config['mist']['config']['rogue']['whitelisted_bssids'], "whitelisted_ssids": config['mist']['config']['rogue']['whitelisted_ssids'] }, "analytic": { "enabled": config['mist']['config']['rogue']['enabled'] }, "ssh_keys": config['mist']['config']['ssh_keys'], "vars": config['mist']['config']['vars'], "wids": config['mist']['config']['wids'], "mxtunnel": { "enabled": config['mist']['config']['mxtunnel']['enabled'], "vlan_ids": config['mist']['config']['mxtunnel']['vlan_ids'], "ap_subnets": config['mist']['config']['mxtunnel']['ap_subnets'], "mtu": config['mist']['config']['mxtunnel']['mtu'], "protocol": config['mist']['config']['mxtunnel']['protocol'], "clusters": config['mist']['config']['mxtunnel']['clusters'] }, "occupancy": { "min_duration": config['mist']['config']['occupancy']['min_duration'], "clients_enabled": config['mist']['config']['occupancy']['clients_enabled'], "sdkclients_enabled": config['mist']['config']['occupancy']['sdkclients_enabled'], "assets_enabled": config['mist']['config']['occupancy']['assets_enabled'], "unconnected_clients_enabled": config['mist']['config']['occupancy']['unconnected_clients_enabled'] }, "gateway_mgmt": { "app_usage": config['mist']['config']['gateway_mgmt']['app_usage'] } } # Create Site (geocoded, geocoding) = geocode(request, site_address) if geocoded == True: site.update(geocoding) else: print('Failed to geocode...') logging.warning('Failed to geocode...') messages.warning(request, 'Failed to geocode...') print(geocoding) logging.warning(geocoding) print() print('Calling the Mist Create Site API...') logging.info('Calling the Mist Create Site API...') result = admin.post('/orgs/' + org_id + '/sites', site) if result == False: print('Failed to create site {}'.format(site['name'])) logging.warning('Failed to create site {}'.format(site['name'])) print('Skipping remaining operations for this site...') logging.warning('Skipping remaining operations for this site...') print('\n\n==========\n\n') else: site_id = result['id'] print('Created site {} ({})'.format(site['name'], site_id)) logging.info('Created site {} ({})'.format(site['name'], site_id)) if show_more_details: print('\nRetrieving the JSON response object...') logging.info('\nRetrieving the JSON response object...') #print(json.dumps(result, sort_keys=True, indent=4)) logging.debug(json.dumps(result, sort_keys=True, indent=4)) print('\nUsing id in the Mist Update Setting API request') logging.info( '\nUsing id in the Mist Update Setting API request') print() # Update Site Setting print('Calling the Mist Update Setting API...') logging.info('Calling the Mist Update Setting API...') result = admin.put('/sites/' + site_id + '/setting', site_setting) if result == False: print('Failed to update site setting {} ({})'.format( site['name'], site_id)) logging.warning('Failed to update site setting {} ({})'.format( site['name'], site_id)) else: print('Updated site setting {} ({})'.format(site['name'], site_id)) logging.info('Updated site setting {} ({})'.format( site['name'], site_id)) if show_more_details: print('\nRetrieving the JSON response object...') logging.info('\nRetrieving the JSON response object...') #print(json.dumps(result, sort_keys=True, indent=4)) logging.debug(json.dumps(result, sort_keys=True, indent=4)) print('\n\n==========\n\n') # Import map try: map_url = "{}/{}/*.esx".format(import_path_ekahau, gatuadress) list_of_files = glob.glob(map_url) map_file_url = max(list_of_files, key=os.path.getctime) print(map_file_url) map_import_url = "{}/sites/{}/maps/import".format(base_url, site_id) map_import_headers = { 'Authorization': f'token {mist_api_token}' } print('Calling the Mist import map API...') logging.info('Calling the Mist import map API...') map_import_payload = {"vendor_name": "ekahau", "import_all_floorplans": True, "import_height": True, "import_orientation": True} files = { 'file': (os.path.basename(map_file_url), open(map_file_url, 'rb'), 'application/octet-stream'), 'json': (None, json.dumps(map_import_payload), 'application/json') } response = requests.post( map_import_url, files=files, headers=map_import_headers) messages.success(request, 'Ritning laddades upp') imported_aps = response.text print(imported_aps) #Getting the imported AP-modles to create packinglist project, access_points = extract_esx_data(map_file_url) access_points = access_points['accessPoints'] ap_models = Counter( access_point['model'] for access_point in access_points if access_point.get('model')) ap_models = dict(ap_models) print(ap_models) label_file_url = "{}/{}/{}".format(import_path_ekahau, gatuadress, label_file) label_title = str("{} - {}".format(gatuadress, popularnamn)) #Creating packinglist styles = getSampleStyleSheet() style = styles["BodyText"] header = Paragraph( "<bold><font size=15>{}</font></bold>".format(label_title), style) canvas = Canvas(label_file_url, pagesize=(6.2 * cm, 4 * cm)) canvas.drawString(0.1 * cm, 8.2 * cm, label_title) aW = 6 * cm aH = 3 * cm w, h = header.wrap(aW, aH) header.drawOn(canvas, 5, aH) for ap_model in ap_models: aH = aH - h ap_model_str = str("{}: {}st".format( ap_model, ap_models[ap_model])) ap_model_text = Paragraph( "<font size=15>{}</font>".format(ap_model_str), style) ap_model_text.wrap(aW, aH) ap_model_text.drawOn(canvas, 5, aH) aH = aH - h #canvas.drawString(0.1 * cm, 0.2 * cm, ap_model_str) print(ap_model_str) canvas.showPage() canvas.save() if response == False: print('Failed to import map for {} ({})'.format( site['name'], site_id)) logging.warning('Failed to import map for {} ({})'.format( site['name'], site_id)) else: print('Imported map for {} ({})'.format(site['name'], site_id)) logging.info('Imported map for {} ({})'.format( site['name'], site_id)) if show_more_details: print('\nRetrieving the JSON response object...') logging.info('\nRetrieving the JSON response object...') #print(json.dumps(result, sort_keys=True, indent=4)) logging.debug(json.dumps(result, sort_keys=True, indent=4)) print('\n\n==========\n\n') except: print("Something is not working with ekahau import") #Add Vlan to switches print('\n\n==========\n\n') print("Adding Vlans byod and guest to switches on site") session = requests.Session() session.timeout = 30 # Set your timeout in seconds logging.info("Connecting to Solarwinds") swis = orionsdk.SwisClient("SolarWinds-Orion", solarwinds_username, solarwinds_password, verify=False, session=session) logging.info("Getting switches that belong to the site") nodes = swis.query( "SELECT NodeID, Caption, IPAddress, Status FROM Orion.Nodes WHERE Caption LIKE 'swa-%-{}' AND Status LIKE 1".format(shortname)) switch_number = 0 switches = nodes['results'] for switch in switches: print(switch) addVlansToSwitch(switch) switch_number += 1 print("Updated settings on {} switches".format(switch_number)) messages.success(request, 'Lagt till VLAN på {} switchar'.format(switch_number)) return True
#!/usr/bin/env python import orionsdk import urllib3 import sys import re urllib3.disable_warnings() if len(sys.argv) < 2: print("no argument given") exit() config_id = "" rtr = str(sys.argv[1]) # Login swis = orionsdk.SwisClient("netmon.ultainc.lcl", "configdl", "Ulta123$") # Get configID for latest running config, using search config function try: config_id = str(swis.invoke("Cirrus.ConfigArchive", "ConfigSearch", rtr, "running", "", False, True)[0]) except: print("no match for given hostname") exit() # Grab config config = swis.query("SELECT Config FROM Cirrus.ConfigArchive WHERE ConfigID=" + config_id) # Regex to catch local AS and remote AS p1 = re.compile(".*(router bgp [0-9]+)\r.*") p2 = re.compile(".*(neighbor [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ remote-as [0-9]+)\r")
def startup(): send_slack_message("Starting deployment...") serverList = [] #list of servers to deploy to notDeployed = [] #list of servers where the deployment failed VARS = {} if len(sys.argv) == 1: #check if servers were given #send_slack_message("ERROR: no servers to deploy to provided.") print("ERROR: No servers to deploy to given.") printHelp() sys.exit(1) #read command line arguments coreToolsCommand = None downtime = 15 VARS["username"] = None env_vars_file = "./EnvVars.txt" #Vars file that contains commands to deploy and servers to deploy to vars_file = "./DevVars.txt.decrypted" #Vars file that contains secrets max_connections = None #Max connections that we can shut down a server with polite = False #Whether or not to check for important batch jobs automated = False #Whether or not we are reading servers from EnvVars ######THIS NEEDS TO BE ADDRESSED for i in range(1, len(sys.argv)): if "--" in sys.argv[i]: if "username" in sys.argv[i]: VARS["username"] = sys.argv[i].split("=")[1] elif "downtime" in sys.argv[i]: downtime = int(sys.argv[i].split("=")[1]) elif "help" in sys.argv[i]: printHelp() sys.exit(1) elif "envvars" in sys.argv[i]: env_vars_file = sys.argv[i].split("=")[1] elif "connections" in sys.argv[i]: max_connections = int(sys.argv[i].split("=")[1]) elif "polite" in sys.argv[i]: polite = True elif "uservars" in sys.argv[i]: vars_file = sys.argv[i].split("=")[1] elif "automated" in sys.argv[i]: automated = True elif "command" in sys.argv[i]: command = sys.argv[i].split("=")[1:] command = "=".join(command) command_len = len(command.split(" ")) i += command_len coreToolsCommand = command else: serverList.append(sys.argv[i]) VARS = readVariables(vars_file) #get secrets print() print("Connecting to the solarwinds api", end="...") sys.stdout.flush() try: swis = orionsdk.SwisClient( "###########", VARS["username"], VARS["solarwinds-pass"]) #connect to solarwinds api except Exception as e: if "401" in str(e): send_slack_message("ERROR: Invalid solarwinds credentials.") print("ERROR: Invalid Credentials") sys.exit(1) else: send_slack_message( "ERROR: Could not connect to the solarwinds API.") print("Error connecting to the solarwinds API.") sys.exit(1) print("Done") print("Connecting to the F5 management interface", end="...") sys.stdout.flush() try: mgmt = f5.bigip.ManagementRoot( "qaltm01.net.jewelry.acn", VARS["username"], VARS["password"]) #connect to f5 api except Exception as e: if "401" in str(e): send_slack_message("ERROR: Invalid f5 credentials.") print("ERROR: Invalid Credentials") sys.exit(1) else: send_slack_message( "ERROR: Could not connect to the f5 management interface.") print( "Error: Could not connect to the f5 management interface.") sys.exit(1) print("Done") notDeployed = [] if automated: deployments = read_servers(env_vars_file) for command in deployments: nohup_index = command.find("core") + 5 first_half = command[:nohup_index] second_half = command[nohup_index:] first_half = first_half + "/bin/nohup " #add nohup so that the process does not end on logout. (man nohup) nohup_command = first_half + second_half notDeployed += deploy_to_servers(nohup_command, deployments[command], swis, mgmt, VARS, downtime, max_connections) else: if coreToolsCommand == None: coreToolsCommand = input( "Input the given coretools command: ") #deploy command if polite == True: coreToolsCommand += "--polite" check_command(coreToolsCommand) nohup_index = coreToolsCommand.find("core") + 5 first_half = coreToolsCommand[:nohup_index] second_half = coreToolsCommand[nohup_index:] first_half = first_half + "/bin/nohup " #add nohup so that the process does not end on logout. (man nohup) nohup_command = first_half + second_half notDeployed += deploy_to_servers(nohup_command, serverList, swis, mgmt, VARS, downtime, max_connections) if len(notDeployed) > 0: listFailedDeploys(notDeployed)
def query_solarwinds(server, username, password, query): # logs into the server and executes query swis = orionsdk.SwisClient(server, username, password) return swis.query(query)
def main(nodeRegexArgv): config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.ini") imported = False try: config = configparser.ConfigParser() config.read(config_file) #load config files setting import_dev_list_file = ( config["DATA_PARAMETERS"]["Import_Dev_List_File"]) enable_email_notification = ( config["EMAIL_PARAMETERS"]["EnableEmailNotification"]) email_on_import = (config["EMAIL_PARAMETERS"]["EmailOnImport"]) email_on_failure = (config["EMAIL_PARAMETERS"]["EmailOnFailure"]) sw_host = config["SOLARWINDS_PARAMETERS"]["SW_Host"].split(",") sw_username = config["SOLARWINDS_PARAMETERS"]["SW_Username"] sw_password = config["SOLARWINDS_PARAMETERS"]["SW_Password"] email_server = config["EMAIL_PARAMETERS"]["EmailServer"] admin_email_sender_name = ( config["EMAIL_PARAMETERS"]["AdminEmailSenderName"]) admin_email_sender_address = ( config["EMAIL_PARAMETERS"]["AdminEmailSenderAddress"]) admin_email_receiver_name = ( config["EMAIL_PARAMETERS"]["AdminEmailReceiverName"]) admin_email_receiver_address = ( config["EMAIL_PARAMETERS"]["AdminEmailReceiverAddress"]) admin_email_subject = config["EMAIL_PARAMETERS"]["AdminEmailSubject"] except: print("Error: it is not possible to read config from file: " + config_file) sys.exit(0) def sendmail(em_msg): em_host = email_server em_sender_name = admin_email_sender_name em_sender = admin_email_sender_address em_receiver_name = admin_email_receiver_name em_receiver = admin_email_receiver_address em_subject = admin_email_subject email = send_email_SMTP(em_host, em_sender_name, em_sender, em_receiver_name, em_receiver, em_subject, em_msg) email.send() print("e-mail sent to " + admin_email_receiver_address) def runNewDevicesList(server_ip): ip = server_ip try: item_dict = swis.query("SELECT DISTINCT " + "NodeID, " + "Caption, " + "IPAddress, " + "Vendor, " + "MachineType, " + "IOSImage, " + "IOSVersion " + "FROM Orion.Nodes ORDER BY Caption ASC") item_list = item_dict["results"] device_entry = headerSpacing newDeviceReportMsg = "" for item in item_list: device_entry += ("{Caption},{IPAddress},,\n".format(**item)) f = open(import_dev_list_file, "w") f.write("#DO NOT EDIT THIS FILE. THIS FILE IS PROCESSED BY " + "PYTHON SCRIPT ntw-menu_solarwinds_import.py") f.write(device_entry) f.close() print("ntw-menu device list successfully imported!") if len(item_list) > 0: device_entry_count = str(len(item_list)) heading = ("ntw-menu device list import into " + import_dev_list_file + " has completed successfully.\n") count_msg = ( device_entry_count + " devices have been re-imported into the" + " ntw-menu. (Manual entries will remain unchanged)") device_list_msg = heading + "\n" + count_msg + "\n" return device_list_msg except: print("Failed to import device list from: " + ip + "\n") return "" script_runtime_msg = ("Script Runtime: " + datetime.now().strftime("%H:%M:%S - %d/%m/%Y")) separator_msg = ("\n" + "-" * 70 + "\n") headerSpacing = "\n" body_msg = "" requests.packages.urllib3.disable_warnings(InsecureRequestWarning) if len(sw_host) == 1: try: print("Trying to connect to and import from: " + sw_host[0]) swis = orionsdk.SwisClient(sw_host[0], sw_username, sw_password, verify="") runNewDevicesListResult = runNewDevicesList(sw_host[0]) body_msg = runNewDevicesListResult if body_msg != "": imported = True except: print("Unable to connect to and import from: " + sw_host[0]) elif imported == False: for ip in sw_host: try: if imported == False: print("Trying to connect to and import from: " + ip) swis = orionsdk.SwisClient(ip, sw_username, sw_password, verify="") runNewDevicesListResult = runNewDevicesList(ip) body_msg = runNewDevicesListResult if body_msg != "": imported = True except: print("Unable to connect to and import from: " + ip) if enable_email_notification == "True": #print("Testing availability of SMTP server: " + email_server) if imported == False: email_test_result = test_email_server(email_server) if email_test_result: if body_msg != "": if email_on_import == "True": body_msg = script_runtime_msg + "\n\n\n" + body_msg sendmail(body_msg) print("\nMessage Sent:\n" + separator_msg + body_msg + separator_msg) else: if email_on_failure == "True": body_msg = ( script_runtime_msg + "\n\n\nntw-menu device list could not be imported!" ) sendmail(body_msg) print("Message Sent:\n" + separator_msg + body_msg + separator_msg) else: print("unable to send e-mail notifications")
import orionsdk server = 'orion_server' username = '******' password = '******' ip_address = '192.168.1.1' # change this to the node you want to check sw = orionsdk.SwisClient(server, username, password) uri = sw.query("SELECT Uri FROM Orion.Nodes WHERE IPAddress=@IPAddress", IPAddress=ip_address)['results'][0]['Uri'] data = sw.invoke('Orion.AlertSuppression', 'GetAlertSuppressionState', [uri]) print(data)
import orionsdk import requests import pandas as pd import numpy import os server = os.environ['server'] name = os.environ['name'] password = os.environ['password'] swis = orionsdk.SwisClient(server, name, password) verify = False if not verify: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) def getInterface(series_length, interface_id): s = "Select TOP " s += str(series_length) s += " it.InterfaceID, it.DateTime, it.InAveragebps, it.OutAveragebps FROM Orion.NPM.InterfaceTraffic it where InterfaceID = " s += str(interface_id) s += " order by it.DateTime" results = swis.query(s) ins = list() insTrains = list() outs = list() outsTrains = list()
parser.add_argument( "-p", "--password", help="Provide the password for the given user, or omit to be prompted") args = parser.parse_args() npm_server = args.npm_server user = args.user # ask for a password if not provided in args if args.password: password = args.password else: password = getpass.getpass() # load the swis client and login to the NPM server swis = orionsdk.SwisClient(npm_server, user, password, verify=False) # define the query to run via the client query1 = """ select n.Caption from Orion.Nodes n JOIN Orion.NodesCustomProperties c ON n.nodeid = c.nodeid WHERE c.ManagingTeam = 'UNIX' ORDER BY n.caption;" """ # run the query and save the output queryresults = swis.query(query1)
ipam_server = "ipam.yourdomain.com" ipam_user = sys.argv[1] ipam_password = sys.argv[2] # Subrede a ser consultada. Ex: 10.180.200.0 subnet = sys.argv[3] # Mascara da subrede a ser consultada. Ex: 22 ou 255.255.252.0 cidr = sys.argv[4] # Transforma a mascara em CIDR caso tenha sido informada no padrao XXX.XXX.XXX.XXX if len(cidr) > 2: cidr = IPAddress(cidr).netmask_bits() #swis = orionsdk.SwisClient("SolarWinds-Orion","user","passwd", verify="server.pem") swis = orionsdk.SwisClient(ipam_server, ipam_user, ipam_password) #aliases = swis.invoke('Metadata.Entity', 'GetAliases', 'SELECT B.Caption FROM Orion.Nodes B') #print(aliases) #result = swis.query("SELECT TOP 10 IPAddress FROM Orion.Nodes") #for node in result['results']: # print(node) print(swis.invoke( 'IPAM.SubnetManagement', 'GetFirstAvailableIp', subnet, cidr ) )
""" query solarwinds IPAM based on custom-attribute name/value, extract required data """ import orionsdk import configparser config = configparser.ConfigParser() config.read('.credentials/work.ini') swis = orionsdk.SwisClient(config['orion']['host'], config['orion']['user'], config['orion']['pass']) data = swis.query( "Select Address,CIDR,Location from IPAM.GroupNode gn INNER JOIN IPAM.GroupNodeAttr gna on gn.GroupID=gna.GroupID where gna.IsPublicIPAddress='yes'" ) data = [x for x in data if x['Address'] is not None] result = {} for entry in data: if entry['Location'] in result.keys(): result[entry['Location']].add(entry['Address'] + '/' + str(entry['CIDR'])) else: result[entry['Location']] = set() result[entry['Location']].add(entry['Address'] + '/' + str(entry['CIDR'])) txt = set([ entry['Address'] + '/' + str(entry['CIDR']) + ' #' + str(entry['Location']) for entry in data
def lambda_handler(event, context): """ Script assumes Solarwinds IPAM has required groups (subnets) configured in a special way: 1) custom property "IsPublicIPAddress" should be set to "yes" 2) location information should be filled in the following format: City (full city name), Country (as a country code top-level domain, per https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains) e.g. "Moscow, RU" (no quotes) Script performs an API call to Orion Server via HTTPS (port 17778) Script uses "orionsdk" module - https://github.com/solarwinds/orionsdk-python """ # define vars res = dns.resolver.Resolver(configure=False) res.nameservers = ['1.1.24.68', '1.1.1.51'] server = os.environ['SOLARWINDS_ORION_HOST'] user = os.environ['SOLARWINDS_ORION_USER'] passwd = os.environ['SOLARWINDS_ORION_PASS'] verify = False s3_client = boto3.client('s3') bucket_name = os.environ['PA_EDL_AWS_S3_BUCKET'] path = 'iprange/' out_file_json = 'meteo_public_ip_addresses.json' out_file_txt = 'meteo_public_ip_addresses.txt' # configure logging logger = logging.getLogger() logger.setLevel(logging.INFO) if verify is False: requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.InsecureRequestWarning) # validate connectivity & authentication/authorization try: dns_response = res.query(server, 'a') if dns_response: server = dns_response[0].address else: raise ValueError("Unable to resolve server's DNS record") swis = orionsdk.SwisClient(server, user, passwd) swis.query("SELECT NodeID from Orion.Nodes") data = swis.query( "Select Address,CIDR,Location from IPAM.GroupNode gn INNER JOIN IPAM.GroupsCustomProperties gna on gn.GroupID=gna.GroupID where gna.IsPublicIPAddress='yes'" ) data = data['results'] # filter out any 'None' results data = [x for x in data if x['Address'] is not None] # exit if data is empty if not data: raise ValueError('Data returned by Orion is empty, exiting') # create a json output (dict with keys as prefix location) result_json = {} for entry in data: if entry['Location'] in result_json.keys(): result_json[entry['Location']].add(entry['Address'] + '/' + str(entry['CIDR'])) else: result_json[entry['Location']] = set() result_json[entry['Location']].add(entry['Address'] + '/' + str(entry['CIDR'])) # convert values back to array to support json serialization result_json = {k: list(v) for k, v in result_json.items()} s3_client.put_object(Bucket=bucket_name, Key=path + out_file_json, Body=json.dumps(result_json), ContentType='application/json') # create a simple txt output of all prefixes for PAN EDL result_txt = set([ entry['Address'] + '/' + str(entry['CIDR']) + ' #' + str(entry['Location']) for entry in data ]) s3_client.put_object(Bucket=bucket_name, Key=path + out_file_txt, Body='\n'.join(result_txt), ContentType='text/html') except Exception as e: logger.exception('Error occurred: ' + str(e)) exit(1) logger.info('Successful invocation') return ';'.join(result_txt)
import orionsdk import os from difflib import SequenceMatcher import time from tkinter import * orion = orionsdk.SwisClient("dotnpm02", "abushati", "aug2018AB") results = orion.query("SELECT IPAddress\ FROM Orion.Nodes") listOfIPOrion = [] notOnSW = [] listOfIPsCRT = [] inSW = [] IPtoDevice = {} communityString = "netOP$RO" nodeStatusPolling = "120 seconds" collectStatEvery = "10 minutes" pollingEngin = "DOTNPM02" NodeCategory = "Auto-detected" topologyPollingInterval = "30 minutes" SNMPPort = "161" #allow 64 bit counter SNMPversion = "3" nodeidTOip = {} def pushToSW(IPtoDevice, notOnSW): for Ips in notOnSW: # fill these in for the node you want to add!
def callback(): print "Starting to pipe Data ORION --> Influxdb" if SQL.count('DateTime') <= 2: print 'Please Insert DateTime to the Query for TimeSeries Data' sys.exit() #open InfluxDB server to connect try: client = InfluxDBClient(influxdb, dbport, dbID, dbPass, dbName) client.create_database(dbName) except: print("InfluxDb server/port/ID or Pass is wrong") sys.exit() #open SolarWinds server to connect swis = orionsdk.SwisClient(SolarWinds, SWID, SWPass) latestPointSW = {} #var to load 1 day-worth of data at first use, then only a short peiod afterwards firstInput = 1 #minute-worth of data for loading Solarwinds Database (in minutes) delayBy = 2 while (True): if (firstInput == 0): a = SQL.replace(('ADDDAY(-' + str(day)), 'ADDMINUTE(-' + str(int(t / 60) + delayBy), 1) firstInput = -1 if (firstInput == 1): firstInput = 0 start_time = time.time() #turn of the Certificate warning requests.packages.urllib3.disable_warnings() #getting query done try: if (firstInput == -1): data = swis.query(a) else: data = swis.query(SQL) except: print("SolarWinds Server or ID or Pass is wrong") sys.exit() #preparing to get the titles and table name SQL_temp = SQL SQL_temp = SQL_temp.replace(',', '') #this line is to get the Series Name measurement = getMeasurement(SQL_temp) data_str = json.dumps(data) data_arr = json.loads(data_str) try: rowsTitle = data_arr["results"] except: print "Error in Query Request Please check Syntax Again" sys.exit() L = [] for i in range(0, len(rowsTitle)): onePoint = submitPoint(rowsTitle, measurement, i) #Check to see which is the latest point posting to InfluxDB if (cmp(latestPointSW, onePoint) == 0): print "Database is Up-To-Date" break L.append(onePoint) if not L: #if no new point is added to L, dont post anything p = 1 #useless code, just for syntax purpose else: print "Submit " + str(len(L)) + " point(s)" latestPointSW = L[0] client.write_points(L) print "\n Update Database: " + dbName runTime = time.time() - start_time print " Run time " + str(runTime) if (int(runTime) > 120): delayBy = (runTime + 61) / 60 print " Executing again in " + str(t) + " seconds from " + str( datetime.now()) + "\n\n" time.sleep(t)
return parsed_yaml # Read config CONFIG = _read_yaml_file("./config/config.yaml") # Establish SolarWinds connection if not CONFIG['npm_user']: USER = getpass.getuser() CONFIG['npm_user'] = raw_input("Orion username [{}]: ".format(USER)) \ or USER if not CONFIG['npm_pass']: CONFIG['npm_pass'] = getpass.getpass("Orion password: "******""" Returns standardized interface dict based on manual_iface """ iface_dict = { 'node_id': 'manual', 'node_uri': None, 'node_name': None, 'node_addr': None, 'node_fqdn': None, 'node_class': 'Network', 'iface_id': 'manual',
import orionsdk swis = orionsdk.SwisClient("server", "user", "password") devices = swis.query( 'SELECT IPAddress, DNS, SysName, Vendor, MachineType, Description, IOSVersion, Status FROM Orion.Nodes' ) print(devices)