├── .gitignore ├── Episodes ├── Episode6 │ ├── report_template.html │ ├── reportcreator.py │ ├── PrinterList.csv │ ├── 1-deleterecord-REST.py │ ├── 1-deleterecord-SOAP.py │ └── 2-getServers-REST.py ├── Episode1 │ ├── curl rest example │ │ ├── curl_login.sh │ │ ├── curl_logout.sh │ │ └── curl_getSysteminfo.sh │ ├── 1-firstscript-SOAP.py │ ├── 1-firstscript-REST.py │ ├── PrinterList.csv │ ├── 2-addHost-SOAP.py │ ├── 3-bulk-addhostrecords.py │ ├── bulk-delete.py │ └── 2-addHost-REST.py ├── Episode2 │ ├── 1-firstscript-SOAP-unverified.py │ ├── 1-firstscript-SOAP.py │ ├── 4-SimpleSearch-SOAP.py │ ├── 1-firstscript-REST.py │ ├── 1-firstscript-REST-unverified.py │ ├── 2-assignDHCPReservation-SOAP.py │ ├── 4-SimpleSearch-REST.py │ └── 2-assignDHCPReservation-REST.py ├── Episode3 │ ├── 4-getipaddressfrommac-SOAP.py │ ├── csvcreator.py │ ├── 1-SimpleSearch-SOAP.py │ ├── 4-getipaddressfrommac-REST.py │ ├── 3-CustomSearch-REST.py │ ├── 1-SimpleSearch-REST.py │ ├── 3-CustomSearch-SOAP.py │ ├── 2-getreservedip-SOAP.py │ └── 2-getreservedip-REST.py ├── Episode7 │ ├── 3-selectivedeploy-SOAP.py │ ├── 1-deleterecord-SOAP.py │ └── 2-fulldeploy-REST.py ├── Episode5 │ ├── 2-CheckAccess-SOAP.py │ ├── 1-deleterecord-REST.py │ └── 1-deleterecord-SOAP.py ├── Episode4 │ ├── 2-Disaster-Recovery-REST.py │ └── 1-Automated-Services-SOAP.py └── Episode8 │ └── 1-taging-REST.py ├── CODE_OF_CONDUCT.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /Episodes/Episode6/report_template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |34 | Report was Generated at {{ currentdate }} 35 |
36 | 37 | 38 | -------------------------------------------------------------------------------- /Episodes/Episode1/curl rest example/curl_login.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Author: vivek Mistry @[Vivek M.] 3 | # Date: 2017-10-11T20:28:17.096Z 4 | # 5 | # Disclaimer: 6 | # All information, documentation, and code is provided to you AS-IS and should 7 | # only be used in an internal, non-production laboratory environment. 8 | # 9 | # License: 10 | # Copyright 2017 BlueCat Networks, Inc. 11 | # 12 | # Licensed under the Apache License, Version 2.0 (the "License"); 13 | # you may not use this file except in compliance with the License. 14 | # You may obtain a copy of the License at 15 | # 16 | # http://www.apache.org/licenses/LICENSE-2.0 17 | # 18 | # Unless required by applicable law or agreed to in writing, software 19 | # distributed under the License is distributed on an "AS IS" BASIS, 20 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | # See the License for the specific language governing permissions and 22 | # limitations under the License. 23 | # 24 | curl --request GET \ 25 | --url 'http://bam.lab.corp/Services/REST/v1/login?&username=api&password=pass' \ 26 | --header 'content-type: application/json' 27 | -------------------------------------------------------------------------------- /Episodes/Episode1/curl rest example/curl_logout.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Author: vivek Mistry @[Vivek M.] 3 | # Date: 2017-10-11T20:28:17.096Z 4 | # 5 | # Disclaimer: 6 | # All information, documentation, and code is provided to you AS-IS and should 7 | # only be used in an internal, non-production laboratory environment. 8 | # 9 | # 10 | # License: 11 | # Copyright 2017 BlueCat Networks, Inc. 12 | # 13 | # Licensed under the Apache License, Version 2.0 (the "License"); 14 | # you may not use this file except in compliance with the License. 15 | # You may obtain a copy of the License at 16 | # 17 | # http://www.apache.org/licenses/LICENSE-2.0 18 | # 19 | # Unless required by applicable law or agreed to in writing, software 20 | # distributed under the License is distributed on an "AS IS" BASIS, 21 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | # See the License for the specific language governing permissions and 23 | # limitations under the License. 24 | # 25 | curl -request GET \ 26 | --url 'http://bam.lab.corp/Services/REST/v1/logout?' \ 27 | --header 'Authorization : "BAMAuthToken: 9g4fEMTUwODMzMTc5MzE0NTphcGk="' \ 28 | --header 'content-type: application/json' 29 | -------------------------------------------------------------------------------- /Episodes/Episode1/curl rest example/curl_getSysteminfo.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Author: vivek Mistry @[Vivek M.] 3 | # Date: 2017-10-11T20:28:17.096Z 4 | # 5 | # Disclaimer: 6 | # All information, documentation, and code is provided to you AS-IS and should 7 | # only be used in an internal, non-production laboratory environment. 8 | # 9 | # License: 10 | # Copyright 2017 BlueCat Networks, Inc. 11 | # 12 | # Licensed under the Apache License, Version 2.0 (the "License"); 13 | # you may not use this file except in compliance with the License. 14 | # You may obtain a copy of the License at 15 | # 16 | # http://www.apache.org/licenses/LICENSE-2.0 17 | # 18 | # Unless required by applicable law or agreed to in writing, software 19 | # distributed under the License is distributed on an "AS IS" BASIS, 20 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | # See the License for the specific language governing permissions and 22 | # limitations under the License. 23 | # 24 | curl -request GET \ 25 | --url 'http://bam.lab.corp/Services/REST/v1/getSystemInfo?' \ 26 | --header 'Authorization : "BAMAuthToken: 9g4fEMTUwODMzMTc5MzE0NTphcGk="' \ 27 | --header 'content-type: application/json' 28 | -------------------------------------------------------------------------------- /Episodes/Episode2/1-firstscript-SOAP-unverified.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | from zeep import Client 27 | from getpass import getpass 28 | #Parameters 29 | BAMAddress="bam.lab.corp" 30 | # SSL is unverified in this script see 1-firstscript-SOAP.py in this dir for 31 | # example on how to make sure ssl certificate is verified. 32 | url="http://"+BAMAddress+"/Services/API?wsdl" 33 | account="api" 34 | account_password=getpass("Enter Password: ") 35 | 36 | #api session 37 | # get the HTTPS session verified 38 | client = Client(url) 39 | 40 | #login to api session 41 | client.service.login(account,account_password) 42 | 43 | #APi calls 44 | BAM_system_info = client.service.getSystemInfo() 45 | 46 | 47 | # logout of api session 48 | client.service.logout() 49 | 50 | # procesing 51 | print("--------") 52 | for item in BAM_system_info.split("|"): 53 | print(item) 54 | -------------------------------------------------------------------------------- /Episodes/Episode3/4-getipaddressfrommac-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-11-06T22:21:31.880Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | from requests import Session 29 | from zeep.transports import Transport 30 | from getpass import getpass 31 | 32 | #Parameters 33 | #Parameters 34 | BAMAddress="bam.lab.corp" 35 | url="https://"+BAMAddress+"/Services/API?wsdl" 36 | account="api" 37 | account_password=getpass("Enter Password: ") 38 | 39 | macid=105739 40 | 41 | # get the HTTPS session verified 42 | websession = Session() 43 | # refer to certificate file path 44 | websession.verify = "bam.crt" 45 | webtransport=Transport(session=websession) 46 | client = Client(url, transport=webtransport) 47 | 48 | #login to api session 49 | client.service.login(account,account_password) 50 | 51 | ipadd = client.service.getLinkedEntities(macid,"IP4Address",0,10) 52 | print(ipadd) 53 | 54 | client.service.logout() 55 | -------------------------------------------------------------------------------- /Episodes/Episode1/1-firstscript-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from suds.client import Client 28 | 29 | #Parameters 30 | BAMAddress="bam.lab.corp" 31 | # we are using unsecure http example, for secure https connection with BAM see 32 | # episode 2 on how to verify SSL connection. 33 | # see link 34 | url="http://"+BAMAddress+"/Services/API?wsdl" 35 | account="api" 36 | # saving passwords in scripts is unsecure see episode 2 on how to secure your 37 | # passwords. see link 38 | account_password="pass" 39 | 40 | #api session 41 | client = Client(url) 42 | 43 | #login to api session 44 | client.service.login(account,account_password) 45 | 46 | #APi calls 47 | BAM_system_info = client.service.getSystemInfo() 48 | #print(BAM_system_info) 49 | 50 | for item in BAM_system_info.split("|"): 51 | print(item) 52 | 53 | # logout of api session 54 | client.service.logout() 55 | -------------------------------------------------------------------------------- /Episodes/Episode3/csvcreator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 15-01-2018 09:49 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | import csv, os 28 | 29 | def csvwriter(filename, datalist): 30 | """csvwriter function to take a list and write it to CSV 31 | Parameters 32 | filename : Name of the file it you will create for CSV 33 | datalist : Python list that has the data for the CSV file 34 | """ 35 | with open (filename, 'wb') as f: 36 | wr = csv.writer(f, delimiter=",", quoting=csv.QUOTE_ALL) 37 | wr.writerow(datalist) 38 | print("see file "+filename+" in "+os.getcwd()) 39 | 40 | def appendheader (datalist, header): 41 | """appendheader function to add a header to datalist python list for CSV 42 | Parameters 43 | datalist : Python list that has data for the CSV file 44 | header : Python list with the header for the datalist entities 45 | """ 46 | datalist.insert(0,header) 47 | return datalist 48 | -------------------------------------------------------------------------------- /Episodes/Episode2/1-firstscript-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | from zeep import Client 27 | from requests import Session 28 | from zeep.transports import Transport 29 | import getpass 30 | 31 | #Parameters 32 | BAMAddress="bam.lab.corp" 33 | url="https://"+BAMAddress+"/Services/API?wsdl" 34 | account="api" 35 | account_password=getpass.getpass("Enter Password: ") 36 | 37 | #api session 38 | # get the HTTPS session verified 39 | websession = Session() 40 | websession.verify = "bam.crt" 41 | webtransport=Transport(session=websession) 42 | client = Client(url, transport=webtransport) 43 | 44 | #login to api session 45 | client.service.login(account,account_password) 46 | 47 | #APi calls 48 | BAM_system_info = client.service.getSystemInfo() 49 | 50 | 51 | # logout of api session 52 | client.service.logout() 53 | 54 | # procesing 55 | print("--------") 56 | for item in BAM_system_info.split("|"): 57 | print(item) 58 | -------------------------------------------------------------------------------- /Episodes/Episode2/4-SimpleSearch-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-11-06T22:21:31.880Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | from requests import Session 29 | from zeep.transports import Transport 30 | from getpass import getpass 31 | 32 | #Parameters 33 | BAMAddress="bam.lab.corp" 34 | url="https://"+BAMAddress+"/Services/API?wsdl" 35 | account="api" 36 | account_password=getpass("Enter Password: ") 37 | 38 | # get the HTTPS session verified 39 | websession = Session() 40 | # refer to certificate file path 41 | websession.verify = "bam.crt" 42 | webtransport=Transport(session=websession) 43 | client = Client(url, transport=webtransport) 44 | 45 | searchTerm="192.168.2" 46 | 47 | #login to api session 48 | client.service.login(account,account_password) 49 | 50 | #APi calls 51 | searchresults = client.service.searchByObjectTypes(searchTerm,"IP4Address", \ 52 | 0, 100) 53 | for items in searchresults: 54 | if "GATEWAY" in items.properties: 55 | print items 56 | 57 | searchresults = client.service.searchByCategory("bdds1","ALL",0,50) 58 | for items in searchresults: 59 | print(items.name + " " +items.type) 60 | 61 | # logout of api session 62 | client.service.logout() 63 | -------------------------------------------------------------------------------- /Episodes/Episode3/1-SimpleSearch-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-11-06T22:21:31.880Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | from requests import Session 29 | from zeep.transports import Transport 30 | from getpass import getpass 31 | 32 | #Parameters 33 | BAMAddress="bam.lab.corp" 34 | url="https://"+BAMAddress+"/Services/API?wsdl" 35 | account="api" 36 | account_password=getpass("Enter Password: ") 37 | 38 | searchTerm="appsrv" 39 | 40 | # get the HTTPS session verified 41 | websession = Session() 42 | # refer to certificate file path 43 | websession.verify = "bam.crt" 44 | webtransport=Transport(session=websession) 45 | client = Client(url, transport=webtransport) 46 | 47 | #login to api session 48 | client.service.login(account,account_password) 49 | 50 | #APi calls 51 | searchresults = client.service.searchByObjectTypes(searchTerm,"HostRecord", \ 52 | 0, 100) 53 | 54 | print(searchresults) 55 | """for items in searchresults: 56 | if "GATEWAY" in items.properties: 57 | print items""" 58 | 59 | searchresults = client.service.searchByCategory("F*1","RESOURCE_RECORD",0,50) 60 | for items in searchresults: 61 | print(items.name + " " +items.type) 62 | 63 | 64 | # logout of api session 65 | client.service.logout() 66 | -------------------------------------------------------------------------------- /Episodes/Episode7/3-selectivedeploy-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 31-05-2018 10:25 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | import zeep 29 | from getpass import getpass 30 | import sys 31 | from time import sleep 32 | 33 | # remove this if your are using python 3.x 34 | # input = raw_input 35 | 36 | # Parameters 37 | BAMAddress = "bam.lab.corp" 38 | url = "http://"+BAMAddress+"/Services/API?wsdl" 39 | account = "api" 40 | account_password = getpass("Enter Password: ") 41 | hostrecordname = {"fqdn":"test.lab.corp", "newip":"192.168.0.11"} 42 | 43 | client = Client(url) 44 | client.service.login(account, account_password) 45 | 46 | record = client.service.getEntityByName(105021, "test", "HostRecord") 47 | print(record) 48 | 49 | record["properties"] = "absoluteName=test.lab.corp|addresses={}|reverseRecord=true|".format(hostrecordname['newip']) 50 | print(record) 51 | 52 | client.service.update(record) 53 | 54 | longArrayType = client.get_type('ns0:longArray') 55 | records = longArrayType() 56 | # print(records) 57 | 58 | records['item'].append(record["id"]) 59 | # print(records) 60 | 61 | deploymenttoken = client.service.selectiveDeploy(records, "scope=related") 62 | 63 | print(deploymenttoken) 64 | 65 | count = range(5) 66 | for i in count: 67 | status = client.service.getDeploymentTaskStatus(deploymenttoken) 68 | print(status) 69 | sleep(1) 70 | 71 | client.service.logout() 72 | -------------------------------------------------------------------------------- /Episodes/Episode2/1-firstscript-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json, getpass 27 | 28 | #main variables 29 | user = "api" 30 | password = getpass.getpass("Enter password: ") 31 | bamurl = "bam.lab.corp" 32 | mainurl = "https://"+bamurl+"/Services/REST/v1/" 33 | bamcert = "bam.crt" 34 | # methods url 35 | # Login method 36 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 37 | loginurl = mainurl+"login?" 38 | param = {"username":user,"password":password} 39 | 40 | # getsysinfo method 41 | getsysinfourl = mainurl+"getSystemInfo?" 42 | 43 | # logout method 44 | logouturl = mainurl+"logout?" 45 | 46 | # login to BAM 47 | response = requests.get(loginurl, params=param, verify=bamcert) 48 | 49 | # print login 50 | #print(response) 51 | #print(response.text) 52 | #print(response.status_code) 53 | #print(response.json()) 54 | 55 | # get the Token and put it into a variable 56 | token = str(response.json()) 57 | token = token.split()[2]+" "+token.split()[3] 58 | #print token 59 | # set header value for the next methods 60 | header={'Authorization':token,'Content-Type':'application/json'} 61 | 62 | # run the methods needed for example getSystemInfo method 63 | response = requests.get(getsysinfourl,headers=header, verify=bamcert) 64 | newdata = response.json() 65 | 66 | # print the items in response received from the server 67 | #print(newdata) 68 | for items in newdata.split("|"): 69 | print(items) 70 | 71 | # logout from BAM 72 | response=requests.get(logouturl,headers=header, verify=bamcert) 73 | print(response.json()) 74 | -------------------------------------------------------------------------------- /Episodes/Episode6/reportcreator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 26-04-2018 07:01 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import pandas as pd 27 | import numpy as np 28 | from jinja2 import Environment, FileSystemLoader 29 | import datetime as dt 30 | from weasyprint import HTML 31 | 32 | reportName = "Printer List for Head Office" 33 | reportfilename = reportName.replace(" ","_")+"_"+str(dt.datetime.now().strftime("%Y%m%d-%H%M%S")) 34 | 35 | df = pd.read_csv("PrinterList.csv") 36 | #print(df.head()) 37 | #print(df) 38 | printer_report = pd.pivot_table(df, 39 | index=["SubNet","PrinterModel"], 40 | values=["PrinterName"], 41 | aggfunc=[np.count_nonzero], 42 | margins=True) 43 | 44 | #print(printer_report) 45 | 46 | 47 | # Import HTML Template using jinja2 48 | env = Environment(loader=FileSystemLoader('.')) 49 | template = env.get_template("report_template.html") 50 | 51 | # Assign values to variables in report 52 | template_vars = {"title" : reportName, 53 | "data_table": printer_report.to_html(), 54 | "currentdate":dt.datetime.now().strftime('%Y-%m-%d %H:%M')} 55 | 56 | # get the html output from the template with the data 57 | html_out = template.render(template_vars) 58 | #print(html_out) 59 | # create html report 60 | with open(reportfilename+".html","w") as f: 61 | f.write(html_out) 62 | 63 | 64 | # Generate pdf using weasyprint 65 | HTML(string=html_out).write_pdf(reportfilename+".pdf") 66 | 67 | #HTML(string=html_out).write_pdf(args.outfile.name, stylesheets=["style.css"]) 68 | -------------------------------------------------------------------------------- /Episodes/Episode2/1-firstscript-REST-unverified.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json 27 | 28 | #main variables 29 | user = "api" 30 | password = "pass" 31 | bamurl = "bam.lab.corp" 32 | # SSL is unverified in this script see 1-firstscript-REST.py in this dir for 33 | # example on how to make sure ssl certificate is verified. 34 | mainurl = "http://"+bamurl+"/Services/REST/v1/" 35 | # methods url 36 | # Login method 37 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 38 | loginurl = mainurl+"login?" 39 | param = {"username":user,"password":password} 40 | 41 | # getsysinfo method 42 | getsysinfourl = mainurl+"getSystemInfo?" 43 | 44 | # logout method 45 | logouturl = mainurl+"logout?" 46 | 47 | # login to BAM 48 | response = requests.get(loginurl, params=param) 49 | 50 | # print login 51 | #print(response) 52 | #print(response.text) 53 | #print(response.status_code) 54 | #print(response.json()) 55 | 56 | # get the Token and put it into a variable 57 | token = str(response.json()) 58 | token = token.split()[2]+" "+token.split()[3] 59 | #print token 60 | # set header value for the next methods 61 | header={'Authorization':token,'Content-Type':'application/json'} 62 | 63 | # run the methods needed for example getSystemInfo method 64 | response = requests.get(getsysinfourl,headers=header) 65 | newdata = response.json() 66 | 67 | # print the items in response received from the server 68 | #print(newdata) 69 | for items in newdata.split("|"): 70 | print(items) 71 | 72 | # logout from BAM 73 | response=requests.get(logouturl,headers=header) 74 | print(response.json()) 75 | -------------------------------------------------------------------------------- /Episodes/Episode1/1-firstscript-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json 27 | 28 | #main variables 29 | user = "api" 30 | # saving passwords in scripts is unsecure see episode 2 on how to secure your 31 | # passwords. see link 32 | password = "pass" 33 | bamurl = "bam.lab.corp" 34 | 35 | # we are using unsecure http example, for secure https connection with BAM see 36 | # episode 2 on how to verify SSL connection. 37 | # see link 38 | mainurl = "http://"+bamurl+"/Services/REST/v1/" 39 | # methods url 40 | # Login method 41 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 42 | loginurl = mainurl+"login?username="+user+"&password="+password 43 | 44 | # getsysinfo method 45 | getsysinfourl = mainurl+"getSystemInfo?" 46 | 47 | # logout method 48 | logouturl = mainurl+"logout?" 49 | 50 | # login to BAM 51 | response = requests.get(loginurl) 52 | 53 | # print login 54 | #print response 55 | #print response.text 56 | #print response.status_code 57 | #print response.json() 58 | 59 | # get the Token and put it into a variable 60 | token = str(response.json()) 61 | token = token.split()[2]+" "+token.split()[3] 62 | #print token 63 | # set header value for the next methods 64 | header={'Authorization':token,'Content-Type':'application/json'} 65 | 66 | # run the methods needed for example getSystemInfo method 67 | response = requests.get(getsysinfourl,headers=header) 68 | newdata = response.json() 69 | 70 | # print the items in response received from the server 71 | #print(newdata) 72 | for items in newdata.split("|"): 73 | print items 74 | 75 | # logout from BAM 76 | response=requests.get(logouturl,headers=header) 77 | print(response.json()) 78 | -------------------------------------------------------------------------------- /Episodes/Episode1/PrinterList.csv: -------------------------------------------------------------------------------- 1 | 192.168.3.2,PRNDALXER2,9C:93:4E:11:22:33,DAL-LAN,XEROX-3600,MHB8923044 2 | 192.168.3.3,PRNDALXER3,9C:93:4E:12:23:34,DAL-LAN,XEROX-3600,MHB8923045 3 | 192.168.1.2,PRNNYCXER2,9C:93:4E:13:24:35,NYC-LAN,XEROX-3600,MHB8923046 4 | 192.168.2.2,PRNLONXER2,9C:93:4E:14:25:36,LON-LAN,XEROX-3600,MHB8923047 5 | 192.168.2.3,PRNLONXER3,9C:93:4E:15:26:37,LON-LAN,XEROX-3600,MHB8923048 6 | 192.168.4.2,PRNCHIXER2,9C:93:4E:16:27:38,CHI-LAN,XEROX-3600,MHB8923049 7 | 192.168.3.4,PRNDALXER4,9C:93:4E:17:28:39,DAL-LAN,XEROX-3600,MHB8923050 8 | 192.168.2.4,PRNLONXER4,9C:93:4E:18:29:40,LON-LAN,XEROX-3600,MHB8923051 9 | 192.168.0.2,PRNTORXER2,9C:93:4E:19:30:41,TOR-LAN,XEROX-3600,MHB8923052 10 | 192.168.0.3,PRNTORXER3,9C:93:4E:20:31:42,TOR-LAN,XEROX-3600,MHB8923053 11 | 192.168.1.3,PRNNYCXER3,9C:93:4E:21:32:43,NYC-LAN,XEROX-3600,MHB8923054 12 | 192.168.4.3,PRNCHIXER3,9C:93:4E:22:33:44,CHI-LAN,XEROX-3600,MHB8923055 13 | 192.168.1.4,PRNNYCXER4,9C:93:4E:23:34:45,NYC-LAN,XEROX-3600,MHB8923056 14 | 192.168.2.5,PRNLONXER5,9C:93:4E:24:35:46,LON-LAN,XEROX-3600,MHB8923057 15 | 192.168.0.4,PRNTORXER4,9C:93:4E:25:36:47,TOR-LAN,XEROX-3600,MHB8923058 16 | 192.168.1.5,PRNNYCXER5,9C:93:4E:26:37:48,NYC-LAN,XEROX-3600,MHB8923059 17 | 192.168.4.4,PRNCHIXER4,9C:93:4E:27:38:49,CHI-LAN,XEROX-3600,MHB8923060 18 | 192.168.4.5,PRNCHIXER5,9C:93:4E:28:39:50,CHI-LAN,XEROX-3600,MHB8923061 19 | 192.168.2.6,PRNLONXER6,9C:93:4E:29:40:51,LON-LAN,XEROX-3600,MHB8923062 20 | 192.168.2.7,PRNLONXER7,9C:93:4E:30:41:52,LON-LAN,XEROX-3600,MHB8923063 21 | 192.168.0.5,PRNTORXER5,9C:93:4E:31:42:53,TOR-LAN,XEROX-3600,MHB8923064 22 | 192.168.3.5,PRNDALXER5,9C:93:4E:32:43:54,DAL-LAN,XEROX-3600,MHB8923065 23 | 192.168.4.6,PRNCHIXER6,9C:93:4E:33:44:55,CHI-LAN,XEROX-3600,MHB8923066 24 | 192.168.4.7,PRNCHIXER7,9C:93:4E:34:45:56,CHI-LAN,XEROX-3600,MHB8923067 25 | 192.168.1.6,PRNNYCXER6,9C:93:4E:35:46:57,NYC-LAN,XEROX-3600,MHB8923068 26 | 192.168.0.6,PRNTORXER6,9C:93:4E:36:47:58,TOR-LAN,XEROX-3600,MHB8923069 27 | 192.168.4.8,PRNCHIXER8,9C:93:4E:37:48:59,CHI-LAN,XEROX-3600,MHB8923070 28 | 192.168.3.6,PRNDALXER6,9C:93:4E:38:49:60,DAL-LAN,XEROX-3600,MHB8923071 29 | 192.168.0.7,PRNTORXER7,9C:93:4E:39:50:61,TOR-LAN,XEROX-3600,MHB8923072 30 | 192.168.2.8,PRNLONXER8,9C:93:4E:40:51:62,LON-LAN,XEROX-3600,MHB8923073 31 | 192.168.2.9,PRNLONXER9,9C:93:4E:41:52:63,LON-LAN,XEROX-3600,MHB8923074 32 | 192.168.1.7,PRNNYCXER7,9C:93:4E:42:53:64,NYC-LAN,XEROX-3600,MHB8923075 33 | 192.168.4.9,PRNCHIXER9,9C:93:4E:43:54:65,CHI-LAN,XEROX-3600,MHB8923076 34 | 192.168.0.8,PRNTORXER8,9C:93:4E:44:55:66,TOR-LAN,XEROX-3600,MHB8923077 35 | 192.168.0.9,PRNTORXER9,9C:93:4E:45:56:67,TOR-LAN,XEROX-3600,MHB8923078 36 | 192.168.4.10,PRNCHIXER10,9C:93:4E:46:57:68,CHI-LAN,XEROX-3600,MHB8923079 37 | 192.168.2.10,PRNLONXER10,9C:93:4E:47:58:69,LON-LAN,XEROX-3600,MHB8923080 38 | -------------------------------------------------------------------------------- /Episodes/Episode3/4-getipaddressfrommac-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-11-06T22:21:31.880Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json, getpass 27 | 28 | 29 | #main variables 30 | user = "api" 31 | password = getpass.getpass("Enter Password: ") 32 | bamurl = "bam.lab.corp" 33 | mainurl = "https://"+bamurl+"/Services/REST/v1/" 34 | bamcert = "bam.crt" 35 | s = requests.Session() 36 | s.verify = bamcert 37 | # methods url 38 | # Login method 39 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 40 | loginurl = mainurl+"login?" 41 | param = {"username":user,"password":password} 42 | 43 | # getsysinfo method 44 | getsysinfourl = mainurl+"getSystemInfo?" 45 | 46 | # logout method 47 | logouturl = mainurl+"logout?" 48 | 49 | # getLinkedEntities method 50 | getLinkedEntitiesURL = mainurl+"getLinkedEntities?" 51 | getLinkedEntitiesparam = { 52 | "entityId":"", 53 | "type":"", 54 | "start":0, 55 | "count":100 56 | } 57 | 58 | 59 | # login to BAM 60 | response = requests.get(loginurl, params=param) 61 | 62 | # get the Token and put it into a variable 63 | token = str(response.json()) 64 | token = token.split()[2]+" "+token.split()[3] 65 | #print token 66 | # set header value for the next methods 67 | header={'Authorization':token,'Content-Type':'application/json'} 68 | 69 | # get information for macid=105739 70 | macid=105739 71 | getLinkedEntitiesparam["entityId"] = macid 72 | getLinkedEntitiesparam["type"] = "IP4Address" 73 | 74 | response=requests.get( 75 | getLinkedEntitiesURL, 76 | params=getLinkedEntitiesparam, 77 | headers=header 78 | ) 79 | 80 | print(response.json()) 81 | 82 | # Logout of BAM 83 | response=requests.get(logouturl,headers=header) 84 | print(response.json()) 85 | -------------------------------------------------------------------------------- /Episodes/Episode6/PrinterList.csv: -------------------------------------------------------------------------------- 1 | IPAddr,PrinterName,MACAddress,SubNet,PrinterModel,SerialNumber 2 | 192.168.3.2,PRNDALXER2,9C:93:4E:11:22:33,DAL-LAN,XEROX-3600,MHB8923044 3 | 192.168.3.3,PRNDALXER3,9C:93:4E:12:23:34,DAL-LAN,XEROX-3600,MHB8923045 4 | 192.168.1.2,PRNNYCXER2,9C:93:4E:13:24:35,NYC-LAN,XEROX-3600,MHB8923046 5 | 192.168.2.2,PRNLONXER2,9C:93:4E:14:25:36,LON-LAN,XEROX-3600,MHB8923047 6 | 192.168.2.3,PRNLONXER3,9C:93:4E:15:26:37,LON-LAN,XEROX-3600,MHB8923048 7 | 192.168.4.2,PRNCHIXER2,9C:93:4E:16:27:38,CHI-LAN,XEROX-3600,MHB8923049 8 | 192.168.3.4,PRNDALXER4,9C:93:4E:17:28:39,DAL-LAN,XEROX-3600,MHB8923050 9 | 192.168.2.4,PRNLONXER4,9C:93:4E:18:29:40,LON-LAN,XEROX-3600,MHB8923051 10 | 192.168.0.2,PRNTORXER2,9C:93:4E:19:30:41,TOR-LAN,XEROX-3600,MHB8923052 11 | 192.168.0.3,PRNTORXER3,9C:93:4E:20:31:42,TOR-LAN,XEROX-3600,MHB8923053 12 | 192.168.1.3,PRNNYCXER3,9C:93:4E:21:32:43,NYC-LAN,XEROX-3600,MHB8923054 13 | 192.168.4.3,PRNCHIXER3,9C:93:4E:22:33:44,CHI-LAN,XEROX-3600,MHB8923055 14 | 192.168.1.4,PRNNYCXER4,9C:93:4E:23:34:45,NYC-LAN,XEROX-3600,MHB8923056 15 | 192.168.2.5,PRNLONXER5,9C:93:4E:24:35:46,LON-LAN,XEROX-3600,MHB8923057 16 | 192.168.0.4,PRNTORXER4,9C:93:4E:25:36:47,TOR-LAN,XEROX-3600,MHB8923058 17 | 192.168.1.5,PRNNYCXER5,9C:93:4E:26:37:48,NYC-LAN,XEROX-3600,MHB8923059 18 | 192.168.4.4,PRNCHIXER4,9C:93:4E:27:38:49,CHI-LAN,XEROX-3600,MHB8923060 19 | 192.168.4.5,PRNCHIXER5,9C:93:4E:28:39:50,CHI-LAN,XEROX-3600,MHB8923061 20 | 192.168.2.6,PRNLONXER6,9C:93:4E:29:40:51,LON-LAN,XEROX-3600,MHB8923062 21 | 192.168.2.7,PRNLONXER7,9C:93:4E:30:41:52,LON-LAN,XEROX-3600,MHB8923063 22 | 192.168.0.5,PRNTORXER5,9C:93:4E:31:42:53,TOR-LAN,XEROX-3600,MHB8923064 23 | 192.168.3.5,PRNDALXER5,9C:93:4E:32:43:54,DAL-LAN,XEROX-3600,MHB8923065 24 | 192.168.4.6,PRNCHIXER6,9C:93:4E:33:44:55,CHI-LAN,XEROX-3600,MHB8923066 25 | 192.168.4.7,PRNCHIXER7,9C:93:4E:34:45:56,CHI-LAN,XEROX-3600,MHB8923067 26 | 192.168.1.6,PRNNYCXER6,9C:93:4E:35:46:57,NYC-LAN,XEROX-3600,MHB8923068 27 | 192.168.0.6,PRNTORXER6,9C:93:4E:36:47:58,TOR-LAN,XEROX-3600,MHB8923069 28 | 192.168.4.8,PRNCHIXER8,9C:93:4E:37:48:59,CHI-LAN,XEROX-3600,MHB8923070 29 | 192.168.3.6,PRNDALXER6,9C:93:4E:38:49:60,DAL-LAN,XEROX-3600,MHB8923071 30 | 192.168.0.7,PRNTORXER7,9C:93:4E:39:50:61,TOR-LAN,XEROX-3600,MHB8923072 31 | 192.168.2.8,PRNLONXER8,9C:93:4E:40:51:62,LON-LAN,XEROX-3600,MHB8923073 32 | 192.168.2.9,PRNLONXER9,9C:93:4E:41:52:63,LON-LAN,XEROX-3600,MHB8923074 33 | 192.168.1.7,PRNNYCXER7,9C:93:4E:42:53:64,NYC-LAN,XEROX-3600,MHB8923075 34 | 192.168.4.9,PRNCHIXER9,9C:93:4E:43:54:65,CHI-LAN,XEROX-3600,MHB8923076 35 | 192.168.0.8,PRNTORXER8,9C:93:4E:44:55:66,TOR-LAN,XEROX-3600,MHB8923077 36 | 192.168.0.9,PRNTORXER9,9C:93:4E:45:56:67,TOR-LAN,XEROX-3600,MHB8923078 37 | 192.168.4.10,PRNCHIXER10,9C:93:4E:46:57:68,CHI-LAN,XEROX-3600,MHB8923079 38 | 192.168.2.10,PRNLONXER10,9C:93:4E:47:58:69,LON-LAN,XEROX-3600,MHB8923080 39 | -------------------------------------------------------------------------------- /Episodes/Episode1/2-addHost-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-23T17:31:56.063Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from suds.client import Client 28 | 29 | # login parameters 30 | BAMAddress="bam.lab.corp" 31 | # we are using unsecure http example, for secure https connection with BAM see 32 | # episode 2 on how to verify SSL connection. 33 | # see link 34 | url="http://"+BAMAddress+"/Services/API?wsdl" 35 | account="api" 36 | # saving passwords in scripts is unsecure see episode 2 on how to secure your 37 | # passwords. see link 38 | account_password="pass" 39 | 40 | # Server information 41 | ipaddress='192.168.0.15' 42 | hostname='FINRPT01' 43 | alias='reporting' 44 | zone='lab.corp' 45 | 46 | # additional info known 47 | config_name='main' 48 | view_name='default' 49 | 50 | 51 | 52 | # api session 53 | client = Client(url) 54 | 55 | # login to api session 56 | client.service.login(account,account_password) 57 | 58 | # api calls 59 | # configuration information 60 | config_info = client.service.getEntityByName(0,config_name,'Configuration') 61 | #print(config_info) 62 | 63 | # view information 64 | view_info = client.service.getEntityByName(config_info.id,view_name,'View') 65 | #print(view_info) 66 | 67 | # addhost record 68 | hostrecordname = hostname +"."+ zone 69 | record = client.service.addHostRecord(view_info.id,hostrecordname,ipaddress, \ 70 | -1,"reverseRecord=true|") 71 | print("Record ID Created:"+str(record)) 72 | print("--------") 73 | showrecord = client.service.getEntityById(record) 74 | print(showrecord) 75 | 76 | # add alias record link to the record created on line 49 77 | aliasrecordname = alias+"."+zone 78 | aliasrecord = client.service.addAliasRecord(view_info.id,aliasrecordname, \ 79 | hostrecordname,-1,"" ) 80 | print("--------") 81 | print("Record ID Created:"+str(aliasrecord)) 82 | print("--------") 83 | showrecord = client.service.getEntityById(aliasrecord) 84 | print(showrecord) 85 | 86 | #logout of api session 87 | client.service.logout() 88 | -------------------------------------------------------------------------------- /Episodes/Episode3/3-CustomSearch-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 24-01-2018 09:17 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json, getpass 27 | 28 | #main variables 29 | user = "api" 30 | password = getpass.getpass("Enter Password: ") 31 | bamurl = "bam.lab.corp" 32 | mainurl = "https://"+bamurl+"/Services/REST/v1/" 33 | bamcert = "bam.crt" 34 | s = requests.Session() 35 | s.verify = bamcert 36 | # methods url 37 | # Login method 38 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 39 | loginurl = mainurl+"login?" 40 | param = {"username":user,"password":password} 41 | 42 | # getsysinfo method 43 | getsysinfourl = mainurl+"getSystemInfo?" 44 | 45 | # logout method 46 | logouturl = mainurl+"logout?" 47 | 48 | 49 | #customSearch Parameters 50 | customSearchurl = mainurl+"customSearch?" 51 | customSearchparams = { 52 | "filters":"", 53 | "type":"", 54 | "options":"", 55 | "start":0, 56 | "count":100 57 | } 58 | 59 | # login to BAM 60 | response = requests.get(loginurl, params=param) 61 | 62 | # get the Token and put it into a variable 63 | token = str(response.json()) 64 | token = token.split()[2]+" "+token.split()[3] 65 | #print token 66 | # set header value for the next methods 67 | header={'Authorization':token,'Content-Type':'application/json'} 68 | 69 | # your api calls 70 | """ 71 | SearchTerm: XEROX 72 | UDF: printerModel 73 | """ 74 | customSearchparams['filters'] = "printerModel=XEROX" 75 | customSearchparams['type']="MACAddress" 76 | response = requests.get(customSearchurl,params=customSearchparams,headers=header) 77 | for item in response.json(): 78 | print item['properties'] 79 | 80 | 81 | """printer Serial# MHB8923049 82 | UDF: serialNumber""" 83 | customSearchparams['filters'] = "serialNumber=MHB8923049" 84 | customSearchparams['type']="MACAddress" 85 | response = requests.get(customSearchurl,params=customSearchparams,headers=header) 86 | print(response.json()) 87 | 88 | # Logout of BAM 89 | response=requests.get(logouturl,headers=header) 90 | print(response.json()) 91 | -------------------------------------------------------------------------------- /Episodes/Episode5/2-CheckAccess-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | from getpass import getpass 29 | 30 | input = raw_input 31 | 32 | BAMAddress="bam.lab.corp" 33 | url="http://"+BAMAddress+"/Services/API?wsdl" 34 | account=input("Enter Your User ID: ") 35 | account_password=getpass("Enter Password: ") 36 | username = "blue" 37 | hostrecordname = "oldtest.lab.corp" 38 | 39 | def getuser(bam_url,login_user,login_password,user_name): 40 | """Get the User details 41 | """ 42 | # api session 43 | client = Client(bam_url) 44 | # login 45 | client.service.login(login_user,login_password) 46 | # get User 47 | user = client.service.getEntityByName(0,user_name,"User") 48 | # logout 49 | client.service.logout() 50 | 51 | return user 52 | 53 | def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name): 54 | """get the host record FQDN and return the entity details 55 | """ 56 | # api session 57 | client = Client(bam_url) 58 | # login 59 | client.service.login(login_user,login_password) 60 | # get the host record details 61 | records = client.service.getHostRecordsByHint(0,10,"hint="+host_record_name+"|") 62 | # logout of BAM 63 | client.service.logout() 64 | # return the records from function 65 | return records 66 | 67 | def getAccessRightbyuseronentity(bam_url, login_user, login_password, user_id, entity_id): 68 | """get the access rights for a user from getAccessRights api call 69 | """ 70 | # api session 71 | client = Client(bam_url) 72 | 73 | # login 74 | client.service.login(login_user,login_password) 75 | # get the host record details 76 | accessrights = client.service.getAccessRight(entity_id,user_id) 77 | # logout of BAM 78 | client.service.logout() 79 | # return the records from function 80 | return accessrights 81 | 82 | 83 | userinfo = getuser(url,account,account_password,username) 84 | entityinfo = gethostrecordwithhint(url,account,account_password,hostrecordname) 85 | accessrights = getAccessRightbyuseronentity(url,account,account_password,userinfo['id'],entityinfo[0]['id']) 86 | print(accessrights) 87 | -------------------------------------------------------------------------------- /Episodes/Episode1/3-bulk-addhostrecords.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-24T15:58:20.851Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import csv 27 | from suds.client import Client 28 | 29 | #Parameters 30 | BAMAddress="bam.lab.corp" 31 | # we are using unsecure http example, for secure https connection with BAM see 32 | # episode 2 on how to verify SSL connection. 33 | # see link 34 | url="http://"+BAMAddress+"/Services/API?wsdl" 35 | account="api" 36 | # saving passwords in scripts is unsecure see episode 2 on how to secure your 37 | # passwords. see link 38 | account_password="pass" 39 | 40 | # known info 41 | printerList="PrinterList.csv" 42 | config_name='main' 43 | view_name='default' 44 | zone_name='lab.corp' 45 | 46 | def getRecords(csvfile): 47 | ''' 48 | Get a csv file and convert it to a list in python 49 | Format of the file would follows 50 | ip,hostname 51 | ''' 52 | with open(csvfile, 'rb') as f: 53 | reader = csv.reader(f) 54 | your_list = map(tuple, reader) 55 | 56 | return tuple(your_list) 57 | 58 | printertuple = getRecords(csvfile=printerList) 59 | 60 | #api session 61 | client = Client(url) 62 | 63 | #login to api session 64 | client.service.login(account,account_password) 65 | 66 | #APi calls 67 | #set a list to track added hostrecords in a list 68 | addedlist = [] 69 | # get the config information to get the view information 70 | configinfo = client.service.getEntityByName(0,'main','Configuration') 71 | 72 | # get the view information to 73 | viewinfo = client.service.getEntityByName(configinfo.id,'default','View') 74 | 75 | # add the records in BAM now 76 | for item in printertuple: 77 | # get item on the 2nd column in csv file 78 | # with the hostname and append with zone 79 | absoluteName=item[1]+"."+zone_name 80 | # get ip from the 1st column from the csv file 81 | addresses=str(item[0]) 82 | # set ttl to default ttl 83 | ttl=-1 84 | # allow PTR record to be created for the records in the properties 85 | properties="reverseRecord=true|" 86 | # send the api call the BAM 87 | addedrecord = client.service.addHostRecord(viewinfo.id, absoluteName, \ 88 | addresses, ttl, properties) 89 | 90 | # append the list with added record information 91 | addedlist.append(addedrecord) 92 | 93 | for a in addedlist: 94 | print a 95 | 96 | # logout of api session 97 | client.service.logout() 98 | -------------------------------------------------------------------------------- /Episodes/Episode2/2-assignDHCPReservation-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | '''2-assignDHCPReservation-SOAP 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-11-22T16:25:09.525Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | from requests import Session 29 | from zeep.transports import Transport 30 | from getpass import getpass 31 | 32 | #Parameters 33 | BAMAddress="bam.lab.corp" 34 | url="https://"+BAMAddress+"/Services/API?wsdl" 35 | account="api" 36 | account_password=getpass("Enter Password: ") 37 | 38 | # get the HTTPS session verified 39 | websession = Session() 40 | # refer to certificate file path 41 | websession.verify = "bam.crt" 42 | webtransport=Transport(session=websession) 43 | client = Client(url, transport=webtransport) 44 | 45 | #login to api session 46 | client.service.login(account,account_password) 47 | 48 | # Add DHCP reservation for client 49 | mac_address="BB:CC:AA:AA:AA:AA" 50 | networkcidr="192.168.3.0/24" 51 | hostname="appsrv22" 52 | zonename="lab.corp" 53 | viewname="default" 54 | config_name="main" 55 | 56 | # assignNextAvailableIP4Address 57 | # get configuration information 58 | configinfo = client.service.getEntityByName(0,config_name,"Configuration") 59 | configurationId = configinfo.id 60 | 61 | # get network information 62 | networkinfo = client.service.getIPRangedByIP(configinfo.id,"IP4Network","192.168.3.1") 63 | parentId = networkinfo.id 64 | 65 | #macAddress information 66 | macAddress=mac_address 67 | 68 | #viewid information 69 | viewinfo = client.service.getEntityByName(configinfo.id,viewname,"View") 70 | #hostinfo 71 | hostInfo = hostname+"."+zonename+","+str(viewinfo.id)+",true,false" 72 | 73 | action = "MAKE_DHCP_RESERVED" 74 | properties = "name="+hostname+"|locationCode=US DAL|" 75 | 76 | assignaddress = client.service.assignNextAvailableIP4Address(configurationId, 77 | parentId, 78 | macAddress, 79 | hostInfo, 80 | action, 81 | properties) 82 | # logout of api session 83 | client.service.logout() 84 | 85 | print("ID: "+str(assignaddress.id)) 86 | print("Name: "+assignaddress.name) 87 | print("Type: "+assignaddress.type) 88 | print("Properties:") 89 | for item in (assignaddress.properties).split("|"): 90 | print(item) 91 | -------------------------------------------------------------------------------- /Episodes/Episode5/1-deleterecord-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, logging 27 | from getpass import getpass 28 | 29 | logging.basicConfig(filename="debug-rest.log", 30 | level=logging.DEBUG, 31 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 32 | datefmt='%m/%d/%Y %I:%M:%S %p') 33 | 34 | 35 | def get(bam_url, api_call, call_parameters, header): 36 | """requests get call that returns the json data""" 37 | 38 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 39 | if call_parameters == "": 40 | response = requests.get(call_url, headers=header) 41 | else: 42 | response = requests.get(call_url, params=call_parameters, headers=header) 43 | 44 | return response.json() 45 | 46 | def deletecall(bam_url,api_call,call_parameters,delete_entity,header): 47 | """API request to delete and return values""" 48 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 49 | print("You are requesting to delete:") 50 | print(delete_entity) 51 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 52 | if answer.lower() == "y": 53 | response = requests.delete(call_url,params=call_parameters, headers=header) 54 | return response.json() 55 | elif answer.lower() == "n": 56 | return "You aborted deletion" 57 | else: 58 | return "You entered an invalid character" 59 | 60 | def update_header(login_response, call_header): 61 | """Function to process and update the header after login""" 62 | 63 | token = str(login_response).split()[2] + " " + str(login_response).split()[3] 64 | call_header['Authorization'] = token 65 | return call_header 66 | 67 | input = raw_input 68 | 69 | user = input("Enter Your User ID: ") 70 | password = getpass("Enter Password: ") 71 | bamurl = "bam.lab.corp" 72 | header = {'Content-Type': 'application/json'} 73 | 74 | # Login parameters 75 | login_param = {"username": user, "password": password} 76 | 77 | # login to BAM 78 | login = get(bamurl, "login", login_param, header) 79 | 80 | # update header with login token 81 | header = update_header(login, header) 82 | 83 | # get BAM System info 84 | sys_info = get(bamurl, "getSystemInfo", "", header) 85 | for item in sys_info.split("|"): 86 | print(item) 87 | # logout 88 | logout = get(bamurl, "logout", "", header) 89 | print(logout) 90 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # BlueCat's Contributor Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at bluecatlabs-conduct@bluecatnetworks.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /Episodes/Episode5/1-deleterecord-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | from getpass import getpass 29 | import logging 30 | 31 | 32 | # turn on logging 33 | logging.basicConfig(filename="debug-soap.log", 34 | level=logging.DEBUG, 35 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 36 | datefmt='%m/%d/%Y %I:%M:%S %p') 37 | 38 | # remove this if your are using python 3.x 39 | input = raw_input 40 | 41 | # Parameters 42 | BAMAddress="bam.lab.corp" 43 | url="http://"+BAMAddress+"/Services/API?wsdl" 44 | account=input("Enter User Name: ") 45 | account_password=getpass("Enter Password: ") 46 | hostrecordname = "oldtest.lab.corp" 47 | 48 | def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name): 49 | """get the host record FQDN and return the entity details 50 | """ 51 | # api session 52 | client = Client(bam_url) 53 | # login 54 | client.service.login(login_user,login_password) 55 | # get the host record details 56 | records = client.service.getHostRecordsByHint(0,10,"hint="+host_record_name+"|") 57 | # logout of BAM 58 | client.service.logout() 59 | # return the records from function 60 | return records 61 | 62 | 63 | def deletehostrecord(bam_url, login_user, login_password, host_record): 64 | """Delete host record 65 | """ 66 | # api session 67 | client = Client(bam_url) 68 | 69 | # login 70 | client.service.login(login_user,login_password) 71 | # get the host record details 72 | print("You are requesting to delete:") 73 | print(host_record) 74 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 75 | if answer.lower() == "y": 76 | deletion = client.service.deleteWithOptions(host_record['id'], 77 | "deleteOrphanedIPAddresses=true|") 78 | elif answer.lower() == "n": 79 | print("You requested deletion to be stopped") 80 | else: 81 | print("Invalid Entry") 82 | # logout of BAM 83 | client.service.logout() 84 | # return the records from function 85 | 86 | hostrecords = gethostrecordwithhint(bam_url=url, 87 | login_user=account, 88 | login_password=account_password, 89 | host_record_name=hostrecordname) 90 | 91 | deletehostrecord(url,account,account_password,hostrecords[0]) 92 | -------------------------------------------------------------------------------- /Episodes/Episode2/4-SimpleSearch-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json, getpass 27 | 28 | #main variables 29 | user = "api" 30 | password = getpass.getpass("Enter Password: ") 31 | bamurl = "bam.lab.corp" 32 | mainurl = "https://"+bamurl+"/Services/REST/v1/" 33 | bamcert = "bam.crt" 34 | s = requests.Session() 35 | s.verify = bamcert 36 | # methods url 37 | # Login method 38 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 39 | loginurl = mainurl+"login?" 40 | param = {"username":user,"password":password} 41 | 42 | # getsysinfo method 43 | getsysinfourl = mainurl+"getSystemInfo?" 44 | 45 | # logout method 46 | logouturl = mainurl+"logout?" 47 | 48 | # searchByObjectTypes 49 | searchByObjectTypesurl = mainurl+"searchByObjectTypes?" 50 | searchByObjectTypesparams = { 51 | "keyword":"192.168.2", 52 | "types":"IP4Address", 53 | "start":"0", 54 | "count":"500" 55 | } 56 | 57 | # searchByCategory 58 | searchByCategoryurl = mainurl+"searchByCategory?" 59 | searchByCategoryparams = { 60 | "keyword":"bdds1", 61 | "category":"ALL", 62 | "start":"0", 63 | "count":"100" 64 | } 65 | # login to BAM 66 | response = requests.get(loginurl, params=param) 67 | 68 | # get the Token and put it into a variable 69 | token = str(response.json()) 70 | token = token.split()[2]+" "+token.split()[3] 71 | #print token 72 | # set header value for the next methods 73 | header={'Authorization':token,'Content-Type':'application/json'} 74 | 75 | # run the methods needed for example getSystemInfo method 76 | response = requests.get(searchByObjectTypesurl, 77 | params=searchByObjectTypesparams, 78 | headers=header) 79 | 80 | ipaddresslist = response.json() 81 | print("------IP address list------") 82 | for ip in ipaddresslist: 83 | print(ip) 84 | print("----------------------------\n") 85 | response = requests.get(searchByCategoryurl, 86 | params=searchByCategoryparams, 87 | headers=header) 88 | results = response.json() 89 | 90 | print("--------results for bdds1-----------") 91 | for item in results: 92 | print(item) 93 | print("------------------------------------") 94 | 95 | # logout from BAM 96 | response=requests.get(logouturl,headers=header) 97 | print(response.json()) 98 | -------------------------------------------------------------------------------- /Episodes/Episode1/bulk-delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-24T16:18:27.003Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import csv, sys 27 | from suds.client import Client 28 | from suds import WebFault 29 | 30 | #Parameters 31 | BAMAddress="bam.lab.corp" 32 | # we are using unsecure http example, for secure https connection with BAM see 33 | # episode 2 on how to verify SSL connection. 34 | # see link 35 | url="http://"+BAMAddress+"/Services/API?wsdl" 36 | account="api" 37 | # saving passwords in scripts is unsecure see episode 2 on how to secure your 38 | # passwords. see link 39 | account_password="pass" 40 | #api session 41 | client = Client(url) 42 | 43 | def getRecords(csvfile): 44 | ''' 45 | read a file with a list of ids 46 | ''' 47 | with open(csvfile, 'rb') as f: 48 | reader = f.readlines() 49 | 50 | your_list = [x.strip() for x in reader] 51 | return tuple(your_list) 52 | 53 | def check_arguments(): 54 | ''' 55 | returns the numnber of arguments 56 | ''' 57 | return len(sys.argv) 58 | 59 | def deletion(entityid, delete_options): 60 | ''' 61 | run the api call to delete the entity with options below 62 | noServerUpdate=[true/false] 63 | deleteOrphanedIPAddresses=[true/false] 64 | ''' 65 | delete = client.service.deleteWithOptions(entityid,delete_options) 66 | return delete 67 | 68 | def main(): 69 | ''' 70 | main method that executes 71 | ''' 72 | idlist=getRecords(sys.argv[1]) 73 | print idlist 74 | 75 | #login to api session 76 | client.service.login(account,account_password) 77 | 78 | #deletion tracking list 79 | deletedList=[] 80 | #deletion 81 | for id_num in idlist: 82 | deleteOptions='deleteOrphanedIPAddresses=true|' 83 | if id_num != "" or id_num != None: 84 | try: 85 | deleted="" 86 | deleted = deletion(id_num,deleteOptions) 87 | except WebFault as errormessage: 88 | print errormessage.fault.faultstring 89 | except UnboundLocalError as arguments: 90 | print("--") 91 | else: 92 | print("skipped blank") 93 | deletedList.append(deleted) 94 | 95 | # logout of api session 96 | client.service.logout() 97 | for items in deletedList: 98 | print items 99 | 100 | 101 | if __name__ == "__main__": 102 | if check_arguments() == 2: 103 | main() 104 | else: 105 | print('''Please Enter parameter with the csvfile 106 | bulk-delete.py "filename.csv"''') 107 | -------------------------------------------------------------------------------- /Episodes/Episode3/1-SimpleSearch-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-11T20:28:17.096Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json, getpass 27 | 28 | #main variables 29 | user = "api" 30 | password = getpass.getpass("Enter Password: ") 31 | bamurl = "bam.lab.corp" 32 | mainurl = "https://"+bamurl+"/Services/REST/v1/" 33 | bamcert = "bam.crt" 34 | s = requests.Session() 35 | s.verify = bamcert 36 | # methods url 37 | # Login method 38 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 39 | loginurl = mainurl+"login?" 40 | param = {"username":user,"password":password} 41 | 42 | # getsysinfo method 43 | getsysinfourl = mainurl+"getSystemInfo?" 44 | 45 | # logout method 46 | logouturl = mainurl+"logout?" 47 | 48 | # searchByObjectTypes 49 | searchByObjectTypesurl = mainurl+"searchByObjectTypes?" 50 | searchByObjectTypesparams = { 51 | "keyword":"192.168.2", 52 | "types":"IP4Address", 53 | "start":"0", 54 | "count":"500" 55 | } 56 | 57 | # searchByCategory 58 | searchByCategoryurl = mainurl+"searchByCategory?" 59 | searchByCategoryparams = { 60 | "keyword":"f*1", 61 | "category":"ALL", 62 | "start":"0", 63 | "count":"100" 64 | } 65 | # login to BAM 66 | response = requests.get(loginurl, params=param) 67 | 68 | # get the Token and put it into a variable 69 | token = str(response.json()) 70 | token = token.split()[2]+" "+token.split()[3] 71 | #print token 72 | # set header value for the next methods 73 | header={'Authorization':token,'Content-Type':'application/json'} 74 | 75 | # run the methods needed for example getSystemInfo method 76 | response = requests.get(searchByObjectTypesurl, 77 | params=searchByObjectTypesparams, 78 | headers=header) 79 | 80 | ipaddresslist = response.json() 81 | print("------IP address list------") 82 | for ip in ipaddresslist: 83 | print(ip) 84 | print("----------------------------\n") 85 | response = requests.get(searchByCategoryurl, 86 | params=searchByCategoryparams, 87 | headers=header) 88 | results = response.json() 89 | 90 | print("--------results for bdds1-----------") 91 | for item in results: 92 | print(str(item['name'])+" "+item['type']) 93 | print("------------------------------------") 94 | 95 | # logout from BAM 96 | response=requests.get(logouturl,headers=header) 97 | print(response.json()) 98 | -------------------------------------------------------------------------------- /Episodes/Episode3/3-CustomSearch-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 24-01-2018 09:17 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | from getpass import getpass 27 | from requests import Session 28 | from zeep.transports import Transport 29 | from zeep import Client 30 | import os 31 | 32 | #Parameters 33 | BAMAddress="bam.lab.corp" 34 | url="https://"+BAMAddress+"/Services/API?wsdl" 35 | account="api" 36 | account_password=getpass("Enter Password: ") 37 | 38 | # get the HTTPS session verified 39 | websession = Session() 40 | # refer to certificate file path 41 | websession.verify = "bam.crt" 42 | webtransport=Transport(session=websession) 43 | client = Client(url, transport=webtransport) 44 | 45 | #login to api session 46 | client.service.login(account,account_password) 47 | 48 | """SearchTerm: XEROX 49 | UDF: printerModel""" 50 | """ 51 | Before starting to make the api call we first to define String array 52 | in for the filters and options. 53 | Since Options will be left blank we will just put 2 doublequotes. 54 | For filters we need to first with zeep identify the type of entity, 55 | which in this case is a stringArray. After inspecting the WSDL using 56 | the command 57 | python -m zeep http://bam.lab.corp/Services/API?wsdl 58 | 59 | I found the value for customSearch to be 60 | customSearch(filters: ns0:stringArray, type: xsd:string, 61 | options: ns0:stringArray, start: xsd:int, count: xsd:int 62 | ) -> return: ns1:APIEntityArray 63 | 64 | using get_type function on zeep client library we define it as below 65 | """ 66 | stringArrayType = client.get_type('ns0:stringArray') 67 | 68 | #assign the variable filters the stringArrayType 69 | filters = stringArrayType() 70 | # append value list of the dictory for the key item 71 | filters['item'].append("printerModel=XEROX") 72 | 73 | # enter the parameters for customSearch and search 74 | searchresults = client.service.customSearch( 75 | filters, 76 | "MACAddress", 77 | "", 78 | 0, 79 | 100) 80 | for items in searchresults: 81 | print(items['properties']) 82 | 83 | """printer Serial# MHB8923049 84 | UDF: serialNumber""" 85 | # create filter for printer serial number result stringArrayType 86 | printer_Serial = stringArrayType() 87 | 88 | # assign value same as prior example 89 | printer_Serial['item'].append("serialNumber=MHB8923049") 90 | 91 | searchresults = client.service.customSearch( 92 | printer_Serial, 93 | "MACAddress", 94 | "", 95 | 0, 96 | 100) 97 | print(searchresults) 98 | 99 | #logout of API session 100 | client.service.logout() 101 | -------------------------------------------------------------------------------- /Episodes/Episode6/1-deleterecord-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 26-04-2018 07:02 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, logging 27 | from getpass import getpass 28 | import sys 29 | 30 | logging.basicConfig(filename="debug-rest.log", 31 | level=logging.DEBUG, 32 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 33 | datefmt='%m/%d/%Y %I:%M:%S %p') 34 | 35 | 36 | def get(bam_url, api_call, call_parameters, header): 37 | """requests get call that returns the json data""" 38 | 39 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 40 | try: 41 | if call_parameters == "": 42 | response = requests.get(call_url, headers=header) 43 | else: 44 | response = requests.get(call_url, params=call_parameters, headers=header) 45 | 46 | #print(response.text) 47 | if response.status_code != 200: 48 | raise requests.ConnectionError("Code "+str(response.status_code)+" "+response.json()) 49 | 50 | except requests.exceptions.RequestException as e: 51 | print(e) 52 | sys.exit(1) 53 | 54 | return response.json() 55 | 56 | def deletecall(bam_url,api_call,call_parameters,delete_entity,header): 57 | """API request to delete and return values""" 58 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 59 | print("You are requesting to delete:") 60 | print(delete_entity) 61 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 62 | try: 63 | if answer.lower() == "y": 64 | response = requests.delete(call_url,params=call_parameters, headers=header) 65 | return response.json() 66 | elif answer.lower() == "n": 67 | return "You aborted deletion" 68 | else: 69 | return "You entered an invalid character" 70 | except requests.exceptions.RequestException as e: 71 | print(e) 72 | 73 | 74 | def update_header(login_response, call_header): 75 | """Function to process and update the header after login""" 76 | 77 | token = str(login_response).split()[2] + " " + str(login_response).split()[3] 78 | call_header['Authorization'] = token 79 | return call_header 80 | 81 | #input = raw_input 82 | 83 | user = input("Enter Your User ID: ") 84 | password = getpass("Enter Password: ") 85 | bamurl = "bam.lab.corp" 86 | header = {'Content-Type': 'application/json'} 87 | 88 | # Login parameters 89 | login_param = {"username": user, "password": password} 90 | 91 | # login to BAM 92 | login = get(bamurl, "login", login_param, header) 93 | 94 | # update header with login token 95 | header = update_header(login, header) 96 | 97 | # get BAM System info 98 | sys_info = get(bamurl, "getSystemInfo", "", header) 99 | for item in sys_info.split("|"): 100 | print(item) 101 | # logout 102 | logout = get(bamurl, "logout", "", header) 103 | print(logout) 104 | -------------------------------------------------------------------------------- /Episodes/Episode6/1-deleterecord-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 26-04-2018 07:02 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | import zeep 29 | from getpass import getpass 30 | import logging, sys 31 | 32 | 33 | # turn on logging 34 | logging.basicConfig(filename="debug-soap.log", 35 | level=logging.DEBUG, 36 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 37 | datefmt='%m/%d/%Y %I:%M:%S %p') 38 | 39 | # remove this if your are using python 3.x 40 | #input = raw_input 41 | 42 | # Parameters 43 | BAMAddress="bam.lab.corp" 44 | url="http://"+BAMAddress+"/Services/API?wsdl" 45 | account = "" 46 | try: 47 | account=input("Enter User Name: ") 48 | if account == "": 49 | raise ValueError("Error: No User Name was provided") 50 | except Exception as e: 51 | print(e) 52 | logging.exception(e) 53 | sys.exit(1) 54 | account_password=getpass("Enter Password: ") 55 | hostrecordname = "test.lab.corp" 56 | 57 | def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name): 58 | """get the host record FQDN and return the entity details 59 | """ 60 | records="" 61 | try: 62 | # api session 63 | client = Client(bam_url) 64 | # login 65 | client.service.login(login_user,login_password) 66 | # get the host record details 67 | records = client.service.getHostRecordsByHint(0,10,"hint="+host_record_name+"|") 68 | # logout of BAM 69 | client.service.logout() 70 | except zeep.exceptions.Fault as e: 71 | print(e.message) 72 | logging.exception(e) 73 | sys.exit(1) 74 | # return the records from function 75 | return records 76 | 77 | 78 | def deletehostrecord(bam_url, login_user, login_password, host_record): 79 | """Delete host record 80 | """ 81 | # api session 82 | client = Client(bam_url) 83 | 84 | # login 85 | client.service.login(login_user,login_password) 86 | # get the host record details 87 | print("You are requesting to delete:") 88 | print(host_record) 89 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 90 | if answer.lower() == "y": 91 | deletion = client.service.deleteWithOptions(host_record['id'], 92 | "deleteOrphanedIPAddresses=true|") 93 | elif answer.lower() == "n": 94 | print("You requested deletion to be stopped") 95 | else: 96 | print("Invalid Entry") 97 | # logout of BAM 98 | client.service.logout() 99 | # return the records from function 100 | 101 | hostrecords = gethostrecordwithhint(bam_url=url, 102 | login_user=account, 103 | login_password=account_password, 104 | host_record_name=hostrecordname) 105 | 106 | print(hostrecords) 107 | #deletehostrecord(url,account,account_password,hostrecords[0]) 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Making APIs Work for You 2 | 3 | This is sample code from the webinar series **Making APIs Work For You** to show how you can leverage BlueCat DNS Integrity™ API and develop solutions for software defined networking for Enterprise DNS, DHCP and IPAM services. 4 | 5 | ## Setup 6 | 7 | Before using the code, you must download Python and your preferred Python IDE. 8 | 9 | 1. Install Python version 2.x or 3.x. 10 | 2. Install Python libraries: `pip install requests zeep` 11 | 3. Clone this repository with git: `git clone https://github.com/bluecatlabs/making-apis-work-for-you.git` 12 | 13 | **NOTE: Episode 1 code uses Python suds library instead of zeep library for SOAP API examples. Episode 2 will show you how to convert code from suds to zeep on Episode 1.** 14 | 15 | ## Usage 16 | 17 | Make sure to only use the code provided in a lab environment reserved for testing and learning purposes. You should change the scripts as per enterprise standards before adapting it for production use. Before executing the scripts, make sure to change the variables and URL for the BAM service to match your environment. 18 | 19 | To execute the script, run `python 1-scriptname.py` 20 | 21 | ## Webinars Links 22 | You can view all the previous webinars on the [BlueCat Customer Care Portal](https://care.bluecatnetworks.com/s/topic/0TO1W000000I2QKWA0/bluecat-webinars?tabset-5657e=2) 23 | 24 | Here is the current list of webinars in this webinar series: 25 | - Episode 1: Jump start to BAM API - [[Customer Link ](https://care.bluecatnetworks.com/s/article/User-Group-webinar-Making-APIs-Work-for-you-Episode-1)] [[Non-Customer Link](https://www.bluecatnetworks.com/resource/making-apis-work-part-1/)][[Code](/Episodes/Episode1)] 26 | - Episode 2: Working Through Your IP Space - [[Customer Link](https://care.bluecatnetworks.com/s/article/User-Group-Webinar-Making-APIs-Work-for-You-Episode-2)] [[Non-Customer Link](https://www.bluecatnetworks.com/resource/making-apis-work-part-2/)][[Code](/Episodes/Episode2)] 27 | - Episode 3: Searching Enterprise DNS - [[Customer Link](https://care.bluecatnetworks.com/s/article/User-Group-Webinar-Making-APIs-Work-for-You-Episode-3)] [[Non-Customer Link](https://www.bluecatnetworks.com/resource/making-apis-work-part-3/)][[Code](/Episodes/Episode3)] 28 | - Episode 4: BDDS Server Management - [[Customer Link](https://care.bluecatnetworks.com/s/article/User-Group-webinar-Making-APIs-Work-for-You-Episode-4)][[Non-Customer Link](https://www.bluecatnetworks.com/resource/making-apis-work-part-4/)][[Code](/Episodes/Episode4)] 29 | - Episode 5: User Security Management - [[Customer Link](https://care.bluecatnetworks.com/s/article/User-Group-webinar-Making-APIs-Work-for-You-Episode-5)][[Non-Customer Link](https://www.bluecatnetworks.com/resource/making-apis-work-part-5/)][[Code](/Episodes/Episode5)] 30 | - Episode 6: Advanced BAM Reporting - [[Customer Link](https://care.bluecatnetworks.com/s/article/User-Group-webinar-Making-APIs-Work-for-You-Episode-6)][[Non-Customer Link](https://www.bluecatnetworks.com/resource/making-apis-work-for-you-part-6/)][[Code](/Episodes/Episode6)] 31 | - Episode 7: Deploying your Configuration - [[Customer Link](https://care.bluecatnetworks.com/s/article/User-Group-Webinar-Making-APIs-Work-for-You-Episode-7)][[Non-Customer Link](https://www.bluecatnetworks.com/resource/making-apis-work-for-you-part-7/)][[Code](/Episodes/Episode7)] 32 | 33 | 34 | ## Credits 35 | 36 | #### Team: 37 | - Vivek Mistry 38 | - James Fuentes 39 | - Rosalie Thompson 40 | 41 | #### Special Thanks: 42 | - Darren McPhee 43 | - Gunvit Bhatia 44 | - Joel Brooks 45 | 46 | ## License 47 | 48 | Copyright 2017 BlueCat Networks, Inc. 49 | 50 | Licensed under the Apache License, Version 2.0 (the "License"); 51 | you may not use this file except in compliance with the License. 52 | You may obtain a copy of the License at 53 | 54 | http://www.apache.org/licenses/LICENSE-2.0 55 | 56 | Unless required by applicable law or agreed to in writing, software 57 | distributed under the License is distributed on an "AS IS" BASIS, 58 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 59 | See the License for the specific language governing permissions and 60 | limitations under the License. 61 | -------------------------------------------------------------------------------- /Episodes/Episode3/2-getreservedip-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-11-06T10:06:52.002-05:00 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | 12 | License: 13 | Copyright 2017 BlueCat Networks, Inc. 14 | 15 | Licensed under the Apache License, Version 2.0 (the "License"); 16 | you may not use this file except in compliance with the License. 17 | You may obtain a copy of the License at 18 | 19 | http://www.apache.org/licenses/LICENSE-2.0 20 | 21 | Unless required by applicable law or agreed to in writing, software 22 | distributed under the License is distributed on an "AS IS" BASIS, 23 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 24 | See the License for the specific language governing permissions and 25 | limitations under the License. 26 | ''' 27 | from getpass import getpass 28 | from requests import Session 29 | from zeep.transports import Transport 30 | from zeep import Client 31 | import csv, os 32 | 33 | #Parameters 34 | BAMAddress="bam.lab.corp" 35 | url="https://"+BAMAddress+"/Services/API?wsdl" 36 | account="api" 37 | account_password=getpass("Enter Password: ") 38 | 39 | def printEntity(apientity): 40 | ''' 41 | takes a entity got by prints it easy to read with properties 42 | ''' 43 | for key in apientity: 44 | if key == 'properties': 45 | if apientity['properties'] != None: 46 | print(key) 47 | for props in apientity[key].split("|"): 48 | print(props) 49 | else: 50 | print(key+": None") 51 | 52 | else: 53 | print(key+"="+str(apientity[key])) 54 | 55 | 56 | # get the HTTPS session verified 57 | websession = Session() 58 | # refer to certificate file path 59 | websession.verify = "bam.crt" 60 | webtransport=Transport(session=websession) 61 | client = Client(url, transport=webtransport) 62 | 63 | #login to api session 64 | client.service.login(account,account_password) 65 | 66 | #APi calls 67 | # The networks we are looking at is 192.168.0.0/24 68 | # let get the details of that network first. 69 | config = client.service.getEntityByName(0,"main","Configuration") 70 | torontoNetwork = client.service.getIPRangedByIP(config.id, "IP4Network", \ 71 | "192.168.0.1") 72 | 73 | listofIP = client.service.getEntities(torontoNetwork.id, "IP4Address",0,250) 74 | 75 | # logout of api session 76 | client.service.logout() 77 | 78 | '''for address in listofIP: 79 | print("--------------------") 80 | printEntity(address) 81 | print("--------------------")''' 82 | 83 | def searchReserved(listofips): 84 | searchlist=[] 85 | for address in listofips: 86 | if address.name == None: 87 | address.name = "" 88 | 89 | ipitem = [address.id,address.type,address.name] 90 | 91 | addressprops="" 92 | for aprop in address.properties.split("|"): 93 | proplist = aprop.split("=") 94 | if len(proplist) > 1: 95 | ipitem.append(proplist[1]) 96 | 97 | del ipitem[5] 98 | 99 | if "DHCP_RESERVED" in ipitem: 100 | searchlist.append(ipitem) 101 | return searchlist 102 | 103 | def exportToCSV(IP4Addresslist): 104 | ''' 105 | Export list of ip addresses to CSV file named iplist.CSV 106 | ''' 107 | csvfile = "iplist.csv" 108 | header = ["ID","Type","Name","IP4Address","IPState","MACAddress"] 109 | IP4Addresslist.insert(0,header) 110 | with open(csvfile,'wb') as outfile: 111 | wr = csv.writer(outfile, delimiter=',',quoting=csv.QUOTE_ALL) 112 | wr.writerows(IP4Addresslist) 113 | print("see file iplist.csv in "+os.getcwd()) 114 | 115 | def printlist(IP4Addresslist): 116 | ''' 117 | print the list of ip address 118 | ''' 119 | print("ID,Type,Name,IP4Address,IPState,MACAddress") 120 | for item in searchReserved(listofIP): 121 | print(item) 122 | 123 | printlist(listofIP) 124 | exportToCSV(searchReserved(listofIP)) 125 | -------------------------------------------------------------------------------- /Episodes/Episode7/1-deleterecord-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 31-05-2018 10:25 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | from zeep import Client 28 | import zeep 29 | from getpass import getpass 30 | import logging 31 | import sys 32 | 33 | 34 | # turn on logging 35 | logging.basicConfig( 36 | filename="debug-soap.log", 37 | level=logging.DEBUG, 38 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 39 | datefmt='%m/%d/%Y %I:%M:%S %p' 40 | ) 41 | 42 | # remove this if your are using python 3.x 43 | # input = raw_input 44 | 45 | # Parameters 46 | BAMAddress = "bam.lab.corp" 47 | url = "http://"+BAMAddress+"/Services/API?wsdl" 48 | account = "" 49 | try: 50 | account = input("Enter User Name: ") 51 | if account == "": 52 | raise ValueError("Error: No User Name was provided") 53 | except Exception as e: 54 | print(e) 55 | logging.exception(e) 56 | sys.exit(1) 57 | account_password = getpass("Enter Password: ") 58 | hostrecordname = "test.lab.corp" 59 | 60 | 61 | def gethostrecordwithhint(bam_url, login_user, login_password, host_record_name): 62 | """get the host record FQDN and return the entity details 63 | """ 64 | records = "" 65 | try: 66 | # api session 67 | client = Client(bam_url) 68 | # login 69 | client.service.login(login_user, login_password) 70 | # get the host record details 71 | records = client.service.getHostRecordsByHint( 72 | 0, 73 | 10, 74 | "hint="+host_record_name+"|" 75 | ) 76 | # logout of BAM 77 | client.service.logout() 78 | except zeep.exceptions.Fault as e: 79 | print(e.message) 80 | logging.exception(e) 81 | sys.exit(1) 82 | # return the records from function 83 | return records 84 | 85 | 86 | def deletehostrecord(bam_url, login_user, login_password, host_record): 87 | """Delete host record 88 | """ 89 | # api session 90 | client = Client(bam_url) 91 | 92 | # login 93 | client.service.login(login_user, login_password) 94 | # get the host record details 95 | zone = client.service.getParent(host_record['id']) 96 | print("You are requesting to delete:") 97 | print(host_record) 98 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 99 | if answer.lower() == "y": 100 | deletion = client.service.deleteWithOptions( 101 | host_record['id'], 102 | "deleteOrphanedIPAddresses=true|") 103 | elif answer.lower() == "n": 104 | print("You requested deletion to be stopped") 105 | else: 106 | print("Invalid Entry") 107 | # logout of BAM 108 | client.service.quickDeploy(zone["id"], "services=DNS") 109 | 110 | client.service.logout() 111 | # return the records from function 112 | 113 | 114 | hostrecords = gethostrecordwithhint( 115 | bam_url=url, 116 | login_user=account, 117 | login_password=account_password, 118 | host_record_name=hostrecordname 119 | ) 120 | 121 | print(hostrecords) 122 | deletehostrecord(url, account, account_password, hostrecords[0]) 123 | -------------------------------------------------------------------------------- /Episodes/Episode2/2-assignDHCPReservation-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | '''2-assignDHCPReservation-SOAP 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-11-22T16:25:09.525Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | import requests, json, getpass 28 | 29 | #main variables 30 | user = "api" 31 | password = getpass.getpass("Enter password: ") 32 | bamurl = "bam.lab.corp" 33 | mainurl = "https://"+bamurl+"/Services/REST/v1/" 34 | bamcert = "bam.crt" 35 | 36 | # Add DHCP reservation for client 37 | mac_address="BB:CC:DD:AA:AA:AA" 38 | networkcidr="192.168.3.0/24" 39 | hostname="appsrv23" 40 | zonename="lab.corp" 41 | viewname="default" 42 | config_name="main" 43 | 44 | # Login 45 | loginurl = mainurl+"login?" 46 | loginparam = {"username":account,"password":account_password} 47 | 48 | # logout method 49 | logouturl = mainurl+"logout?" 50 | 51 | # getEntityByName 52 | getEntityByNameurl = mainurl+"getEntityByName?" 53 | getEntityByNameparams = { 54 | "parentId":"0", 55 | "name":config_name, 56 | "type":"Configuration" 57 | } 58 | 59 | # getIPRangedByIP 60 | getIPRangedByIPurl = mainurl+"getIPRangedByIP?" 61 | getIPRangedByIPparams = { 62 | "containerId":"0", 63 | "type":"IP4Network", 64 | "address":"192.168.3.1" 65 | } 66 | 67 | # assignNextAvailableIP4Address 68 | assignNextAvailableIP4Addressurl = mainurl+"assignNextAvailableIP4Address?" 69 | assignNextAvailableIP4Addressparams = { 70 | "configurationId":"0", 71 | "parentId":"0", 72 | "macAddress":mac_address, 73 | "hostInfo":"", 74 | "action":"MAKE_DHCP_RESERVED", 75 | "properties":"name="+hostname+"|locationCode=US DAL|" 76 | } 77 | 78 | # login to BAM 79 | response = requests.get(loginurl, params=loginparam, verify=bamcert) 80 | # process the token 81 | token = str(response.json()) 82 | token = token.split()[2]+" "+token.split()[3] 83 | # set header value for the next methods 84 | header={'Authorization':token,'Content-Type':'application/json'} 85 | # configuration information 86 | response = requests.get( 87 | getEntityByNameurl, 88 | params=getEntityByNameparams, 89 | headers=header, 90 | verify=bamcert 91 | ) 92 | configinfo = response.json() 93 | # set the valie of containerId for getIPRangedByIPparams to config id 94 | getIPRangedByIPparams["containerId"] = configinfo['id'] 95 | # IPv4 Network information 96 | response = requests.get( 97 | getIPRangedByIPurl, 98 | params=getIPRangedByIPparams, 99 | headers=header, 100 | verify=bamcert 101 | ) 102 | networkinfo = response.json() 103 | 104 | # view information 105 | getEntityByNameparams["parentId"] = configinfo['id'] 106 | getEntityByNameparams["name"] = viewname 107 | getEntityByNameparams["type"] = "View" 108 | 109 | response = requests.get( 110 | getEntityByNameurl, 111 | params=getEntityByNameparams, 112 | headers=header, 113 | verify=bamcert 114 | ) 115 | viewinfo = response.json() 116 | 117 | # assignNextAvailableIP4Address 118 | hostInfo = hostname+"."+zonename+","+str(viewinfo['id'])+",true,false" 119 | assignNextAvailableIP4Addressparams['hostInfo'] = hostInfo 120 | assignNextAvailableIP4Addressparams['parentId'] = networkinfo['id'] 121 | assignNextAvailableIP4Addressparams['configurationId'] = configinfo['id'] 122 | 123 | response = requests.post( 124 | assignNextAvailableIP4Addressurl, 125 | params=assignNextAvailableIP4Addressparams, 126 | headers=header, 127 | verify=bamcert 128 | ) 129 | print(response.json()) 130 | 131 | # logout of api session 132 | response = requests.get(logouturl,headers=header,verify=bamcert) 133 | print(response.json()) 134 | -------------------------------------------------------------------------------- /Episodes/Episode6/2-getServers-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 26-04-2018 07:02 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, logging 27 | from getpass import getpass 28 | import sys 29 | 30 | logging.basicConfig(filename="warning-rest.log", 31 | level=logging.DEBUG, 32 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 33 | datefmt='%m/%d/%Y %I:%M:%S %p') 34 | 35 | 36 | def get(bam_url, api_call, call_parameters, header): 37 | """requests get call that returns the json data""" 38 | 39 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 40 | try: 41 | if call_parameters == "": 42 | response = requests.get(call_url, headers=header) 43 | else: 44 | response = requests.get(call_url, params=call_parameters, headers=header) 45 | 46 | #print(response.text) 47 | if response.status_code != 200: 48 | raise requests.ConnectionError("Code "+str(response.status_code)+" "+response.json()) 49 | 50 | except requests.exceptions.RequestException as e: 51 | print(e) 52 | logging.exception(e) 53 | sys.exit(1) 54 | 55 | return response.json() 56 | 57 | def deletecall(bam_url,api_call,call_parameters,delete_entity,header): 58 | """API request to delete and return values""" 59 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 60 | print("You are requesting to delete:") 61 | print(delete_entity) 62 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 63 | try: 64 | if answer.lower() == "y": 65 | response = requests.delete(call_url,params=call_parameters, headers=header) 66 | return response.json() 67 | elif answer.lower() == "n": 68 | return "You aborted deletion" 69 | else: 70 | return "You entered an invalid character" 71 | except requests.exceptions.RequestException as e: 72 | print(e) 73 | 74 | 75 | def update_header(login_response, call_header): 76 | """Function to process and update the header after login""" 77 | 78 | token = str(login_response).split()[2] + " " + str(login_response).split()[3] 79 | call_header['Authorization'] = token 80 | return call_header 81 | 82 | #input = raw_input 83 | 84 | user = input("Enter Your User ID: ") 85 | password = getpass("Enter Password: ") 86 | bamurl = "bam.lab.corp" 87 | header = {'Content-Type': 'application/json'} 88 | 89 | # Login parameters 90 | login_param = {"username": user, "password": password} 91 | 92 | # login to BAM 93 | login = get(bamurl, "login", login_param, header) 94 | 95 | # update header with login token 96 | header = update_header(login, header) 97 | 98 | # get BAM System info 99 | """sys_info = get(bamurl, "getSystemInfo", "", header) 100 | for item in sys_info.split("|"): 101 | print(item)""" 102 | 103 | # get servers 104 | configid = 100957 105 | getserverparams = { 106 | 'parentId': configid, 107 | 'type':'Server', 108 | 'start':0, 109 | 'count':100 110 | } 111 | serverslist = get(bamurl,"getEntities", getserverparams, header) 112 | # need to transform all properties to a new list that can be used for reporting 113 | reformattedlist = [] 114 | 115 | # get every server from list 116 | for server in serverslist: 117 | # get properties for each server 118 | propertieslist = list(server['properties'].split("|")) 119 | # create empty dictionary for server properties 120 | propertiesdic = {} 121 | for item in propertieslist: 122 | if item is not '': 123 | # only show none blank properties 124 | # create a temp blank list 125 | shortlist=[] 126 | # take the propertie is split it into the temp list 127 | shortlist = list(item.split("=")) 128 | # append the property dictionary with property from temp list 129 | propertiesdic[shortlist[0]] = shortlist[1] 130 | else: 131 | break 132 | # update the server dictionary with new properties 133 | server.update(propertiesdic) 134 | #print(server) 135 | 136 | # remove the properties key 137 | del server['properties'] 138 | #print(server) 139 | 140 | # append the reformatted list with the updated dictionary 141 | reformattedlist.append(server) 142 | 143 | # print the reformatted list that show properties of every entity as dictionary 144 | print(reformattedlist) 145 | 146 | # logout 147 | logout = get(bamurl, "logout", "", header) 148 | print(logout) 149 | -------------------------------------------------------------------------------- /Episodes/Episode3/2-getreservedip-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 24-01-2018 09:17 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json, getpass, csv, os 27 | 28 | #main variables 29 | user = "api" 30 | password = getpass.getpass("Enter Password: ") 31 | bamurl = "bam.lab.corp" 32 | mainurl = "https://"+bamurl+"/Services/REST/v1/" 33 | bamcert = "bam.crt" 34 | s = requests.Session() 35 | s.verify = bamcert 36 | # methods url 37 | # Login method 38 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 39 | loginurl = mainurl+"login?" 40 | param = {"username":user,"password":password} 41 | 42 | # getsysinfo method 43 | getsysinfourl = mainurl+"getSystemInfo?" 44 | 45 | # logout method 46 | logouturl = mainurl+"logout?" 47 | 48 | #config Parameters for getEntityByName 49 | getentitybynameurl = mainurl+"getEntityByName?" 50 | getEntityByNameParams = { 51 | "parentid":"", 52 | "name":"main", 53 | "type":"Configuration" 54 | } 55 | 56 | # getIPRangedByIP Parameters 57 | getIPRangedByIPURL = mainurl+"getIPRangedByIP?" 58 | getIPRangedByIPparams = { 59 | "containerId":0, 60 | "type":"IP4Network", 61 | "address":"192.168.2.1" 62 | } 63 | 64 | # getEntities Parameters 65 | getEntitiesurl = mainurl+"getEntities?" 66 | getEntitiesparams = { 67 | "parentId":0, 68 | "type":"IP4Address", 69 | "start":0, 70 | "count":250 71 | } 72 | 73 | # login to BAM 74 | response = requests.get(loginurl, params=param) 75 | 76 | # get the Token and put it into a variable 77 | token = str(response.json()) 78 | token = token.split()[2]+" "+token.split()[3] 79 | #print token 80 | # set header value for the next methods 81 | header={'Authorization':token,'Content-Type':'application/json'} 82 | 83 | # you api calls 84 | 85 | response = requests.get(getentitybynameurl, 86 | params=getEntityByNameParams, 87 | headers=header) 88 | config = response.json() 89 | getIPRangedByIPparams['containerId'] = config['id'] 90 | 91 | response = requests.get(getIPRangedByIPURL, 92 | params=getIPRangedByIPparams, 93 | headers=header) 94 | londonnetwork = response.json() 95 | getEntitiesparams['parentId'] = londonnetwork['id'] 96 | 97 | response = requests.get(getEntitiesurl, 98 | params=getEntitiesparams, 99 | headers=header) 100 | iplist = response.json() 101 | print(iplist) 102 | # Logout of BAM 103 | response=requests.get(logouturl,headers=header) 104 | print(response.json()) 105 | 106 | def printEntity(apientity): 107 | ''' 108 | takes a entity got by prints it easy to read with properties 109 | ''' 110 | for key in apientity: 111 | if key == 'properties': 112 | if apientity['properties'] != None: 113 | print(key) 114 | for props in apientity[key].split("|"): 115 | print(props) 116 | else: 117 | print(key+": None") 118 | 119 | else: 120 | print(key+"="+str(apientity[key])) 121 | 122 | 123 | def searchReserved(listofips): 124 | """Search for iplist and return only DHCP_RESERVED addresses 125 | """ 126 | searchlist=[] 127 | for address in listofips: 128 | if address["name"] == None: 129 | address["name"] = "" 130 | 131 | ipitem = [address['id'],address['type'],address['name']] 132 | 133 | addressprops="" 134 | for aprop in address['properties'].split("|"): 135 | proplist = aprop.split("=") 136 | if len(proplist) > 1: 137 | ipitem.append(proplist[1]) 138 | 139 | del ipitem[5] 140 | 141 | if "DHCP_RESERVED" in ipitem: 142 | searchlist.append(ipitem) 143 | return searchlist 144 | 145 | def exportToCSV(IP4Addresslist): 146 | ''' 147 | Export list of ip addresses to CSV file named iplist.CSV 148 | ''' 149 | csvfile = "londoniplist.csv" 150 | header = ["ID","Type","Name","IP4Address","IPState","MACAddress"] 151 | IP4Addresslist.insert(0,header) 152 | with open(csvfile,'wb') as outfile: 153 | wr = csv.writer(outfile, delimiter=',',quoting=csv.QUOTE_ALL) 154 | wr.writerows(IP4Addresslist) 155 | print("see file londoniplist.csv in "+os.getcwd()) 156 | 157 | def printlist(IP4Addresslist): 158 | ''' 159 | print the list of ip address 160 | ''' 161 | print("ID,Type,Name,IP4Address,IPState,MACAddress") 162 | for item in IP4Addresslist: 163 | print(item) 164 | 165 | filterediplist = searchReserved(iplist) 166 | exportToCSV(filterediplist) 167 | printlist(filterediplist) 168 | -------------------------------------------------------------------------------- /Episodes/Episode1/2-addHost-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python2 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 2017-10-23T18:44:38.677Z 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | 27 | import requests, json 28 | 29 | # Parameters 30 | #main variables 31 | user = "api" 32 | # saving passwords in scripts is unsecure see episode 2 on how to secure your 33 | # passwords. see link 34 | password = "pass" 35 | bamurl = "bam.lab.corp" 36 | 37 | # we are using unsecure http example, for secure https connection with BAM see 38 | # episode 2 on how to verify SSL connection. 39 | # see link 40 | mainurl = "http://"+bamurl+"/Services/REST/v1/" 41 | 42 | # Server information 43 | ipaddress='192.168.0.16' 44 | hostname='FINRPT02' 45 | alias='reporting2' 46 | zone='lab.corp' 47 | 48 | # additional info known 49 | config_name='main' 50 | view_name='default' 51 | 52 | # Login method 53 | loginurl = mainurl+"login?username="+account+"&password="+account_password 54 | # getsysinfo method 55 | getsysinfourl = mainurl+"getSystemInfo?" 56 | # logout method 57 | logouturl = mainurl+"logout?" 58 | # getEntityByName method 59 | e_parentId=0 60 | e_name="" 61 | e_type="" 62 | getEntityByName = mainurl+"getEntityByName?parentId="+ str(e_parentId) \ 63 | +"&name="+e_name+"&type="+e_type 64 | # getEntityById 65 | e_id=0 66 | getEntityById = mainurl+"getEntityById?id="+str(e_id) 67 | # addHostRecord 68 | r_viewId = 0 69 | r_absoluteName="" 70 | r_addresses = "" 71 | r_ttl="" 72 | r_properties="" 73 | addHostRecord = mainurl+"addHostRecord?viewId="+str(r_viewId)+"&absoluteName=" \ 74 | +r_absoluteName+"&addresses="+r_addresses+ \ 75 | "&ttl="+r_ttl+"&properties="+r_properties 76 | # addAliasRecord 77 | r_linkedRecordName="" 78 | addAliasRecord = mainurl+"addAliasRecord?viewId="+str(r_viewId)+"&absoluteName=" \ 79 | +r_absoluteName+"&linkedRecordName="+r_linkedRecordName+ \ 80 | "&ttl="+r_ttl+"&properties="+r_properties 81 | 82 | # login to BAM 83 | response = requests.get(loginurl) 84 | # get the Token and put it into a variable 85 | token = str(response.json()) 86 | token = token.split()[2]+" "+token.split()[3] 87 | # set header value for the next methods 88 | header={'Authorization':token,'Content-Type':'application/json'} 89 | 90 | # api calls 91 | # configuration information 92 | #config_info = client.service.getEntityByName(0,config_name,'Configuration') 93 | #print(config_info) 94 | # set Parametere to get configuration 95 | e_name='main' 96 | e_type="Configuration" 97 | getEntityByName = mainurl+"getEntityByName?parentId="+ str(e_parentId) \ 98 | +"&name="+e_name+"&type="+e_type 99 | # run the api call 100 | response = requests.get(getEntityByName,headers=header) 101 | config_info = response.json() 102 | print("-------config------") 103 | print(config_info) 104 | print("------config['id']-------") 105 | print(config_info['id']) 106 | print("-------------") 107 | # view information 108 | e_name='default' 109 | e_type='View' 110 | e_parentId = config_info['id'] 111 | getEntityByName = mainurl+"getEntityByName?parentId="+ str(e_parentId) \ 112 | +"&name="+e_name+"&type="+e_type 113 | 114 | # run the api call 115 | response = requests.get(getEntityByName,headers=header) 116 | view_info = response.json() 117 | print("------view-------") 118 | print(view_info) 119 | print("-------------") 120 | # addhost record 121 | r_viewId = view_info['id'] 122 | r_absoluteName= hostname+"."+zone 123 | r_addresses = ipaddress 124 | r_ttl="-1" 125 | r_properties="reverseRecord=true" 126 | addHostRecord = mainurl+"addHostRecord?viewId="+str(r_viewId)+"&absoluteName=" \ 127 | +r_absoluteName+"&addresses="+r_addresses+ \ 128 | "&ttl="+r_ttl+"&properties="+r_properties 129 | 130 | # run the api call to addhostrecord 131 | response = requests.post(addHostRecord,headers=header) 132 | hostinfo = response.text 133 | print("-------------") 134 | print("Record ID Created:"+str(hostinfo)) 135 | print("-------------") 136 | # get hostinformation 137 | e_id=hostinfo 138 | getEntityById = mainurl+"getEntityById?id="+str(e_id) 139 | 140 | # api call 141 | response = requests.get(getEntityById,headers=header) 142 | hostinfo = response.json() 143 | print("------full host info-------") 144 | print(hostinfo) 145 | print("-------------") 146 | 147 | # add alias record link to the record created 148 | r_absoluteName=alias+"."+zone 149 | r_properties="" 150 | r_linkedRecordName=hostname+"."+zone 151 | addAliasRecord = mainurl+"addAliasRecord?viewId="+str(r_viewId)+"&absoluteName=" \ 152 | +r_absoluteName+"&linkedRecordName="+r_linkedRecordName+ \ 153 | "&ttl="+r_ttl+"&properties="+r_properties 154 | 155 | # run the api call to addaliasrecord 156 | response = requests.post(addAliasRecord,headers=header) 157 | aliasinfo = response.text 158 | print("-------------") 159 | print("Record ID Created:"+str(aliasinfo)) 160 | print("-------------") 161 | 162 | # get alias record information 163 | e_id=aliasinfo 164 | getEntityById = mainurl+"getEntityById?id="+str(e_id) 165 | response = requests.get(getEntityById,headers=header) 166 | aliasinfo = response.text 167 | print("------alias record-------") 168 | print(aliasinfo) 169 | print("-------------") 170 | 171 | 172 | # logout from BAM 173 | response=requests.get(logouturl,headers=header) 174 | print(response.json()) 175 | -------------------------------------------------------------------------------- /Episodes/Episode4/2-Disaster-Recovery-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 15-02-2018 09:32 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests, json 27 | 28 | #main variables 29 | user = "api" 30 | password = "pass" 31 | bamurl = "bam.lab.corp" 32 | mainurl = "http://"+bamurl+"/Services/REST/v1/" 33 | 34 | configname = "main" 35 | servername = "bdds1" 36 | bdds1newip = "10.244.137.8" 37 | bdds1netmask = "255.255.255.0" 38 | 39 | """ 40 | Actions that are needed to restore services 41 | 1. Disable Server 42 | 2. Replace Server 43 | 3. Deploy Service to Server 44 | 4. Verify 45 | """ 46 | 47 | # methods url 48 | # Login method 49 | # http://bam.lab.corp/Services/REST/v1/login?username=api&password=pass 50 | loginurl = mainurl+"login?" 51 | param = {"username":user,"password":password} 52 | 53 | # getsysinfo method 54 | getsysinfourl = mainurl+"getSystemInfo?" 55 | 56 | # logout method 57 | logouturl = mainurl+"logout?" 58 | 59 | # replace server 60 | replaceurl = mainurl+"replaceServer?" 61 | replaceparams={ 62 | "serverId":0, 63 | "name":servername, 64 | "defaultInterface":"", 65 | "hostName":servername+".lab.corp", 66 | "password":"bluecat", 67 | "upgrade":False, 68 | "properties":"resetServices=true|"} 69 | # update server 70 | updateurl = mainurl+"update?" 71 | 72 | # deploy method 73 | deployurl = mainurl+"deployServer?" 74 | deployparams = {"serverId":0} 75 | 76 | 77 | 78 | # getEntityByName 79 | getEntityByNameurl = mainurl+"getEntityByName?" 80 | getEntityByNameparams = { 81 | "parentId":0, 82 | "name":configname, 83 | "type":"Configuration" 84 | } 85 | 86 | # getEntities 87 | getEntitiesurl = mainurl+"getEntities?" 88 | getEntitiesparams = { 89 | "parentId":0, 90 | "type":"", 91 | "start":0, 92 | "count":10 93 | } 94 | 95 | # login to BAM 96 | response = requests.get(loginurl, params=param) 97 | 98 | # print login 99 | #print(response) 100 | #print(response.text) 101 | #print(response.status_code) 102 | #print(response.json()) 103 | 104 | # get the Token and put it into a variable 105 | token = str(response.json()) 106 | token = token.split()[2]+" "+token.split()[3] 107 | #print token 108 | # set header value for the next methods 109 | header={'Authorization':token,'Content-Type':'application/json'} 110 | 111 | # get configuration 112 | response = requests.get( 113 | getEntityByNameurl, 114 | params=getEntityByNameparams, 115 | headers=header 116 | ) 117 | configinfo = response.json() 118 | print(configinfo) 119 | 120 | serverparams = { 121 | "parentId":configinfo['id'], 122 | "name":servername, 123 | "type":"Server" 124 | } 125 | # get Server bdds1 126 | response = requests.get( 127 | getEntityByNameurl, 128 | params=serverparams, 129 | headers=header 130 | ) 131 | serverinfo = response.json() 132 | print(serverinfo) 133 | serverinfo['properties'] = serverinfo['properties'] + "connected=false|" 134 | 135 | # disable bdds1 136 | response = requests.put( 137 | updateurl, 138 | json=serverinfo, 139 | headers=header 140 | ) 141 | print(response.status_code) 142 | 143 | getEntitiesparams['parentId'] = serverinfo['id'] 144 | getEntitiesparams['type'] = "NetworkServerInterface" 145 | response = requests.get( 146 | getEntitiesurl, 147 | params=getEntitiesparams, 148 | headers=header 149 | ) 150 | 151 | # get default network interface of bdds1 152 | getEntitiesparams['parentId'] = serverinfo['id'] 153 | getEntitiesparams['type'] = "NetworkServerInterface" 154 | response = requests.get( 155 | getEntitiesurl, 156 | params=getEntitiesparams, 157 | headers=header 158 | ) 159 | 160 | bdds1interface = response.json()[0] 161 | 162 | # replace server Parameters 163 | replaceparams['serverId'] = serverinfo['id'] 164 | replaceparams['defaultInterface'] = bdds1newip 165 | servicesIPv4Address = "servicesIPv4Address="+bdds1newip+"|" 166 | servicesIPv4Netmask = "servicesIPv4Netmask="+bdds1netmask+"|" 167 | replaceparams['properties'] = replaceparams['properties']+servicesIPv4Address+servicesIPv4Netmask 168 | 169 | response = requests.put( 170 | replaceurl, 171 | params=replaceparams, 172 | headers=header 173 | ) 174 | print(response.text) 175 | deployparams['serverId'] = serverinfo['id'] 176 | reponse = requests.post( 177 | deployurl, 178 | params=deployparams, 179 | headers=header 180 | ) 181 | print(response.text) 182 | import time 183 | time.sleep(5) 184 | # logout from BAM 185 | response=requests.get(logouturl,headers=header) 186 | print(response.json()) 187 | -------------------------------------------------------------------------------- /Episodes/Episode8/1-taging-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 31-05-2018 10:25 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests 27 | import logging 28 | from getpass import getpass 29 | import sys 30 | from time import sleep 31 | from ipaddress import ip_network 32 | 33 | logging.basicConfig( 34 | filename="debug-rest.log", 35 | level=logging.DEBUG, 36 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 37 | datefmt='%m/%d/%Y %I:%M:%S %p' 38 | ) 39 | 40 | 41 | def get(bam_url, api_call, call_parameters, header): 42 | """requests get call that returns the json data""" 43 | 44 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 45 | try: 46 | if call_parameters == "": 47 | response = requests.get(call_url, headers=header) 48 | else: 49 | response = requests.get( 50 | call_url, 51 | params=call_parameters, 52 | headers=header 53 | ) 54 | 55 | # print(response.text) 56 | if response.status_code != 200: 57 | raise requests.ConnectionError( 58 | "Code "+str(response.status_code)+" "+response.json() 59 | ) 60 | 61 | except requests.exceptions.RequestException as e: 62 | print(e) 63 | sys.exit(1) 64 | 65 | return response.json() 66 | 67 | 68 | def post(bam_url, api_call, call_parameters, header): 69 | """requests get call that returns the json data""" 70 | 71 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 72 | try: 73 | if call_parameters == "": 74 | raise ValueError("Missing parameters cannot execute") 75 | else: 76 | response = requests.post( 77 | call_url, 78 | params=call_parameters, 79 | headers=header 80 | ) 81 | 82 | # print(response.text) 83 | if response.status_code != 200: 84 | raise requests.ConnectionError( 85 | "Code "+str(response.status_code)+" "+response.json() 86 | ) 87 | 88 | except requests.exceptions.RequestException as e: 89 | print(e) 90 | sys.exit(1) 91 | 92 | return response 93 | 94 | 95 | def put(bam_url, api_call, call_parameters, header): 96 | """requests get call that returns the json data""" 97 | 98 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 99 | try: 100 | if call_parameters == "": 101 | raise ValueError("Missing parameters cannot execute") 102 | else: 103 | response = requests.put( 104 | call_url, 105 | params=call_parameters, 106 | headers=header 107 | ) 108 | 109 | # print(response.text) 110 | if response.status_code != 200: 111 | raise requests.ConnectionError( 112 | "Code "+str(response.status_code)+" "+response.json() 113 | ) 114 | 115 | except requests.exceptions.RequestException as e: 116 | print(e) 117 | sys.exit(1) 118 | 119 | return response 120 | 121 | def deletecall(bam_url, api_call, call_parameters, delete_entity, header): 122 | """API request to delete and return values""" 123 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 124 | print("You are requesting to delete:") 125 | print(delete_entity) 126 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 127 | try: 128 | if answer.lower() == "y": 129 | response = requests.delete( 130 | call_url, 131 | params=call_parameters, 132 | headers=header 133 | ) 134 | return response.json() 135 | elif answer.lower() == "n": 136 | return "You aborted deletion" 137 | else: 138 | return "You entered an invalid character" 139 | except requests.exceptions.RequestException as e: 140 | print(e) 141 | 142 | 143 | def update_header(login_response, call_header): 144 | """Function to process and update the header after login""" 145 | 146 | token = str(login_response).split()[2] + " " + str(login_response).split()[3] 147 | call_header['Authorization'] = token 148 | return call_header 149 | 150 | # input = raw_input 151 | 152 | 153 | user = input("Enter Your User ID: ") 154 | password = getpass("Enter Password: ") 155 | bamurl = "bam.lab.corp" 156 | header = {'Content-Type': 'application/json'} 157 | 158 | # Login parameters 159 | login_param = {"username": user, "password": password} 160 | 161 | # login to BAM 162 | login = get(bamurl, "login", login_param, header) 163 | 164 | # update header with login token 165 | header = update_header(login, header) 166 | 167 | # add DHCP Option 168 | taginfo = {"keyword":"torip","types":"Tag", "start":0, "count": 10} 169 | searchresults = get(bamurl, "searchByObjectTypes", taginfo, header) 170 | print(searchresults) 171 | tortag = {} 172 | for tagitem in searchresults: 173 | if tagitem["name"] == "torip": 174 | tortag = tagitem 175 | 176 | print(tortag) 177 | 178 | network = ip_network("192.168.0.0/24") 179 | print(network) 180 | networkid={"id":105015} 181 | getnetwork = get(bamurl,"getEntityById", networkid, header) 182 | getEntitiesparam = { "parentId": getnetwork['id'], "type": "IP4Address", "start": 0, "count": network.num_addresses} 183 | ipaddresslist = get(bamurl, "getEntities", getEntitiesparam, header) 184 | print(ipaddresslist) 185 | for ip in ipaddresslist: 186 | linentityparam = {"entity1Id": tortag['id'], "entity2Id": ip['id'], "properties":"" } 187 | print(linentityparam) 188 | item = put(bamurl,"linkEntities",linentityparam, header) 189 | print(item.content) 190 | # logout 191 | logout = get(bamurl, "logout", "", header) 192 | print(logout) 193 | -------------------------------------------------------------------------------- /Episodes/Episode7/2-fulldeploy-REST.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 31-05-2018 10:25 6 | 7 | Disclaimer: 8 | All information, documentation, and code is provided to you AS-IS and should 9 | only be used in an internal, non-production laboratory environment. 10 | 11 | License: 12 | Copyright 2017 BlueCat Networks, Inc. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"); 15 | you may not use this file except in compliance with the License. 16 | You may obtain a copy of the License at 17 | 18 | http://www.apache.org/licenses/LICENSE-2.0 19 | 20 | Unless required by applicable law or agreed to in writing, software 21 | distributed under the License is distributed on an "AS IS" BASIS, 22 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 23 | See the License for the specific language governing permissions and 24 | limitations under the License. 25 | ''' 26 | import requests 27 | import logging 28 | from getpass import getpass 29 | import sys 30 | from time import sleep 31 | 32 | logging.basicConfig( 33 | filename="debug-rest.log", 34 | level=logging.DEBUG, 35 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 36 | datefmt='%m/%d/%Y %I:%M:%S %p' 37 | ) 38 | 39 | 40 | def get(bam_url, api_call, call_parameters, header): 41 | """requests get call that returns the json data""" 42 | 43 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 44 | try: 45 | if call_parameters == "": 46 | response = requests.get(call_url, headers=header) 47 | else: 48 | response = requests.get( 49 | call_url, 50 | params=call_parameters, 51 | headers=header 52 | ) 53 | 54 | # print(response.text) 55 | if response.status_code != 200: 56 | raise requests.ConnectionError( 57 | "Code "+str(response.status_code)+" "+response.json() 58 | ) 59 | 60 | except requests.exceptions.RequestException as e: 61 | print(e) 62 | sys.exit(1) 63 | 64 | return response.json() 65 | 66 | 67 | def post(bam_url, api_call, call_parameters, header): 68 | """requests get call that returns the json data""" 69 | 70 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 71 | try: 72 | if call_parameters == "": 73 | raise ValueError("Missing parameters cannot execute") 74 | else: 75 | response = requests.post( 76 | call_url, 77 | params=call_parameters, 78 | headers=header 79 | ) 80 | 81 | # print(response.text) 82 | if response.status_code != 200: 83 | raise requests.ConnectionError( 84 | "Code "+str(response.status_code)+" "+response.json() 85 | ) 86 | 87 | except requests.exceptions.RequestException as e: 88 | print(e) 89 | sys.exit(1) 90 | 91 | return response 92 | 93 | 94 | def put(bam_url, api_call, call_parameters, header): 95 | """requests get call that returns the json data""" 96 | 97 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 98 | try: 99 | if call_parameters == "": 100 | raise ValueError("Missing parameters cannot execute") 101 | else: 102 | response = requests.put( 103 | call_url, 104 | json=call_parameters, 105 | headers=header 106 | ) 107 | 108 | # print(response.text) 109 | if response.status_code != 200: 110 | raise requests.ConnectionError( 111 | "Code "+str(response.status_code)+" "+response.json() 112 | ) 113 | 114 | except requests.exceptions.RequestException as e: 115 | print(e) 116 | sys.exit(1) 117 | 118 | return response 119 | 120 | def deletecall(bam_url, api_call, call_parameters, delete_entity, header): 121 | """API request to delete and return values""" 122 | call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?" 123 | print("You are requesting to delete:") 124 | print(delete_entity) 125 | answer = input("Do you want to proceed (y (yes) or n (no))? ") 126 | try: 127 | if answer.lower() == "y": 128 | response = requests.delete( 129 | call_url, 130 | params=call_parameters, 131 | headers=header 132 | ) 133 | return response.json() 134 | elif answer.lower() == "n": 135 | return "You aborted deletion" 136 | else: 137 | return "You entered an invalid character" 138 | except requests.exceptions.RequestException as e: 139 | print(e) 140 | 141 | 142 | def update_header(login_response, call_header): 143 | """Function to process and update the header after login""" 144 | 145 | token = str(login_response).split()[2] + " " + str(login_response).split()[3] 146 | call_header['Authorization'] = token 147 | return call_header 148 | 149 | # input = raw_input 150 | 151 | 152 | user = input("Enter Your User ID: ") 153 | password = getpass("Enter Password: ") 154 | bamurl = "bam.lab.corp" 155 | header = {'Content-Type': 'application/json'} 156 | 157 | # Login parameters 158 | login_param = {"username": user, "password": password} 159 | 160 | # login to BAM 161 | login = get(bamurl, "login", login_param, header) 162 | 163 | # update header with login token 164 | header = update_header(login, header) 165 | 166 | # add DHCP Option 167 | optionparams = { 168 | "entityId": 100957, 169 | "name": "dns-server", 170 | "serverId": 0 171 | } 172 | 173 | newdnsserver = "10.244.137.8" 174 | 175 | dnsoption = get(bamurl, "getDHCPClientDeploymentOption", optionparams, header) 176 | 177 | dnsoption["value"] = newdnsserver 178 | 179 | updated = put(bamurl,"updateDHCPClientDeploymentOption", dnsoption, header) 180 | 181 | print(updated) 182 | 183 | 184 | server = {"id": 100969, "name": "bdds1"} 185 | # deploy to BAM 186 | deployparam = { 187 | "serverId": 100969, 188 | "properties": "services=DNS,DHCP|forceDNSFullDeployment=true" 189 | } 190 | deploy = post(bamurl, "deployServerConfig", deployparam, header) 191 | # sleep(5) 192 | 193 | # print(deploy.text) 194 | 195 | 196 | def checkstatus(server_id): 197 | """Check the status of deployment""" 198 | deploy_status = 0 199 | statusparam = {"serverId": server_id, "properties": ""} 200 | 201 | while deploy_status < 2: 202 | deploy_status = get( 203 | bamurl, 204 | "getServerDeploymentStatus", 205 | statusparam, 206 | header 207 | ) 208 | print("Status Code:", deploy_status) 209 | sleep(0.5) 210 | 211 | 212 | checkstatus(100969) 213 | # logout 214 | logout = get(bamurl, "logout", "", header) 215 | print(logout) 216 | -------------------------------------------------------------------------------- /Episodes/Episode4/1-Automated-Services-SOAP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """Automate Services using API 4 | Author: vivek Mistry @[Vivek M.] 5 | Date: 15-02-2018 09:32 6 | 7 | 8 | License: 9 | Copyright 2017 BlueCat Networks, Inc. 10 | 11 | Licensed under the Apache License, Version 2.0 (the "License"); 12 | you may not use this file except in compliance with the License. 13 | You may obtain a copy of the License at 14 | 15 | http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | See the License for the specific language governing permissions and 21 | limitations under the License. 22 | """ 23 | 24 | from zeep import Client 25 | from getpass import getpass 26 | 27 | #Parameters 28 | BAMAddress="bam.lab.corp" 29 | url="http://"+BAMAddress+"/Services/API?wsdl" 30 | account="api" 31 | account_password=getpass("Enter Password: ") 32 | 33 | """Steps to create on Parent block 10.0.0.0/8 34 | 1. Create the next available /22 Block 35 | 2. Create the 2 next available /24 Networks 36 | 3. Create the 2 next available /25 Networks 37 | 4. Add 2 BDDS 20 38 | 5. Add DNS and DHCP roles to the network with the 2 BDDS 39 | """ 40 | configname="main" 41 | viewname="default" 42 | mainblock="10.0.0.0/8" 43 | # process parameters customer will give 44 | blockname = "ChrylerBuilding" 45 | locationcode = "US MNH" 46 | locationname = locationcode.replace(" ","") 47 | bdds1name = "BDDS"+locationname+"1" 48 | bdds2name = "BDDS"+locationname+"2" 49 | 50 | 51 | #api session 52 | client = Client(url) 53 | #login to api session 54 | client.service.login(account,account_password) 55 | # Your api calls 56 | # test connection with BAM 57 | #sysinfo = client.service.getSystemInfo() 58 | #print(sysinfo) 59 | # get configuration information 60 | configinfo = client.service.getEntityByName(0,configname,"Configuration") 61 | # get main block information 62 | mainblockinfo = client.service.getEntityByCIDR(configinfo.id,mainblock,"IP4Block") 63 | # Get the first available /22 block and create it 64 | block_22 = client.service.getNextAvailableIPRanges( 65 | mainblockinfo.id, 66 | 1024, 67 | "IP4Block", 68 | 1, 69 | "reuseExsting=False|isLargerAllowed=False|autoCreate=False" 70 | ) 71 | block_22 = client.service.getEntityById(block_22[0].id) 72 | # Update the name and location code for block 73 | block_22.name = blockname 74 | block_22.properties = "locationInherited=false|locationCode="+locationcode+"|" 75 | # send update to BAM 76 | client.service.update(block_22) 77 | # check if updated was completed 78 | block_22 = client.service.getEntityById(block_22.id) 79 | 80 | print(block_22) 81 | # Get first 2 available /24 networks for wired and wireless devices 82 | network_24 = client.service.getNextAvailableIPRanges( 83 | block_22.id, 84 | 256, 85 | "IP4Network", 86 | 2, 87 | "reuseExsting=False|isLargerAllowed=False|autoCreate=False|" 88 | ) 89 | 90 | print(network_24) 91 | # update the names of the 92 | network_24[0].name = locationname+"_Wired" 93 | network_24[1].name = locationname+"_Wireless" 94 | 95 | # send update to BAM 96 | for network in network_24: 97 | client.service.update(network) 98 | 99 | 100 | # verify the networks have the correct details 101 | for network in network_24: 102 | print(client.service.getEntityById(network.id)) 103 | # Get first 2 available /25 networks for servers and IOT devices 104 | network_25 = client.service.getNextAvailableIPRanges( 105 | block_22.id, 106 | 128, 107 | "IP4Network", 108 | 2, 109 | "reuseExsting=False|isLargerAllowed=False|autoCreate=False|" 110 | ) 111 | # update names 112 | network_25[0].name = locationname+"_Servers" 113 | network_25[1].name = locationname+"_IOT" 114 | 115 | # send updates to BAM 116 | for network in network_25: 117 | client.service.update(network) 118 | # verify the changes 119 | for network in network_25: 120 | print(client.service.getEntityById(network.id)) 121 | 122 | 123 | def getippart(ipentity): 124 | """ 125 | Get the CIDR from network entity and return the first 3 octates 126 | """ 127 | cidr = "" 128 | for prop in ipentity.properties.split("|"): 129 | if prop.startswith("CIDR"): 130 | cidr=prop.split("=")[1] 131 | iphead = cidr[:-4] 132 | return iphead 133 | 134 | bdds1ip = getippart(network_25[0])+"11" 135 | bdds2ip = getippart(network_25[0])+"12" 136 | bddsprofile = "DNS_DHCP_SERVER_20" 137 | bddsnetmask = "255.255.255.128" 138 | 139 | # add servers 140 | bdds1 = client.service.addServer( 141 | configinfo.id, 142 | bdds1name, 143 | bdds1ip, 144 | bdds1name+"lab.corp", 145 | bddsprofile, 146 | "connected=false|servicesIPv4Address="+bdds1ip+"|servicesIPv4Netmask="+bddsnetmask+"|locationCode="+locationcode+"|" 147 | ) 148 | bdds1 = client.service.getEntityById(bdds1) 149 | 150 | bdds2 = client.service.addServer( 151 | configinfo.id, 152 | bdds2name, 153 | bdds2ip, 154 | bdds2name+"lab.corp", 155 | bddsprofile, 156 | "connected=false|servicesIPv4Address="+bdds2ip+"|servicesIPv4Netmask="+bddsnetmask+"|locationCode="+locationcode+"|" 157 | ) 158 | bdds2 = client.service.getEntityById(bdds2) 159 | 160 | bdds1ipassign = client.service.assignIP4Address( 161 | configinfo.id, 162 | bdds1ip, 163 | "", 164 | "", 165 | "MAKE_STATIC", 166 | "name="+bdds1name+"|" 167 | ) 168 | 169 | bdds2ipassign = client.service.assignIP4Address( 170 | configinfo.id, 171 | bdds2ip, 172 | "", 173 | "", 174 | "MAKE_STATIC", 175 | "name="+bdds2name+"|" 176 | ) 177 | 178 | bdds1interface = client.service.getEntities(bdds1.id, 179 | "NetworkServerInterface", 180 | 0,10) 181 | bdds1interface = bdds1interface[0] 182 | 183 | bdds2interface = client.service.getEntities(bdds2.id, 184 | "NetworkServerInterface", 185 | 0,10) 186 | bdds2interface = bdds2interface[0] 187 | 188 | dhcprole = client.service.addDHCPDeploymentRole( 189 | block_22.id, 190 | bdds1interface.id, 191 | "MASTER", 192 | "secondaryServerInterfaceId="+str(bdds2interface.id)+"|" 193 | ) 194 | print(dhcprole) 195 | #logout 196 | client.service.logout() 197 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------