diff --git a/LM-1201/00-prep-02-overview-of-rest-apis/spark-room-easy.py b/LM-1201/00-prep-02-overview-of-rest-apis/spark-room-easy.py index 4369c52..7baa400 100644 --- a/LM-1201/00-prep-02-overview-of-rest-apis/spark-room-easy.py +++ b/LM-1201/00-prep-02-overview-of-rest-apis/spark-room-easy.py @@ -8,10 +8,9 @@ spark_header = {'Authorization': accessToken_hdr} uri = 'https://api.ciscospark.com/v1/rooms' resp = requests.get(uri, headers=spark_header) -print("Spark Rooms you belong to: ") +print("Spark Rooms you belong to: ") print(resp.text) print() print("Spark Rooms in easier to read format - pretty format:") print (json.dumps(resp.json(), indent=4, separators=(',', ': '))) - diff --git a/LM-1201/02-python-primer/concat.py b/LM-1201/02-python-primer/concat.py index aae2cae..21cd7b2 100644 --- a/LM-1201/02-python-primer/concat.py +++ b/LM-1201/02-python-primer/concat.py @@ -19,4 +19,4 @@ print("My name is " + name + ". I'm " + str(feet) + " feet " + str(inches) + " inches tall.") myStr = "My name is " + name + ". I'm " + str(feet) + " feet " + str(inches) + " inches tall." -print(myStr) \ No newline at end of file +print(myStr) diff --git a/LM-1201/02-python-primer/concat_sol.py b/LM-1201/02-python-primer/concat_sol.py index 2fa4bbb..335062a 100644 --- a/LM-1201/02-python-primer/concat_sol.py +++ b/LM-1201/02-python-primer/concat_sol.py @@ -26,4 +26,4 @@ myStr = myVarBlue + " violets can grow up to " + str(inches) + " inches!" print(myStr) -print("The " + myVarBlue + " sky turned " + myVarRed + "!") \ No newline at end of file +print("The " + myVarBlue + " sky turned " + myVarRed + "!") diff --git a/LM-1201/02-python-primer/hello.py b/LM-1201/02-python-primer/hello.py index 0854f82..6872e12 100644 --- a/LM-1201/02-python-primer/hello.py +++ b/LM-1201/02-python-primer/hello.py @@ -1,4 +1,4 @@ print ("Hello World!") -print ("How are you?") \ No newline at end of file +print ("How are you?") diff --git a/LM-1201/02-python-primer/helloworld.py b/LM-1201/02-python-primer/helloworld.py index ac73623..b8892b6 100644 --- a/LM-1201/02-python-primer/helloworld.py +++ b/LM-1201/02-python-primer/helloworld.py @@ -3,11 +3,11 @@ num = 1 if num < 1: - print ("I'm less than 1!") + print ("I'm less than 1!") elif num ==1: - print("I'm equal to 1.") + print("I'm equal to 1.") else: - print ("Goodbye Cruel World!") + print ("Goodbye Cruel World!") print("I always get printed!") @@ -17,4 +17,4 @@ print("the val is " + str(val)) -new_val="the value is" + str(val) \ No newline at end of file +new_val="the value is" + str(val) diff --git a/LM-1201/02-python-primer/myworldsol.py b/LM-1201/02-python-primer/myworldsol.py index 58dc73e..6c7cde2 100644 --- a/LM-1201/02-python-primer/myworldsol.py +++ b/LM-1201/02-python-primer/myworldsol.py @@ -1,8 +1,8 @@ num = 1 if num < 1: - print ("I'm less than 1!") + print ("I'm less than 1!") elif num > 1: - print ("I'm bigger than 1!") + print ("I'm bigger than 1!") else: - print ("I'm the default statement!") + print ("I'm the default statement!") diff --git a/LM-1201/03-python-primer2/call_functions.py b/LM-1201/03-python-primer2/call_functions.py index 2ade928..f84880d 100644 --- a/LM-1201/03-python-primer2/call_functions.py +++ b/LM-1201/03-python-primer2/call_functions.py @@ -1,24 +1,23 @@ print ("I'm not a function") def my_function(): - print("Hey I'm a function!") - + print("Hey I'm a function!") + def brett(val): - for i in range(val): - print("I'm a function with args!") - + for i in range(val): + print("I'm a function with args!") + def new_func(data): - data2= "my data is " + str(data) - return (data2) + data2= "my data is " + str(data) + return (data2) def calc(num,num2): - var=num * num2 - print(var) - + var=num * num2 + print(var) + my_function() brett(5) my_data=new_func("happy") print(my_data) calc(5,10) - diff --git a/LM-1201/03-python-primer2/call_functions_sol.py b/LM-1201/03-python-primer2/call_functions_sol.py index 3d94858..b053232 100644 --- a/LM-1201/03-python-primer2/call_functions_sol.py +++ b/LM-1201/03-python-primer2/call_functions_sol.py @@ -1,21 +1,21 @@ print ("I'm not a function") def my_function(): - print("Hey I'm a function!") - + print("Hey I'm a function!") + def brett(val): - for i in range(val): - print("I'm a function with args!") - + for i in range(val): + print("I'm a function with args!") + def my_funct(): - print("I'm a new function!") + print("I'm a new function!") def my_funct2(name): - print(name + " wrote this function!") - - + print(name + " wrote this function!") + + my_function() brett(5) my_funct() -my_funct2("Brett") \ No newline at end of file +my_funct2("Brett") diff --git a/LM-1201/03-python-primer2/my_data_types_sol.py b/LM-1201/03-python-primer2/my_data_types_sol.py index 20b6e29..459a27a 100644 --- a/LM-1201/03-python-primer2/my_data_types_sol.py +++ b/LM-1201/03-python-primer2/my_data_types_sol.py @@ -6,4 +6,4 @@ my_dict={"red":1,"green":2} -print(my_dict["green"]) \ No newline at end of file +print(my_dict["green"]) diff --git a/LM-1201/03-python-primer2/nested_datatypes_loops.py b/LM-1201/03-python-primer2/nested_datatypes_loops.py index 75eca50..ece4cf9 100644 --- a/LM-1201/03-python-primer2/nested_datatypes_loops.py +++ b/LM-1201/03-python-primer2/nested_datatypes_loops.py @@ -1,11 +1,11 @@ food={"vegetables":["carrots","kale","cucumber","tomato"],"desserts":["cake","ice cream", "donut"]} for hungry in food["vegetables"]: - print("My favorite vegetable is " + hungry) + print("My favorite vegetable is " + hungry) cars={"sports":{"Volkswagon":"Porsche","Dodge":"Viper","Chevy":"Corvette"},"classic":{"Mercedes-Benz":"300SL","Toyota":"2000GT","Lincoln":"Continental"}} for auto in cars["sports"]: - print("My favorite sports car is a " + cars["sports"][auto]) - + print("My favorite sports car is a " + cars["sports"][auto]) + dessert={"iceCream":["Rocky Road","strawberry","Pistachio Cashew","Pecan Praline"]} diff --git a/LM-1201/03-python-primer2/nested_datatypes_loops_sol.py b/LM-1201/03-python-primer2/nested_datatypes_loops_sol.py index 0d28769..a7f70d1 100644 --- a/LM-1201/03-python-primer2/nested_datatypes_loops_sol.py +++ b/LM-1201/03-python-primer2/nested_datatypes_loops_sol.py @@ -1,19 +1,19 @@ food={"vegetables":["carrots","kale","cucumber","tomato"],"desserts":["cake","ice cream", "donut"]} for hungry in food["vegetables"]: - print("My favorite vegetable is " + hungry) + print("My favorite vegetable is " + hungry) for hungry in food["desserts"]: - print("My favorite dessert is " + hungry) + print("My favorite dessert is " + hungry) cars={"sports":{"Volkswagon":"Porsche","Dodge":"Viper","Chevy":"Corvette"},"classic":{"Mercedes-Benz":"300SL","Toyota":"2000GT","Lincoln":"Continental"}} for auto in cars["sports"]: - print("My favorite sports car is " + cars["sports"][auto]) + print("My favorite sports car is " + cars["sports"][auto]) for auto in cars["classic"]: - print("My favorite classic car is " + cars["classic"][auto]) + print("My favorite classic car is " + cars["classic"][auto]) dessert={"iceCream":["Rocky Road","strawberry","Pistachio Cashew","Pecan Praline"]} for yummy in dessert["iceCream"]: - print("My favorite dessert is " + yummy) + print("My favorite dessert is " + yummy) soup={"soup":{"tomato":"healthy","onion":"bleh!","vegetable":"good for you"}} for tastey in soup["soup"]: - print("This soup is " + soup["soup"][tastey]) + print("This soup is " + soup["soup"][tastey]) diff --git a/LM-1201/03-python-primer2/nested_datatypes_loops_sol2.py b/LM-1201/03-python-primer2/nested_datatypes_loops_sol2.py index e6ef590..6a4ddf8 100644 --- a/LM-1201/03-python-primer2/nested_datatypes_loops_sol2.py +++ b/LM-1201/03-python-primer2/nested_datatypes_loops_sol2.py @@ -1,19 +1,19 @@ food={"vegetables":["carrots","kale","cucumber","tomato"],"desserts":["cake","ice cream", "donut"]} for hungry in food["vegetables"]: - print("My favorite vegetable is " + hungry) + print("My favorite vegetable is " + hungry) for hungry in food["desserts"]: - print("My favorite dessert is " + hungry) + print("My favorite dessert is " + hungry) cars={"sports":{"Volkswagon":"Porsche","Dodge":"Viper","Chevy":"Corvette"},"classic":{"Mercedes-Benz":"300SL","Toyota":"2000GT","Lincoln":"Continental"}} for auto in cars["sports"]: - print("My favorite sports car make and model is the " + auto + " " + cars["sports"][auto]) + print("My favorite sports car make and model is the " + auto + " " + cars["sports"][auto]) for auto in cars["classic"]: - print("My favorite classic car make and model is the " + auto + " " + cars["classic"][auto]) + print("My favorite classic car make and model is the " + auto + " " + cars["classic"][auto]) dessert={"iceCream":["Rocky Road","strawberry","Pistachio Cashew","Pecan Praline"]} for yummy in dessert["iceCream"]: - print("My favorite dessert is " + yummy) + print("My favorite dessert is " + yummy) soup={"soup":{"tomato":"healthy","onion":"bleh!","vegetable":"good for you"}} for tastey in soup["soup"]: - print("This " + tastey + " soup is " + soup["soup"][tastey]) + print("This " + tastey + " soup is " + soup["soup"][tastey]) diff --git a/LM-1201/04-python-json/json_parse_1.py b/LM-1201/04-python-json/json_parse_1.py index 1e330f6..9f38cb8 100644 --- a/LM-1201/04-python-json/json_parse_1.py +++ b/LM-1201/04-python-json/json_parse_1.py @@ -1,19 +1,19 @@ var={"car":"volvo", "fruit":"apple"} print(var["fruit"]) -for f in var: - print("key: " + f + " value: " + var[f]) +for f in var: + print("key: " + f + " value: " + var[f]) print() print() - + var1={"donut":["chocolate","glazed","sprinkled"]} print(var1["donut"][0]) print("My favorite donut flavors are:", end= " ") for f in var1["donut"]: - print(f, end=" ") + print(f, end=" ") print() print() -#Using the examples above write code to print one value of each JSON structure and a loop to print all values. +#Using the examples above write code to print one value of each JSON structure and a loop to print all values. var={"vegetable":"carrot", "fruit":"apple","animal":"cat","day":"Friday"} @@ -21,6 +21,6 @@ myvar={"dessert":"ice cream", "exercise":"push ups","eyes":"blue","gender":"male"} - -myvar1={"dessert":["cake","candy","ice cream","pudding","cookies"]} \ No newline at end of file + +myvar1={"dessert":["cake","candy","ice cream","pudding","cookies"]} diff --git a/LM-1201/04-python-json/json_parse_1_sol.py b/LM-1201/04-python-json/json_parse_1_sol.py index 01fa82f..2756575 100644 --- a/LM-1201/04-python-json/json_parse_1_sol.py +++ b/LM-1201/04-python-json/json_parse_1_sol.py @@ -1,7 +1,7 @@ var={"car":"volvo", "fruit":"apple"} print(var["fruit"]) -for f in var: - print("key: " + f + " value: " + var[f]) +for f in var: + print("key: " + f + " value: " + var[f]) print() print() @@ -9,15 +9,15 @@ print(var1["donut"][0]) print("My favorite donut flavors are:", end= " ") for f in var1["donut"]: - print(f, end=" ") + print(f, end=" ") print() print() -#Using the examples above write code to print one value of each JSON structure and a loop to print all values below. +#Using the examples above write code to print one value of each JSON structure and a loop to print all values below. var={"vegetable":"carrot", "fruit":"apple","animal":"cat","day":"Friday"} print(var["vegetable"]) -for f in var: - print("key: " + f + " value: " + var[f]) +for f in var: + print("key: " + f + " value: " + var[f]) print() print() @@ -25,19 +25,19 @@ print(var1["animal"][0]) print("My favorite animals are:", end= " ") for f in var1["animal"]: - print(f, end=" ") + print(f, end=" ") print() print() myvar={"dessert":"ice cream", "exercise":"push ups","eyes":"blue","gender":"male"} print(myvar["exercise"]) -for f in myvar: - print("key: " + f + " value: " + myvar[f]) +for f in myvar: + print("key: " + f + " value: " + myvar[f]) +print() print() -print() myvar1={"dessert":["cake","candy","ice cream","pudding","cookies"]} print(myvar1["dessert"][0]) print("My favorite desserts are:", end= " ") for f in myvar1["dessert"]: - print(f, end=" ") + print(f, end=" ") diff --git a/LM-1201/04-python-json/json_parse_2.py b/LM-1201/04-python-json/json_parse_2.py index d1f15a4..b16664c 100644 --- a/LM-1201/04-python-json/json_parse_2.py +++ b/LM-1201/04-python-json/json_parse_2.py @@ -2,27 +2,26 @@ print(var["donut"]["flavors"][0]) print("My favorite donut flavors are:", end=" ") for f in var["donut"]["flavors"]: - print(f, end=" ") + print(f, end=" ") print() print() var1={"type":"donut","flavors":{"flavor":[{"type":"chocolate","id":1001}, {"type":"glazed","id":1002},{"type":"sprinkled","id":1003}]}} print("Id: " + str(var1["flavors"]["flavor"][0]["id"]) + " type: " + var1["flavors"]["flavor"][0]["type"]) for f in var1["flavors"]["flavor"]: - print("Id: " + str(f["id"]) + " type: " + f["type"]) + print("Id: " + str(f["id"]) + " type: " + f["type"]) print() print() - - -#Using the examples above write code to print one value of each JSON structure and a loop to print all values. + + +#Using the examples above write code to print one value of each JSON structure and a loop to print all values. myvar={"exercise":{"high impact":["running","jumping","jump rope","running down stairs","skiing"]}} myvar={"foods":{"healthy":["yogurt","nuts","vegetables","fruits","beans"]}} - + myvar1={"author":"Stephen King","famous works":{"novels":[{"title":"The Shining","id":1001}, {"title":"Carrie","id":1002},{"title":"It","id":1003},{"title":"Misery","id":1004},{"title":"Night Shift","id":1005}]}} myvar1={"type":"car","cars":{"sports":[{"make":"Chevrolet", "model":"Corvette", "id":1001},{"make":"Chevrolet", "model":"Camaro", "id":1002},{"make":"Ford", "model":"Mustang", "id":1003},{"make":"Dodge", "model":"Viper", "id":1004},{"make":"Porsche", "model":"911", "id":1005}]}} - diff --git a/LM-1201/04-python-json/json_parse_2_sol.py b/LM-1201/04-python-json/json_parse_2_sol.py index cde1418..55d3362 100644 --- a/LM-1201/04-python-json/json_parse_2_sol.py +++ b/LM-1201/04-python-json/json_parse_2_sol.py @@ -2,23 +2,23 @@ print(var["donut"]["flavors"][0]) print("My favorite donut flavors are:", end=" ") for f in var["donut"]["flavors"]: - print(f, end=" ") + print(f, end=" ") print() print() var1={"type":"donut","flavors":{"flavor":[{"type":"chocolate","id":1001}, {"type":"glazed","id":1002},{"type":"sprinkled","id":1003}]}} print("Id: " + str(var1["flavors"]["flavor"][0]["id"]) + " type: " + var1["flavors"]["flavor"][0]["type"]) for f in var1["flavors"]["flavor"]: - print("Id: " + str(f["id"]) + " type: " + f["type"]) + print("Id: " + str(f["id"]) + " type: " + f["type"]) print() print() - -#Using the examples above write code to print one value of each JSON structure and a loop to print all values. + +#Using the examples above write code to print one value of each JSON structure and a loop to print all values. myvar={"exercise":{"high impact":["running","jumping","jump rope","running down stairs","skiing"]}} print(myvar["exercise"]["high impact"][0]) print("My favorite high impact exercises are:", end=" ") for f in myvar["exercise"]["high impact"]: - print(f, end=" ") + print(f, end=" ") print() print() @@ -26,14 +26,14 @@ print(myvar["foods"]["healthy"][0]) print("My favorite healthy foods are:", end=" ") for f in myvar["foods"]["healthy"]: - print(f, end=" ") + print(f, end=" ") print() print() - + myvar1={"author":"Stephen King","famous works":{"novels":[{"title":"The Shining","id":1001}, {"title":"Carrie","id":1002},{"title":"It","id":1003},{"title":"Misery","id":1004},{"title":"Night Shift","id":1005}]}} print("id: " + str(myvar1["famous works"]["novels"][0]["id"]) + " novel: " + myvar1["famous works"]["novels"][0]["title"]) for f in myvar1["famous works"]["novels"]: - print("Id: " + str(f["id"]) + " novel: " + f["title"]) + print("Id: " + str(f["id"]) + " novel: " + f["title"]) print() print() @@ -41,5 +41,4 @@ myvar1={"type":"car","cars":{"sports":[{"make":"Chevrolet", "model":"Corvette", "id":1001},{"make":"Chevrolet", "model":"Camaro", "id":1002},{"make":"Ford", "model":"Mustang", "id":1003},{"make":"Dodge", "model":"Viper", "id":1004},{"make":"Porsche", "model":"911", "id":1005}]}} print("id: " + str(myvar1["cars"]["sports"][0]["id"]) + " make: " + myvar1["cars"]["sports"][0]["make"] + " model: " + myvar1["cars"]["sports"][0]["model"]) for f in myvar1["cars"]["sports"]: - print("id: " + str(f["id"]) + " make: " + f["make"] + " model: " + f["model"]) - + print("id: " + str(f["id"]) + " make: " + f["make"] + " model: " + f["model"]) diff --git a/LM-1201/04-python-json/json_parse_3.py b/LM-1201/04-python-json/json_parse_3.py index b6a2f28..955c000 100644 --- a/LM-1201/04-python-json/json_parse_3.py +++ b/LM-1201/04-python-json/json_parse_3.py @@ -1,29 +1,29 @@ food={"vegetables":["carrots","kale","cucumber","tomato"]} print(food["vegetables"][1]) for veg in food["vegetables"]: - print(veg) + print(veg) cars={"sports":{"Porsche":"Volkswagon","Viper":"Dodge","Corvette":"Chevy"}} print(cars["sports"]["Corvette"]) for auto in cars["sports"]: - print(auto,cars["sports"][auto]) - + print(auto,cars["sports"][auto]) + dessert={"iceCream":["Rocky-Road","strawberry","Pistachio-Cashew","Pecan-Praline"]} soup={"soup":{"tomato":"healthy","onion":"bleh!","vegetable":"goodForYou"}} ticket={"response": {"serviceTicket": "ST-16891-ugqKRVvCfPJcEaGXnGEN-cas","idleTimeout": 1800,"sessionTimeout": 21600},"version": "1.0"} - + network={"Network":{"router":{"ipaddress":"192.168.1.21","mac_address":"08:56:27:6f:2b:9c"}}} hosts={"response": [{"id": "4c60d6a7-4812-40d6-a337-773af2625e56","hostIp": "65.1.1.86","hostMac": "00:24:d7:43:59:d8","hostType": "wireless"},{"id": "3ef5a7c3-7f74-4e57-a5cb-1448fbda5078","hostIp": "207.1.10.20","hostMac": "5c:f9:dd:52:07:78","hostType": "wired"},{"id": "12f9c920-24fa-4d32-bf39-4c63813aecd8","hostIp": "212.1.10.20","hostMac": "e8:9a:8f:7a:22:99","hostType": "wired"}],"version": "1.0"} for item in hosts["response"]: - print(item["id"]) - print(item["hostIp"]) - print(item["hostMac"]) - print(item["hostType"]) + print(item["id"]) + print(item["hostIp"]) + print(item["hostMac"]) + print(item["hostType"]) devices={"response": [ @@ -32,7 +32,7 @@ "type": "Cisco Catalyst 2960C-8PC-L Switch", "serialNumber": "FOC1637Y3FJ", "role": "CORE", - "reachabilityStatus": "Reachable", + "reachabilityStatus": "Reachable", "instanceUuid": "2dc30cac-072e-4d67-9720-cc302d02695a", "id": "2dc30cac-072e-4d67-9720-cc302d02695a" }, @@ -48,4 +48,4 @@ ], "version": "1.0" } -print(devices["response"][0]["id"]) \ No newline at end of file +print(devices["response"][0]["id"]) diff --git a/LM-1201/04-python-json/json_parse_3_sol.py b/LM-1201/04-python-json/json_parse_3_sol.py index b3b5633..b599b4d 100644 --- a/LM-1201/04-python-json/json_parse_3_sol.py +++ b/LM-1201/04-python-json/json_parse_3_sol.py @@ -12,7 +12,7 @@ ticket={"response": {"serviceTicket": "ST-16891-ugqKRVvCfPJcEaGXnGEN-cas","idleTimeout": 1800,"sessionTimeout": 21600},"version": "1.0"} print(ticket["response"]["serviceTicket"]) - + network={"Network":{"router":{"ipaddress":"192.168.1.21","mac_address":"08:56:27:6f:2b:9c"}}} print(network["Network"]["router"]["ipaddress"]) @@ -26,7 +26,7 @@ "type": "Cisco Catalyst 2960C-8PC-L Switch", "serialNumber": "FOC1637Y3FJ", "role": "CORE", - "reachabilityStatus": "Reachable", + "reachabilityStatus": "Reachable", "instanceUuid": "2dc30cac-072e-4d67-9720-cc302d02695a", "id": "2dc30cac-072e-4d67-9720-cc302d02695a" }, @@ -42,4 +42,4 @@ ], "version": "1.0" } -print(devices["response"][1]["type"]) \ No newline at end of file +print(devices["response"][1]["type"]) diff --git a/LM-1201/04-python-json/json_parse_3_sol2.py b/LM-1201/04-python-json/json_parse_3_sol2.py index 00dc56b..022d56a 100644 --- a/LM-1201/04-python-json/json_parse_3_sol2.py +++ b/LM-1201/04-python-json/json_parse_3_sol2.py @@ -1,44 +1,44 @@ food={"vegetables":["carrots","kale","cucumber","tomato"]} for veg in food["vegetables"]: - print(veg) + print(veg) cars={"sports":{"Porsche":"Volkswagon","Viper":"Dodge","Corvette":"Chevy"}} for auto in cars["sports"]: - print(auto, cars["sports"][auto]) + print(auto, cars["sports"][auto]) dessert={"iceCream":["Rocky-Road","strawberry","Pistachio-Cashew","Pecan-Praline"]} for yummy in dessert["iceCream"]: - print(yummy) + print(yummy) soup={"soup":{"tomato":"healthy","onion":"bleh!","vegetable":"goodForYou"}} for s in soup["soup"]: - print(s, soup["soup"][s]) + print(s, soup["soup"][s]) ticket={"response": {"serviceTicket": "ST-16891-ugqKRVvCfPJcEaGXnGEN-cas","idleTimeout": 1800,"sessionTimeout": 21600},"version": "1.0"} for auth in ticket["response"]: - print(auth, ticket["response"][auth]) - + print(auth, ticket["response"][auth]) + network={"Network":{"router":{"ipaddress":"192.168.1.21","mac_address":"08:56:27:6f:2b:9c"}}} for net in network["Network"]["router"]: - print(net,network["Network"]["router"][net]) + print(net,network["Network"]["router"][net]) hosts={"response": [{"id": "4c60d6a7-4812-40d6-a337-773af2625e56","hostIp": "65.1.1.86","hostMac": "00:24:d7:43:59:d8","hostType": "wireless"},{"id": "3ef5a7c3-7f74-4e57-a5cb-1448fbda5078","hostIp": "207.1.10.20","hostMac": "5c:f9:dd:52:07:78","hostType": "wired"},{"id": "12f9c920-24fa-4d32-bf39-4c63813aecd8","hostIp": "212.1.10.20","hostMac": "e8:9a:8f:7a:22:99","hostType": "wired"}],"version": "1.0"} #Partial looping solution: iterates through response data returning each value. Note that the version key is skipped, so must hard code. for host in hosts["response"]: - for val in host: - print(val,host[val]) + for val in host: + print(val,host[val]) print("version", hosts["version"]) #Full looping solution: iterates through all data returning each value for key in hosts: - if isinstance(hosts[key],list): - for host in hosts[key]: - for val in host: - print(val,host[val]) - else: - print(key,hosts[key]) + if isinstance(hosts[key],list): + for host in hosts[key]: + for val in host: + print(val,host[val]) + else: + print(key,hosts[key]) @@ -48,7 +48,7 @@ "type": "Cisco Catalyst 2960C-8PC-L Switch", "serialNumber": "FOC1637Y3FJ", "role": "CORE", - "reachabilityStatus": "Reachable", + "reachabilityStatus": "Reachable", "instanceUuid": "2dc30cac-072e-4d67-9720-cc302d02695a", "id": "2dc30cac-072e-4d67-9720-cc302d02695a" }, @@ -66,16 +66,15 @@ } #Partial looping solution: iterates through response data returning each value. Note that version key is skipped, so must hard code. for dev in devices["response"]: - for val in dev: - print(val,dev[val]) + for val in dev: + print(val,dev[val]) print("version", devices["version"]) #Full looping solution: iterates through all data returning each value for key in devices: - if isinstance(devices[key],list): - for dev in devices[key]: - for val in dev: - print(val,dev[val]) - else: - print(key,devices[key]) - + if isinstance(devices[key],list): + for dev in devices[key]: + for val in dev: + print(val,dev[val]) + else: + print(key,devices[key]) diff --git a/LM-4201/demo_bot.py b/LM-4201/demo_bot.py index bb7f1f4..67e32f8 100644 --- a/LM-4201/demo_bot.py +++ b/LM-4201/demo_bot.py @@ -16,23 +16,23 @@ from virl import stop_sim # Attempt to import flask module try: - from flask import Flask - from flask import request -# If fails attempt to install the module -except: - try: - if platform.system() == "Windows": - flask_install = subprocess.check_output("pip3 install Flask") - else: - flask_install = subprocess.check_output(["pip3 install Flask"], shell=True) from flask import Flask from flask import request - print("Flask was successfully imported") - except PermissionError as e: - print("You don't have permissions to install flask library.\n" - "Try to run the script with elevated privileges.") - print(e) - exit() +# If fails attempt to install the module +except: + try: + if platform.system() == "Windows": + flask_install = subprocess.check_output("pip3 install Flask") + else: + flask_install = subprocess.check_output(["pip3 install Flask"], shell=True) + from flask import Flask + from flask import request + print("Flask was successfully imported") + except PermissionError as e: + print("You don't have permissions to install flask library.\n" + "Try to run the script with elevated privileges.") + print(e) + exit() @@ -50,9 +50,9 @@ # BOT'S ACCESS TOKEN bearer = "Zjk4Yjk0NWItZDZlMC00ZTJlLWIzZDYtMTA3YzBkMTc5MDBiOGNmNjNkNGQtNDI0" headers = { - "Accept": "application/json", - "Content-Type": "application/json; charset=utf-8", - "Authorization": "Bearer " + bearer + "Accept": "application/json", + "Content-Type": "application/json; charset=utf-8", + "Authorization": "Bearer " + bearer } parser = argparse.ArgumentParser() @@ -60,284 +60,284 @@ args = parser.parse_args() if '@' in args.email: - EMAIL=args.email + EMAIL=args.email else: - exit("Please provide an email address for webhook filtering.\n"\ - "Use '-h' to get help.") + exit("Please provide an email address for webhook filtering.\n"\ + "Use '-h' to get help.") def ngrok(): - if platform.system() == "Windows": - print("Downloading ngrok for Windows OS from website...") - win_ngrok = requests.get( - "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip") - print("Success!") - print("Unzipping ngrok.zip file....") - with open("ngrok.zip", "wb") as f: - f.write(win_ngrok.content) - with zipfile.ZipFile("ngrok.zip", "r") as z: - z.extractall("./") - print("Success!") - return True - elif platform.system() == "Linux": - try: - print("Checking if ngrok is present in current folder...") - check_ngrok = subprocess.check_output( - ["ls -al ./ | grep ngrok"], shell=True).decode("utf-8") - if "x" in check_ngrok: + if platform.system() == "Windows": + print("Downloading ngrok for Windows OS from website...") + win_ngrok = requests.get( + "https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip") print("Success!") + print("Unzipping ngrok.zip file....") + with open("ngrok.zip", "wb") as f: + f.write(win_ngrok.content) + with zipfile.ZipFile("ngrok.zip", "r") as z: + z.extractall("./") + print("Success!") return True - except subprocess.CalledProcessError as e: - print("ngrok was not found.") - print("Downloading ngrok for UNIX OS from website...") - set_ngrok = subprocess.Popen( - ["wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip " \ - "&& unzip ngrok-stable-linux-amd64.zip "], shell=True) - while set_ngrok.poll() is None: - continue - check_ngrok = subprocess.check_output( - ["ls -al ./ | grep ngrok"], shell=True).decode("utf-8") - if "x" in check_ngrok: - print( - "ngrok was successfully downloaded to current folder") - return True - else: - print("Something went wrong!") - return False - else: - print("Checking if ngrok is present in current folder...") - check_ngrok = subprocess.Popen(["ls -al ./ | grep ngrok"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - check_ngrok = check_ngrok.stdout.read().decode("utf-8") - if "x" in check_ngrok: - print("Success!") - return True + elif platform.system() == "Linux": + try: + print("Checking if ngrok is present in current folder...") + check_ngrok = subprocess.check_output( + ["ls -al ./ | grep ngrok"], shell=True).decode("utf-8") + if "x" in check_ngrok: + print("Success!") + return True + except subprocess.CalledProcessError as e: + print("ngrok was not found.") + print("Downloading ngrok for UNIX OS from website...") + set_ngrok = subprocess.Popen( + ["wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip " \ + "&& unzip ngrok-stable-linux-amd64.zip "], shell=True) + while set_ngrok.poll() is None: + continue + check_ngrok = subprocess.check_output( + ["ls -al ./ | grep ngrok"], shell=True).decode("utf-8") + if "x" in check_ngrok: + print( + "ngrok was successfully downloaded to current folder") + return True + else: + print("Something went wrong!") + return False else: - print("ngrok was not found.") - print("Downloading ngrok for MacOS from website...") - set_ngrok = subprocess.Popen( - ["wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip" \ - "&& unzip ngrok-stable-darwin-amd64.zip"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - while set_ngrok.poll() is None: - continue - check_ngrok = subprocess.Popen(["ls -al ./ | grep ngrok"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - check_ngrok = check_ngrok.stdout.read().decode("utf-8") - if "x" in check_ngrok: - print( - "ngrok was successfully downloaded to current folder") - return True - else: - print("Something went wrong!") - return False + print("Checking if ngrok is present in current folder...") + check_ngrok = subprocess.Popen(["ls -al ./ | grep ngrok"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + check_ngrok = check_ngrok.stdout.read().decode("utf-8") + if "x" in check_ngrok: + print("Success!") + return True + else: + print("ngrok was not found.") + print("Downloading ngrok for MacOS from website...") + set_ngrok = subprocess.Popen( + ["wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip" \ + "&& unzip ngrok-stable-darwin-amd64.zip"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + while set_ngrok.poll() is None: + continue + check_ngrok = subprocess.Popen(["ls -al ./ | grep ngrok"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + check_ngrok = check_ngrok.stdout.read().decode("utf-8") + if "x" in check_ngrok: + print( + "ngrok was successfully downloaded to current folder") + return True + else: + print("Something went wrong!") + return False def send_spark_get(url, payload=None, js=True): - if payload == None: - request = requests.get(url, headers=headers) - else: - request = requests.get(url, headers=headers, params=payload) - if js == True: - request = request.json() - return request + if payload == None: + request = requests.get(url, headers=headers) + else: + request = requests.get(url, headers=headers, params=payload) + if js == True: + request = request.json() + return request def send_spark_post(url, data, js=True): - request = requests.post(url, json.dumps(data), headers=headers) - if js: - request = request.json() - return request + request = requests.post(url, json.dumps(data), headers=headers) + if js: + request = request.json() + return request def send_spark_delete(url, js=False): - request = requests.delete(url, headers=headers) - if js != False: - request = request.json() - return request + request = requests.delete(url, headers=headers) + if js != False: + request = request.json() + return request def send_spark_put(url, data, js=False): - request = requests.put(url, data=json.dumps(data), headers=headers) - if js: - request = request.json() - return request + request = requests.put(url, data=json.dumps(data), headers=headers) + if js: + request = request.json() + return request def help_me(): - return "Sure! I can help. Below are the commands that I understand:
" \ - "`Run [attached file]` - I will run attached virl file.
" \ - "`Start [simulation file name]` - I will start specified simulation
" \ - "`Stop [simulation id]` - I will stop simulation with specified ID
" \ - "`List` - I will provide a list of VIRL files present on local HDD
" \ - "`Check VIRL` - I will check VIRL and see if any simulations are running
" + return "Sure! I can help. Below are the commands that I understand:
" \ + "`Run [attached file]` - I will run attached virl file.
" \ + "`Start [simulation file name]` - I will start specified simulation
" \ + "`Stop [simulation id]` - I will stop simulation with specified ID
" \ + "`List` - I will provide a list of VIRL files present on local HDD
" \ + "`Check VIRL` - I will check VIRL and see if any simulations are running
" def greetings(): - return "Hi my name is %s.
" \ - "Type `Help me` to see what I can do.
" % bot_name + return "Hi my name is %s.
" \ + "Type `Help me` to see what I can do.
" % bot_name def handle_text(text, filename=None): - result = None - if text.lower().startswith('hello'): - result = greetings() - if text.lower().startswith('help me'): - result = help_me() - if text.lower().startswith('run') and not filename: - result = "Please don't forget to upload a VIRL file with your `run` command" - elif text.lower().startswith('run') and not filename.endswith(".virl"): - result = "I can't run a non VIRL file. Type `Help Me` to see what I can do" - elif text.lower().startswith('run') and filename.endswith(".virl"): - sim_id = start_sim(filename) - if sim_id[0]: - result = ("Simulation `%s` was successfully started.
"\ - "To access your simulation navigate to [http://198.18.134.1:19400/simulation/guest/%s/](http://198.18.134.1:19400/simulation/guest/%s/) URL
"\ - "Live visualization is accessible via [http://198.18.134.1:19402/?sim_id=%s](http://198.18.134.1:19402/?sim_id=%s) URL" % (sim_id[1],sim_id[1],sim_id[1],sim_id[1],sim_id[1])) - else: - result = ("Something went wrong while I was trying to start the simulation.
" \ - "VIRL returned %s error code.
Also, VIRL provided a reason which is
**%s**" % (response[1], response[2])) - if text.lower().startswith('stop') and len(text) > 5: - response = stop_sim(text.split(" ")[1]) - if response: - result = "The simulation was successfully stopped!" - else: - result = "Something went wrong while I was trying to stop a simulation.\n" \ - "Please make sure provided simulation ID is correct!" - if text.lower().startswith('start') and len(text) > 6: - response = start_sim(text.split(" ")[1]) - if response[0]: - result = ("Simulation `%s` was successfully started.
"\ - "To access your simulation navigate to [http://198.18.134.1:19400/simulation/guest/%s/](http://198.18.134.1:19400/simulation/guest/%s/) URL
"\ - "Live visualization is accessible via [http://198.18.134.1:19402/?sim_id=%s](http://198.18.134.1:19402/?sim_id=%s) URL" % (response[1],response[1],response[1],response[1],response[1])) - else: - result = ("Something went wrong while I was trying to start the simulation.
" \ - "VIRL returned %s error code.
Also, VIRL provided a reason which is
**%s**" % (response[1], response[2])) - if text.lower().startswith('list'): - result = virl_files() - if text.lower().startswith('check virl'): - result = check_virl() - if result == None: - result = "I did not understand your request. Please type `Help me` to see what I can do" - return result + result = None + if text.lower().startswith('hello'): + result = greetings() + if text.lower().startswith('help me'): + result = help_me() + if text.lower().startswith('run') and not filename: + result = "Please don't forget to upload a VIRL file with your `run` command" + elif text.lower().startswith('run') and not filename.endswith(".virl"): + result = "I can't run a non VIRL file. Type `Help Me` to see what I can do" + elif text.lower().startswith('run') and filename.endswith(".virl"): + sim_id = start_sim(filename) + if sim_id[0]: + result = ("Simulation `%s` was successfully started.
"\ + "To access your simulation navigate to [http://198.18.134.1:19400/simulation/guest/%s/](http://198.18.134.1:19400/simulation/guest/%s/) URL
"\ + "Live visualization is accessible via [http://198.18.134.1:19402/?sim_id=%s](http://198.18.134.1:19402/?sim_id=%s) URL" % (sim_id[1],sim_id[1],sim_id[1],sim_id[1],sim_id[1])) + else: + result = ("Something went wrong while I was trying to start the simulation.
" \ + "VIRL returned %s error code.
Also, VIRL provided a reason which is
**%s**" % (response[1], response[2])) + if text.lower().startswith('stop') and len(text) > 5: + response = stop_sim(text.split(" ")[1]) + if response: + result = "The simulation was successfully stopped!" + else: + result = "Something went wrong while I was trying to stop a simulation.\n" \ + "Please make sure provided simulation ID is correct!" + if text.lower().startswith('start') and len(text) > 6: + response = start_sim(text.split(" ")[1]) + if response[0]: + result = ("Simulation `%s` was successfully started.
"\ + "To access your simulation navigate to [http://198.18.134.1:19400/simulation/guest/%s/](http://198.18.134.1:19400/simulation/guest/%s/) URL
"\ + "Live visualization is accessible via [http://198.18.134.1:19402/?sim_id=%s](http://198.18.134.1:19402/?sim_id=%s) URL" % (response[1],response[1],response[1],response[1],response[1])) + else: + result = ("Something went wrong while I was trying to start the simulation.
" \ + "VIRL returned %s error code.
Also, VIRL provided a reason which is
**%s**" % (response[1], response[2])) + if text.lower().startswith('list'): + result = virl_files() + if text.lower().startswith('check virl'): + result = check_virl() + if result == None: + result = "I did not understand your request. Please type `Help me` to see what I can do" + return result def get_files(file_urls, room_id): - for file_url in file_urls: - response = send_spark_get(file_url, js=False) - content_disp = response.headers.get('Content-Disposition', None) - if content_disp is not None: - filename = content_disp.split("filename=")[1].replace('"', '') - if filename.endswith('.virl'): - with open("./sims/" + filename, 'wb') as f: - f.write(response.content) - send_spark_post(URL + "/messages", - {"roomId": room_id, "markdown": ' Received and saved - ' + filename}) - return filename - else: - send_spark_post(URL + "/messages", - {"roomId": room_id, "markdown": '**Sorry but I only accept VIRL files**'}) + for file_url in file_urls: + response = send_spark_get(file_url, js=False) + content_disp = response.headers.get('Content-Disposition', None) + if content_disp is not None: + filename = content_disp.split("filename=")[1].replace('"', '') + if filename.endswith('.virl'): + with open("./sims/" + filename, 'wb') as f: + f.write(response.content) + send_spark_post(URL + "/messages", + {"roomId": room_id, "markdown": ' Received and saved - ' + filename}) + return filename + else: + send_spark_post(URL + "/messages", + {"roomId": room_id, "markdown": '**Sorry but I only accept VIRL files**'}) def webhook(): - url = URL + "/webhooks" - webhooks = {} - resources = ["messages", "memberships"] - webhook_name = "Webhook for demo" - event = "created" - status = None - name = "Webhook Demo" - target_url = "" - - ngrok_url = requests.get( - "http://127.0.0.1:4040/api/tunnels", headers={"Content-Type": "application/json"}).json() - for urls in ngrok_url["tunnels"]: - if "https://" in urls['public_url']: - target_url = urls['public_url'] - - check_webhook = send_spark_get(url, js=False) - if check_webhook.ok: - check_webhook = check_webhook.json() - if len(check_webhook["items"]) > 0: - for items in check_webhook["items"]: - webhooks[items["id"]] = [items["id"], items["resource"], items["filter"]] - if len(webhooks) == 0: - for resource in resources: - payload = {"name": name, "targetUrl": target_url, - "resource": resource, "event": "created", "filter" : "personEmail="+EMAIL} - webhook = send_spark_post(url, payload, js=False) - if webhook.ok: - status = True - print("Webhook was successfully created") - else: - status = False - print( - "Something went wrong. I was unable to create the webhook") - else: - for webhook_id in webhooks: - for item in webhooks[webhook_id]: - if EMAIL in item: - send_spark_delete(url+"/"+webhook_id) - print("Webhook was removed") - for resource in resources: - payload = {"name": name, "targetUrl": target_url, - "resource": resource, "event": "created", "filter" : "personEmail="+EMAIL} - webhook=send_spark_post(url, payload, js=False) - if webhook.ok: - status = True - print("Webhook was successfully created") - return status + url = URL + "/webhooks" + webhooks = {} + resources = ["messages", "memberships"] + webhook_name = "Webhook for demo" + event = "created" + status = None + name = "Webhook Demo" + target_url = "" + + ngrok_url = requests.get( + "http://127.0.0.1:4040/api/tunnels", headers={"Content-Type": "application/json"}).json() + for urls in ngrok_url["tunnels"]: + if "https://" in urls['public_url']: + target_url = urls['public_url'] + + check_webhook = send_spark_get(url, js=False) + if check_webhook.ok: + check_webhook = check_webhook.json() + if len(check_webhook["items"]) > 0: + for items in check_webhook["items"]: + webhooks[items["id"]] = [items["id"], items["resource"], items["filter"]] + if len(webhooks) == 0: + for resource in resources: + payload = {"name": name, "targetUrl": target_url, + "resource": resource, "event": "created", "filter" : "personEmail="+EMAIL} + webhook = send_spark_post(url, payload, js=False) + if webhook.ok: + status = True + print("Webhook was successfully created") + else: + status = False + print( + "Something went wrong. I was unable to create the webhook") + else: + for webhook_id in webhooks: + for item in webhooks[webhook_id]: + if EMAIL in item: + send_spark_delete(url+"/"+webhook_id) + print("Webhook was removed") + for resource in resources: + payload = {"name": name, "targetUrl": target_url, + "resource": resource, "event": "created", "filter" : "personEmail="+EMAIL} + webhook=send_spark_post(url, payload, js=False) + if webhook.ok: + status = True + print("Webhook was successfully created") + return status def virl_files(): - contents = "" - num = 0 - file_name = None - for file in os.listdir("./sims/"): - if file.endswith(".virl"): - num += 1 - contents += str(num) + ". " + str(file) + "
" - if file_name == None: - file_name = file - if num == 0: - return "**No VIRL files are present on local HDD.
" \ - "Use `run` command to upload a file and run it." - return "**Found " + str(num) + " VIRL file(s) on local HDD**.
" + contents + \ - "> **Note:** You can say `start " + file_name + \ - "` and I will start the simulation for you." + contents = "" + num = 0 + file_name = None + for file in os.listdir("./sims/"): + if file.endswith(".virl"): + num += 1 + contents += str(num) + ". " + str(file) + "
" + if file_name == None: + file_name = file + if num == 0: + return "**No VIRL files are present on local HDD.
" \ + "Use `run` command to upload a file and run it." + return "**Found " + str(num) + " VIRL file(s) on local HDD**.
" + contents + \ + "> **Note:** You can say `start " + file_name + \ + "` and I will start the simulation for you." def check_virl(): - # Combine the url and the API call - URL = "http://198.18.134.1:19399/simengine/rest/list" + # Combine the url and the API call + URL = "http://198.18.134.1:19399/simengine/rest/list" - headers = {'content-type': 'text/xml'} + headers = {'content-type': 'text/xml'} - # Make a request call with method get to the VIRL server - response = requests.get( - URL, auth=("guest", "guest"), headers=headers).json() + # Make a request call with method get to the VIRL server + response = requests.get( + URL, auth=("guest", "guest"), headers=headers).json() - # Print how many active simulations were found. - if len(response["simulations"]) == 0: - message = "There are no running simulations on VIRL" + # Print how many active simulations were found. + if len(response["simulations"]) == 0: + message = "There are no running simulations on VIRL" + return message + else: + message = ("**VIRL reports " + + str(len(response["simulations"])) + " active simulation(s).**
") + sim_name = None + # Iterate over the response and print each simulation to the user. + # If user recognizes the simulation return it. + for i, sim in enumerate(response["simulations"]): + if not sim_name: + sim_name = sim + message += str(i+1) + ". "+ sim + "
" + message += "> **Note:** You can say `stop " + sim_name + "` and I will stop the simulation for you." return message - else: - message = ("**VIRL reports " + - str(len(response["simulations"])) + " active simulation(s).**
") - sim_name = None - # Iterate over the response and print each simulation to the user. - # If user recognizes the simulation return it. - for i, sim in enumerate(response["simulations"]): - if not sim_name: - sim_name = sim - message += str(i+1) + ". "+ sim + "
" - message += "> **Note:** You can say `stop " + sim_name + "` and I will stop the simulation for you." - return message app = Flask(__name__) @@ -345,102 +345,102 @@ def check_virl(): @app.route('/', methods=['GET', 'POST']) def spark_webhook(): - if request.method == 'POST': - webhook = request.get_json(silent=True) - resource = webhook['resource'] - senders_email = webhook['data']['personEmail'] - room_id = webhook['data']['roomId'] - - if senders_email != bot_email: - pprint(webhook) - if resource == "memberships" and senders_email == bot_email: - send_spark_post(URL + "/messages", - { - "roomId": room_id, - "markdown": (greetings() + - "**Note This is a group room and you have to call " - "me specifically with `@%s` for me to respond**" % bot_name) - } - ) - - msg = None - filename = None - if senders_email != bot_email: - if "files" in webhook['data']: - filename = get_files(webhook['data']['files'], room_id) - result = send_spark_get( - URL + '/messages/{0}'.format(webhook['data']['id'])) - in_message = result.get('text', '') - print("Received " + in_message + " from spark. Processing...") - try: - in_message = in_message.replace(bot_name.split(" ")[0] + " ", "") - except: - in_message = in_message.replace(bot_name.lower() + " ", '') - if filename != None: - msg = handle_text(in_message, filename=filename) - else: - msg = handle_text(in_message) - if msg != None: - send_spark_post(URL + "/messages", - {"roomId": room_id, "markdown": msg}) - return "true" - elif request.method == 'GET': - message = "
\"Spark" \ - "

Congratulations! Your %s bot is up and running.

" \ - "
Please don't forget to create Webhooks to start receiving events from Cisco Spark!
" % bot_name - return message + if request.method == 'POST': + webhook = request.get_json(silent=True) + resource = webhook['resource'] + senders_email = webhook['data']['personEmail'] + room_id = webhook['data']['roomId'] + + if senders_email != bot_email: + pprint(webhook) + if resource == "memberships" and senders_email == bot_email: + send_spark_post(URL + "/messages", + { + "roomId": room_id, + "markdown": (greetings() + + "**Note This is a group room and you have to call " + "me specifically with `@%s` for me to respond**" % bot_name) + } + ) + + msg = None + filename = None + if senders_email != bot_email: + if "files" in webhook['data']: + filename = get_files(webhook['data']['files'], room_id) + result = send_spark_get( + URL + '/messages/{0}'.format(webhook['data']['id'])) + in_message = result.get('text', '') + print("Received " + in_message + " from spark. Processing...") + try: + in_message = in_message.replace(bot_name.split(" ")[0] + " ", "") + except: + in_message = in_message.replace(bot_name.lower() + " ", '') + if filename != None: + msg = handle_text(in_message, filename=filename) + else: + msg = handle_text(in_message) + if msg != None: + send_spark_post(URL + "/messages", + {"roomId": room_id, "markdown": msg}) + return "true" + elif request.method == 'GET': + message = "
\"Spark" \ + "

Congratulations! Your %s bot is up and running.

" \ + "
Please don't forget to create Webhooks to start receiving events from Cisco Spark!
" % bot_name + return message def main(): - global bot_email, bot_name - if len(bearer) != 0: - test_auth = send_spark_get(URL + "/people/me", js=False) - if test_auth.status_code == 401: - print("Looks like provided access token is not correct. \n" - "Please review it and make sure it belongs to your bot account.\n" - "Do not worry if you have lost the access token. " - "You can always go to https://developer.ciscospark.com/apps.html " - "URL and generate a new access token.") - sys.exit() - if test_auth.status_code == 200: - test_auth = test_auth.json() - bot_name = test_auth.get("displayName", "") - bot_email = test_auth.get("emails", "")[0] - else: - print("'bearer' variable is empty! \n" - "Please populate it with bot's access token and run the script again.\n" - "Do not worry if you have lost the access token. " - "You can always go to https://developer.ciscospark.com/apps.html " - "URL and generate a new access token.") - sys.exit() - - if "@sparkbot.io" not in bot_email: - print("You have provided access token which does not belong to your bot.\n" - "Please review it and make sure it belongs to your bot account.\n" - "Do not worry if you have lost the access token. " - "You can always go to https://developer.ciscospark.com/apps.html " - "URL and generate a new access token.") - sys.exit() - else: - app.run(host='localhost', port=8080) + global bot_email, bot_name + if len(bearer) != 0: + test_auth = send_spark_get(URL + "/people/me", js=False) + if test_auth.status_code == 401: + print("Looks like provided access token is not correct. \n" + "Please review it and make sure it belongs to your bot account.\n" + "Do not worry if you have lost the access token. " + "You can always go to https://developer.ciscospark.com/apps.html " + "URL and generate a new access token.") + sys.exit() + if test_auth.status_code == 200: + test_auth = test_auth.json() + bot_name = test_auth.get("displayName", "") + bot_email = test_auth.get("emails", "")[0] + else: + print("'bearer' variable is empty! \n" + "Please populate it with bot's access token and run the script again.\n" + "Do not worry if you have lost the access token. " + "You can always go to https://developer.ciscospark.com/apps.html " + "URL and generate a new access token.") + sys.exit() + + if "@sparkbot.io" not in bot_email: + print("You have provided access token which does not belong to your bot.\n" + "Please review it and make sure it belongs to your bot account.\n" + "Do not worry if you have lost the access token. " + "You can always go to https://developer.ciscospark.com/apps.html " + "URL and generate a new access token.") + sys.exit() + else: + app.run(host='localhost', port=8080) if __name__ == "__main__": - if ngrok(): - if platform.system() != "Windows": - ngrok_run = subprocess.Popen( - ["./ngrok http 8080"], shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True) - print("Waiting for ngrok to come up ...") - time.sleep(2) - print("Success! Ngrok is up") - if webhook(): - main() - elif platform.system() == "Windows": - ngrok_run = os.popen("ngrok http 8080", mode='r', buffering=-1) - print("Waiting for ngrok to come up ...") - time.sleep(2) - print("Success! Ngrok is up") - if webhook(): - main() \ No newline at end of file + if ngrok(): + if platform.system() != "Windows": + ngrok_run = subprocess.Popen(["./ngrok http 8080"], + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) + print("Waiting for ngrok to come up ...") + time.sleep(2) + print("Success! Ngrok is up") + if webhook(): + main() + elif platform.system() == "Windows": + ngrok_run = os.popen("ngrok http 8080", mode='r', buffering=-1) + print("Waiting for ngrok to come up ...") + time.sleep(2) + print("Success! Ngrok is up") + if webhook(): + main() diff --git a/LM-4402/04-coding-python-json/json-parse-loop-sol.py b/LM-4402/04-coding-python-json/json-parse-loop-sol.py index 38b31b5..8ed9675 100644 --- a/LM-4402/04-coding-python-json/json-parse-loop-sol.py +++ b/LM-4402/04-coding-python-json/json-parse-loop-sol.py @@ -1,5 +1,5 @@ -# Classification Data +# Classification Data cars={"sportsCars":[{"Make":"Volkswagon","Model":"Porsche"},{"Make":"Dodge","Model":"Viper"},{"Make":"Chevy","Model":"Corvette"}]} ### Write loop here to parse and print data @@ -17,7 +17,7 @@ }, { "title": "Room with a View!" - } + } ] } @@ -67,7 +67,7 @@ "id": "Y2lzY29zcGFyazovLVzL1JPT00vZTY2Yzc3ZDAtZTRjNC0xMWU2LWJjNGItNjliMTc1N2J633", "isLocked": "false", "title": "Living Room" - } + } ] } diff --git a/LM-4402/04-coding-python-json/json-parse-loop.py b/LM-4402/04-coding-python-json/json-parse-loop.py index da843f6..f2727f3 100644 --- a/LM-4402/04-coding-python-json/json-parse-loop.py +++ b/LM-4402/04-coding-python-json/json-parse-loop.py @@ -1,5 +1,5 @@ -# Classification Data +# Classification Data cars={"sportsCars":[{"Make":"Volkswagon","Model":"Porsche"},{"Make":"Dodge","Model":"Viper"},{"Make":"Chevy","Model":"Corvette"}]} ### Write loop here to parse and print data @@ -17,12 +17,12 @@ }, { "title": "Room with a View!" - } + } ] } ### Write loop here to parse and print data - + @@ -64,7 +64,7 @@ "id": "Y2lzY29zcGFyazovLVzL1JPT00vZTY2Yzc3ZDAtZTRjNC0xMWU2LWJjNGItNjliMTc1N2J633", "isLocked": "false", "title": "Living Room" - } + } ] } diff --git a/LM-4402/04-coding-python-json/spark-room-loop-sol.py b/LM-4402/04-coding-python-json/spark-room-loop-sol.py index 8219fef..a272e38 100644 --- a/LM-4402/04-coding-python-json/spark-room-loop-sol.py +++ b/LM-4402/04-coding-python-json/spark-room-loop-sol.py @@ -4,28 +4,28 @@ accessToken = "" #put your access token here between the quotes. -def setHeaders(): - accessToken_hdr = 'Bearer ' + accessToken - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} - return spark_header +def setHeaders(): + accessToken_hdr = 'Bearer ' + accessToken + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} + return spark_header -def getRooms(theHeader): - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.get(uri, headers=theHeader) - return resp.json() +def getRooms(theHeader): + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.get(uri, headers=theHeader) + return resp.json() def parseData(theData): - for data in theData["items"]: - for room_info in data: - key = room_info - value = str(data[room_info]) - print(key + ": " + value) - print() - print() + for data in theData["items"]: + for room_info in data: + key = room_info + value = str(data[room_info]) + print(key + ": " + value) + print() + print() header=setHeaders() value=getRooms(header) print ("Spark Response Data:") print (json.dumps(value, indent=4, separators=(',', ': '))) -parseData(value) \ No newline at end of file +parseData(value) diff --git a/LM-4402/04-coding-python-json/spark-room-loop.py b/LM-4402/04-coding-python-json/spark-room-loop.py index 775de00..859bcf1 100644 --- a/LM-4402/04-coding-python-json/spark-room-loop.py +++ b/LM-4402/04-coding-python-json/spark-room-loop.py @@ -4,26 +4,26 @@ accessToken = "" #put your access token here between the quotes. -def setHeaders(): - accessToken_hdr = 'Bearer ' + accessToken - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} - return spark_header +def setHeaders(): + accessToken_hdr = 'Bearer ' + accessToken + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} + return spark_header -def getRooms(theHeader): - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.get(uri, headers=theHeader) - return resp.json() - +def getRooms(theHeader): + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.get(uri, headers=theHeader) + return resp.json() + header=setHeaders() value=getRooms(header) print ("Spark Response Data:") print (json.dumps(value, indent=4, separators=(',', ': '))) -for data in value["items"]: - for room_info in data: - key = room_info - value = str(data[room_info]) - print(key + ": " + value) - print() - print() \ No newline at end of file +for data in value["items"]: + for room_info in data: + key = room_info + value = str(data[room_info]) + print(key + ": " + value) + print() + print() diff --git a/LM-4402/04-coding-python-json/spark-room-sol.py b/LM-4402/04-coding-python-json/spark-room-sol.py index 3e2d813..76ca87a 100644 --- a/LM-4402/04-coding-python-json/spark-room-sol.py +++ b/LM-4402/04-coding-python-json/spark-room-sol.py @@ -4,26 +4,26 @@ accessToken = "" #put your access token here between the quotes. -def setHeaders(): - accessToken_hdr = 'Bearer ' + accessToken - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} - return spark_header +def setHeaders(): + accessToken_hdr = 'Bearer ' + accessToken + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} + return spark_header -def getRooms(theHeader): - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.get(uri, headers=theHeader) - return resp.json() +def getRooms(theHeader): + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.get(uri, headers=theHeader) + return resp.json() def parseData(data): - for val in data["items"]: - print() - print("Room Name: " + val["title"]) - print("Last Active: " + val["lastActivity"]) + for val in data["items"]: + print() + print("Room Name: " + val["title"]) + print("Last Active: " + val["lastActivity"]) header=setHeaders() value=getRooms(header) print ("Spark Response Data:") print (json.dumps(value, indent=4, separators=(',', ': '))) -parseData(value) \ No newline at end of file +parseData(value) diff --git a/LM-4402/04-coding-python-json/spark-room.py b/LM-4402/04-coding-python-json/spark-room.py index 579b586..436c70a 100644 --- a/LM-4402/04-coding-python-json/spark-room.py +++ b/LM-4402/04-coding-python-json/spark-room.py @@ -4,18 +4,18 @@ accessToken = "" #put your access token here between the quotes. -def setHeaders(): - accessToken_hdr = 'Bearer ' + accessToken - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} - return spark_header +def setHeaders(): + accessToken_hdr = 'Bearer ' + accessToken + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} + return spark_header -def getRooms(theHeader): - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.get(uri, headers=theHeader) - return resp.json() - +def getRooms(theHeader): + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.get(uri, headers=theHeader) + return resp.json() + header=setHeaders() value=getRooms(header) -print (json.dumps(value, indent=4, separators=(',', ': '))) \ No newline at end of file +print (json.dumps(value, indent=4, separators=(',', ': '))) diff --git a/LM-4402/04-lab04-learning-python-json/call-functions.py b/LM-4402/04-lab04-learning-python-json/call-functions.py index 5fa865b..3e0d432 100644 --- a/LM-4402/04-lab04-learning-python-json/call-functions.py +++ b/LM-4402/04-lab04-learning-python-json/call-functions.py @@ -1,14 +1,14 @@ print ("I'm not a function") def my_function(): - print("Hey I'm a function!") - + print("Hey I'm a function!") + def brett(val): for i in range(val): print("I'm a function with args!") - - - + + + my_function() -brett(5) \ No newline at end of file +brett(5) diff --git a/LM-4402/04-lab04-learning-python-json/data-type-values.py b/LM-4402/04-lab04-learning-python-json/data-type-values.py index c554cf5..33b6414 100644 --- a/LM-4402/04-lab04-learning-python-json/data-type-values.py +++ b/LM-4402/04-lab04-learning-python-json/data-type-values.py @@ -6,4 +6,4 @@ my_dict={"red":1,"green":2} -print(my_dict["red"]) \ No newline at end of file +print(my_dict["red"]) diff --git a/LM-4402/04-lab04-learning-python-json/hello.py b/LM-4402/04-lab04-learning-python-json/hello.py index 0854f82..6872e12 100644 --- a/LM-4402/04-lab04-learning-python-json/hello.py +++ b/LM-4402/04-lab04-learning-python-json/hello.py @@ -1,4 +1,4 @@ print ("Hello World!") -print ("How are you?") \ No newline at end of file +print ("How are you?") diff --git a/LM-4402/04-lab04-learning-python-json/helloworld.py b/LM-4402/04-lab04-learning-python-json/helloworld.py index 0f854ad..88d7ba1 100644 --- a/LM-4402/04-lab04-learning-python-json/helloworld.py +++ b/LM-4402/04-lab04-learning-python-json/helloworld.py @@ -3,5 +3,5 @@ num = 0 if num < 1: - print ("I'm less than 1!") - print ("Goodbye Cruel World!") + print ("I'm less than 1!") + print ("Goodbye Cruel World!") diff --git a/LM-4402/04-lab04-learning-python-json/json_parse-1.py b/LM-4402/04-lab04-learning-python-json/json_parse-1.py index 3a3773c..f670c6f 100644 --- a/LM-4402/04-lab04-learning-python-json/json_parse-1.py +++ b/LM-4402/04-lab04-learning-python-json/json_parse-1.py @@ -7,7 +7,7 @@ soup={"soup":{"tomato":"healthy","onion":"bleh!","vegetable":"goodForYou"}} ticket={"response": {"serviceTicket": "ST-16891-ugqKRVvCfPJcEaGXnGEN-cas","idleTimeout": 1800,"sessionTimeout": 21600},"version": "1.0"} - + network={"Network":{"router":{"ipaddress":"192.168.1.21","mac_address":"08:56:27:6f:2b:9c"}}} hosts={"response": [{"id": "4c60d6a7-4812-40d6-a337-773af2625e56","hostIp": "65.1.1.86","hostMac": "00:24:d7:43:59:d8","hostType": "wireless"},{"id": "3ef5a7c3-7f74-4e57-a5cb-1448fbda5078","hostIp": "207.1.10.20","hostMac": "5c:f9:dd:52:07:78","hostType": "wired"},{"id": "12f9c920-24fa-4d32-bf39-4c63813aecd8","hostIp": "212.1.10.20","hostMac": "e8:9a:8f:7a:22:99","hostType": "wired"}],"version": "1.0"} @@ -18,7 +18,7 @@ "type": "Cisco Catalyst 2960C-8PC-L Switch", "serialNumber": "FOC1637Y3FJ", "role": "CORE", - "reachabilityStatus": "Reachable", + "reachabilityStatus": "Reachable", "instanceUuid": "2dc30cac-072e-4d67-9720-cc302d02695a", "id": "2dc30cac-072e-4d67-9720-cc302d02695a" }, diff --git a/LM-4402/04-lab04-learning-python-json/json_parse-2.py b/LM-4402/04-lab04-learning-python-json/json_parse-2.py index 7fa83c6..d2aa5fd 100644 --- a/LM-4402/04-lab04-learning-python-json/json_parse-2.py +++ b/LM-4402/04-lab04-learning-python-json/json_parse-2.py @@ -7,8 +7,8 @@ def read_network(network1): #get the attributes for each device. Returns a dictionary for each for attrib in network1["Network"][device]: print("Device attributes are: " + str(attrib)) - #parse the attributes for each device - for val in attrib: + #parse the attributes for each device + for val in attrib: print ("Device attribute values are: " + val + " " + attrib[val]) print() #add extra line for separation @@ -18,8 +18,3 @@ def read_network(network1): #Assignment: network2={"Network":{"routers":[{"ipaddress":"192.168.1.21","mac_address":"08:56:27:6f:2b:9c"}],"switches":[{"ipaddress":"192.168.32.1","mac_address":"3a:24:37:4f:5b:1d"}],"hosts":[{"ipaddress":"192.168.32.5","mac_address":"3b:25:31:4a:5c:3f"},{"ipaddress":"192.168.32.8","mac_address":"4b:15:32:43:51:3c"}]}} - - - - - diff --git a/LM-4402/04-lab04-learning-python-json/loops.py b/LM-4402/04-lab04-learning-python-json/loops.py index 851ea27..312a4bb 100644 --- a/LM-4402/04-lab04-learning-python-json/loops.py +++ b/LM-4402/04-lab04-learning-python-json/loops.py @@ -2,21 +2,21 @@ print() for i in range(5): - print (str(i) + " I'm alive!") + print (str(i) + " I'm alive!") print() - + basket=["apple","peach","pear","cherry"] for fruit in basket: - print (fruit) -print() + print (fruit) +print() my_color={"red":1,"blue":2,"green":3} for color in my_color: - print (color + " %d" % my_color[color]); + print (color + " %d" % my_color[color]); print() - + name = "Brett" if name == "Brett": - print ("Brett who?") -else: - print ("Nice name!") + print ("Brett who?") +else: + print ("Nice name!") diff --git a/LM-4402/04-lab04-learning-python-json/loops_ex.py b/LM-4402/04-lab04-learning-python-json/loops_ex.py index 75c5ea3..6f3cd58 100644 --- a/LM-4402/04-lab04-learning-python-json/loops_ex.py +++ b/LM-4402/04-lab04-learning-python-json/loops_ex.py @@ -8,7 +8,7 @@ #Parse JSON with loops for hungry in donut["flavors"]["flavor"]: - print(hungry["id"] + " " + hungry["type"]) + print(hungry["id"] + " " + hungry["type"]) print() @@ -21,4 +21,4 @@ #Parse JSON with loops for auto in cars["sports"]: - print(auto + " " + cars["sports"][auto]) + print(auto + " " + cars["sports"][auto]) diff --git a/LM-4402/04-lab04-learning-python-json/spark-messages.py b/LM-4402/04-lab04-learning-python-json/spark-messages.py index 288768d..f96ca2c 100644 --- a/LM-4402/04-lab04-learning-python-json/spark-messages.py +++ b/LM-4402/04-lab04-learning-python-json/spark-messages.py @@ -6,35 +6,35 @@ MESSAGE = "" #put your message between the quotes. -def setHeaders(): - accessToken_hdr = 'Bearer ' + ACCESS_TOKEN - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} - return spark_header +def setHeaders(): + accessToken_hdr = 'Bearer ' + ACCESS_TOKEN + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} + return spark_header -def getRooms(theHeader): - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.get(uri, headers=theHeader) - return resp.json() +def getRooms(theHeader): + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.get(uri, headers=theHeader) + return resp.json() def findRoom(roomList,name): - roomId=0 - for room in roomList["items"]: - if room["title"] == name: - roomId=room["id"] - break - return roomId - -def getRoomMessages(theHeader,roomID): - uri = 'https://api.ciscospark.com/v1/messages?roomId=' + roomID - resp = requests.get(uri, headers=theHeader) - return resp.json() - + roomId=0 + for room in roomList["items"]: + if room["title"] == name: + roomId=room["id"] + break + return roomId + +def getRoomMessages(theHeader,roomID): + uri = 'https://api.ciscospark.com/v1/messages?roomId=' + roomID + resp = requests.get(uri, headers=theHeader) + return resp.json() + def addMessageToRoom(theHeader,roomID,message): - uri = "https://api.ciscospark.com/v1/messages" - payload= {"roomId":roomID,"text":message} - resp = requests.post(uri, data=json.dumps(payload), headers=theHeader) - return resp.json() + uri = "https://api.ciscospark.com/v1/messages" + payload= {"roomId":roomID,"text":message} + resp = requests.post(uri, data=json.dumps(payload), headers=theHeader) + return resp.json() header=setHeaders() @@ -43,14 +43,14 @@ def addMessageToRoom(theHeader,roomID,message): print (json.dumps(rooms, indent=4, separators=(',', ': '))) roomID=findRoom(rooms,ROOM_NAME) if roomID != 0: - msgList=getRoomMessages(header,roomID) - print() - print("Messages in " + ROOM_NAME) - print (json.dumps(msgList, indent=4, separators=(',', ': '))) - resp=addMessageToRoom(header,roomID,MESSAGE) - print(resp) - msgList=getRoomMessages(header,roomID) - print("Messages in " + ROOM_NAME) - print (json.dumps(msgList, indent=4, separators=(',', ': '))) + msgList=getRoomMessages(header,roomID) + print() + print("Messages in " + ROOM_NAME) + print (json.dumps(msgList, indent=4, separators=(',', ': '))) + resp=addMessageToRoom(header,roomID,MESSAGE) + print(resp) + msgList=getRoomMessages(header,roomID) + print("Messages in " + ROOM_NAME) + print (json.dumps(msgList, indent=4, separators=(',', ': '))) else: - print("Specified room was not found!") + print("Specified room was not found!") diff --git a/LM-4402/04-lab04-learning-python-json/spark-room-easy.py b/LM-4402/04-lab04-learning-python-json/spark-room-easy.py index 4369c52..7baa400 100644 --- a/LM-4402/04-lab04-learning-python-json/spark-room-easy.py +++ b/LM-4402/04-lab04-learning-python-json/spark-room-easy.py @@ -8,10 +8,9 @@ spark_header = {'Authorization': accessToken_hdr} uri = 'https://api.ciscospark.com/v1/rooms' resp = requests.get(uri, headers=spark_header) -print("Spark Rooms you belong to: ") +print("Spark Rooms you belong to: ") print(resp.text) print() print("Spark Rooms in easier to read format - pretty format:") print (json.dumps(resp.json(), indent=4, separators=(',', ': '))) - diff --git a/LM-4402/04-lab04-learning-python-json/spark-room-out.py b/LM-4402/04-lab04-learning-python-json/spark-room-out.py index 0b3cfbc..91935b1 100644 --- a/LM-4402/04-lab04-learning-python-json/spark-room-out.py +++ b/LM-4402/04-lab04-learning-python-json/spark-room-out.py @@ -1,6 +1,6 @@ rooms={ - "items": [ + "items": [ { "id": "Y2lzY29zcGFyazovL300vNDM5YmNiZTAtNTI5NC0xMWU2LWExMTEtMTdlMWMwMDI4ZmIy", "type": "group", @@ -9,7 +9,7 @@ "teamId": "Y2lzY29zcGFyazovvNDZlMmFjZDAtMjBlYy0xMWU2LTg5NTItNWJkZTQwMjVmZDVm", "title": "GSX Mini Hacks", "lastActivity": "2016-08-09T19:02:45.199Z" - }, + }, { "id": "Y2lzY29zcGFyazovL00vYzNjOTU1NDAtNDc3Yi0xMWU2LWEwYmYtYTc2NTNjNWQwZTMw", "type": "group", @@ -17,7 +17,7 @@ "isLocked": False, "title": "CLUS16 - Learning Labs", "lastActivity": "2016-07-14T21:52:24.432Z" - }, + }, { "id": "Y2lzY29zcGFyazovL3VzL1JPTvNzAxNjQ0YjAtMjFkZi0xMWU2LWJhMjgtNjU2ZWJlYjhjNjY5", "type": "group", diff --git a/LM-4402/04-lab04-learning-python-json/spark-room.py b/LM-4402/04-lab04-learning-python-json/spark-room.py index b141ea5..0cafc7b 100644 --- a/LM-4402/04-lab04-learning-python-json/spark-room.py +++ b/LM-4402/04-lab04-learning-python-json/spark-room.py @@ -4,18 +4,18 @@ accessToken = "" #put your access token here between the quotes. -def setHeaders(): - accessToken_hdr = 'Bearer ' + accessToken - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} - return spark_header +def setHeaders(): + accessToken_hdr = 'Bearer ' + accessToken + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} + return spark_header -def getRooms(theHeader): - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.get(uri, headers=theHeader) - print("SparkAPI: ") - return resp.json() - +def getRooms(theHeader): + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.get(uri, headers=theHeader) + print("SparkAPI: ") + return resp.json() + header=setHeaders() value=getRooms(header) diff --git a/LM-4402/05-mission/spark_mission.py b/LM-4402/05-mission/spark_mission.py index 802f523..8503560 100644 --- a/LM-4402/05-mission/spark_mission.py +++ b/LM-4402/05-mission/spark_mission.py @@ -3,87 +3,87 @@ import requests #MISSION: FILL IN THE REQUESTED DETAILS -ACCESS_TOKEN = None #Replace None with your access token. Shroud with quotes. -ROOM_NAME = None #Replace None with the name of the room to be created. Shroud with quotes. -YOUR_MESSAGE = None #Replace None with the message that you will post to the room. Shroud with quotes. +ACCESS_TOKEN = None #Replace None with your access token. Shroud with quotes. +ROOM_NAME = None #Replace None with the name of the room to be created. Shroud with quotes. +YOUR_MESSAGE = None #Replace None with the message that you will post to the room. Shroud with quotes. #sets the header to be used for authentication and data format to be sent. -def setHeaders(): - accessToken_hdr = 'Bearer ' + ACCESS_TOKEN - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} - return (spark_header) +def setHeaders(): + accessToken_hdr = 'Bearer ' + ACCESS_TOKEN + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json; charset=utf-8'} + return (spark_header) #check if spark room already exists. If so return the room id def findRoom(the_header,room_name): - roomId=None - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.get(uri, headers=the_header) - resp = resp.json() - for room in resp["items"]: - if room["title"] == room_name: - print() - print("findRoom JSON: ", room) - print("MISSION: findRoom: REPLACE None WITH CODE THAT PARSES JSON TO ASSIGN ROOM ID VALUE TO VARIABLE roomId") - roomId=None - break - return(roomId) - + roomId=None + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.get(uri, headers=the_header) + resp = resp.json() + for room in resp["items"]: + if room["title"] == room_name: + print() + print("findRoom JSON: ", room) + print("MISSION: findRoom: REPLACE None WITH CODE THAT PARSES JSON TO ASSIGN ROOM ID VALUE TO VARIABLE roomId") + roomId=None + break + return(roomId) + # checks if room already exists and if true returns that room ID. If not creates a new room and returns the room id. def createRoom(the_header,room_name): - roomId=findRoom(the_header,room_name) - if roomId==None: - roomInfo = {"title":room_name} - uri = 'https://api.ciscospark.com/v1/rooms' - resp = requests.post(uri, json=roomInfo, headers=the_header) - var = resp.json() - print() - print("createRoom JSON: ", var) - print("MISSION: createRoom: REPLACE None WITH CODE THAT PARSES JSON TO ASSIGN ROOM ID VALUE TO VARIABLE roomId.") - roomId=None - return(roomId) - + roomId=findRoom(the_header,room_name) + if roomId==None: + roomInfo = {"title":room_name} + uri = 'https://api.ciscospark.com/v1/rooms' + resp = requests.post(uri, json=roomInfo, headers=the_header) + var = resp.json() + print() + print("createRoom JSON: ", var) + print("MISSION: createRoom: REPLACE None WITH CODE THAT PARSES JSON TO ASSIGN ROOM ID VALUE TO VARIABLE roomId.") + roomId=None + return(roomId) + # adds a new member to the room. Member e-mail is test@test.com def addMembers(the_header,roomId): - member = {"roomId":roomId,"personEmail": "test@test.com", "isModerator": False} - uri = 'https://api.ciscospark.com/v1/memberships' - resp = requests.post(uri, json=member, headers=the_header) - print() - print("addMembers JSON: ", resp.json()) + member = {"roomId":roomId,"personEmail": "test@test.com", "isModerator": False} + uri = 'https://api.ciscospark.com/v1/memberships' + resp = requests.post(uri, json=member, headers=the_header) + print() + print("addMembers JSON: ", resp.json()) #posts a message to the room def postMsg(the_header,roomId,message): - message = {"roomId":roomId,"text":message} - uri = 'https://api.ciscospark.com/v1/messages' - resp = requests.post(uri, json=message, headers=the_header) - print() - print("postMsg JSON: ", resp.json()) + message = {"roomId":roomId,"text":message} + uri = 'https://api.ciscospark.com/v1/messages' + resp = requests.post(uri, json=message, headers=the_header) + print() + print("postMsg JSON: ", resp.json()) #MISSION: WRITE CODE TO RETRIEVE AND DISPLAY DETAILS ABOUT THE ROOM. def getRoomInfo(the_header,roomId): - print("In function getRoomInfo") - #MISSION: Replace None in the uri variable with the Spark REST API call - uri = None - if uri == None: - sys.exit("Please add the uri call to get room details. See the Spark API Ref Guide") - resp = requests.get(uri, headers=the_header) - print("Room Info: ",resp.text) - resp = resp.json() - print("MISSION: Add code to parse and display details about the room.") - + print("In function getRoomInfo") + #MISSION: Replace None in the uri variable with the Spark REST API call + uri = None + if uri == None: + sys.exit("Please add the uri call to get room details. See the Spark API Ref Guide") + resp = requests.get(uri, headers=the_header) + print("Room Info: ",resp.text) + resp = resp.json() + print("MISSION: Add code to parse and display details about the room.") + if __name__ == '__main__': - if ACCESS_TOKEN==None or ROOM_NAME==None or YOUR_MESSAGE==None: - sys.exit("Please check that variables ACCESS_TOKEN, ROOM_NAME and YOUR_MESSAGE have values assigned.") - header=setHeaders() - #passing the ROOM_NAME for the room to be created - room_id=createRoom(header,ROOM_NAME) - if room_id == None: - sys.exit("Please check that functions findRoom and createRoom return the room ID value.") - #passing roomId to members function here to add member to the room. - addMembers(header,room_id) - #passing roomId to message function here to Post Message to a room. - postMsg(header,room_id,YOUR_MESSAGE) - print() - print("MISSION: ADD FUNCTION CALL getRoomInfo(header,room_id)") + if ACCESS_TOKEN==None or ROOM_NAME==None or YOUR_MESSAGE==None: + sys.exit("Please check that variables ACCESS_TOKEN, ROOM_NAME and YOUR_MESSAGE have values assigned.") + header=setHeaders() + #passing the ROOM_NAME for the room to be created + room_id=createRoom(header,ROOM_NAME) + if room_id == None: + sys.exit("Please check that functions findRoom and createRoom return the room ID value.") + #passing roomId to members function here to add member to the room. + addMembers(header,room_id) + #passing roomId to message function here to Post Message to a room. + postMsg(header,room_id,YOUR_MESSAGE) + print() + print("MISSION: ADD FUNCTION CALL getRoomInfo(header,room_id)") diff --git a/LM-4502/03-python/apic_em_code_2.py b/LM-4502/03-python/apic_em_code_2.py index 420c992..1884cdd 100644 --- a/LM-4502/03-python/apic_em_code_2.py +++ b/LM-4502/03-python/apic_em_code_2.py @@ -69,24 +69,28 @@ def get_config(token, url, id): response.raise_for_status() response = response.json() - #Find the hostname in the response body and save it to a hostname variable + #Find the hostname in the response body and save it to a hostname variable hostname = re.findall('hostname\s(.+?)\s', response['response'])[0] - #Create a date_time variable which will hold current time + #Create a date_time variable which will hold current time date_time = datetime.datetime.now() - #Create a variable which will hold the hostname combined with the date and time + #Create a variable which will hold the hostname combined with the date and time #The format will be hostname_year_month_day_hour.minute.second - file_name = hostname + '_' + str(date_time.year) + '_' + str(date_time.month) + '_' + \ - str(date_time.day) + '_' + str(date_time.hour) + '.' + str(date_time.minute) + \ - '.' + str(date_time.second) + file_name = (hostname + '_' + + str(date_time.year) + '_' + + str(date_time.month) + '_' + + str(date_time.day) + '_' + + str(date_time.hour) + '.' + + str(date_time.minute) + '.' + + str(date_time.second)) file = open(file_name+'.txt', 'w') - #Write response body to the file + #Write response body to the file file.write(response['response']) - #Close the file when writing is complete + #Close the file when writing is complete file.close() diff --git a/LM-4602/create_subinterface.py b/LM-4602/create_subinterface.py index 955d65f..fc16629 100644 --- a/LM-4602/create_subinterface.py +++ b/LM-4602/create_subinterface.py @@ -19,7 +19,7 @@ BASE = 'GigabitEthernet3' -def create_vlan(host, port, user, password, interface, +def create_vlan(host, port, user, password, interface, vlan, ip, ssl, insecure): """ Function to create a subinterface on CSR1000V. diff --git a/LM-4702/07-lab03-api/start_sim.py b/LM-4702/07-lab03-api/start_sim.py index 6ca5b72..b0269bd 100644 --- a/LM-4702/07-lab03-api/start_sim.py +++ b/LM-4702/07-lab03-api/start_sim.py @@ -5,7 +5,7 @@ virl_url = "http://198.18.134.1:19399/" api_call = "/simengine/rest/launch" -virl_url += api_call +virl_url += api_call # Username and password username = "guest" @@ -28,4 +28,4 @@ print("Simulation started successfully") print("Your simulation's name is " + response.text) else: - print("Simulation not started. Status ",response.status_code) + print("Simulation not started. Status ",response.status_code) diff --git a/LM-4702/07-lab03-api/stop_a_node.py b/LM-4702/07-lab03-api/stop_a_node.py index 61eb0e6..d61d6e5 100644 --- a/LM-4702/07-lab03-api/stop_a_node.py +++ b/LM-4702/07-lab03-api/stop_a_node.py @@ -53,9 +53,9 @@ def nodes_in_sim(url, username, password, sim): # Print how many active nodes are in the simulations and choose a number of nodes to be stopped. num_nodes = int(input("\n\nVIRL reports " + str(len(response[sim])) + - " active nodes in the simulation. \n" + - "How many would you like to stop? [1-" + str(len(response[sim])) + - "] ")) + " active nodes in the simulation. \n" + + "How many would you like to stop? [1-" + str(len(response[sim])) + + "] ")) # Create an empty dictionary which will contain all nodes information all_nodes = {} @@ -73,7 +73,7 @@ def nodes_in_sim(url, username, password, sim): # While num_nodes does not equal to zero run below code while num_nodes != 0: user_input = input("\n\n\nEnter the name of the node that you would like to shutdown. \n" + - "Please choose a node in ACTIVE state: ") + "Please choose a node in ACTIVE state: ") if user_input in all_nodes.values(): nodes.append(user_input) num_nodes -= 1 diff --git a/LM-4702/07-lab04-mission/captureme.py b/LM-4702/07-lab04-mission/captureme.py index a2492c8..bae84e0 100644 --- a/LM-4702/07-lab04-mission/captureme.py +++ b/LM-4702/07-lab04-mission/captureme.py @@ -317,4 +317,3 @@ def main(): # true run main() function if __name__ == '__main__': main() - diff --git a/LM-4802/03-mission/human_interaction_mission.py b/LM-4802/03-mission/human_interaction_mission.py index 82c950f..88a099f 100644 --- a/LM-4802/03-mission/human_interaction_mission.py +++ b/LM-4802/03-mission/human_interaction_mission.py @@ -15,10 +15,10 @@ #MISSION: fill in the variables below. -TROPO_APP_NAME = "" # Your Tropo network application name. Enter a different name if you named it something else. -TROPO_USER = "" # Enter your Tropo user name -TROPO_PASS = "" # Enter your Tropo password -YOUR_NAME = "" # Enter your name +TROPO_APP_NAME = "" # Your Tropo network application name. Enter a different name if you named it something else. +TROPO_USER = "" # Enter your Tropo user name +TROPO_PASS = "" # Enter your Tropo password +YOUR_NAME = "" # Enter your name SPARK_TOKEN = "" # Enter your Spark token SPARK_ROOM = "" # Enter the Spark room name that you are a member of to which you will post a message @@ -26,93 +26,93 @@ # Function to retrieve Tropo application ID. def get_tropo_app_id(tropo_api,app_name, tropo_user, tropo_pass): - app_id=None - # Content type must be included in the header - header = {"content-type": "application/json"} - api_call= "/applications" - url= tropo_api + api_call - response = requests.get(url,auth=(tropo_user,tropo_pass),headers=header,verify=False) - if(response): - resp=response.json() - for app in resp: - if(app["name"]==app_name): - app_id=app["id"] - break - if(app_id == None): - print("The Tropo application with name " + app_name + " was not found!") - else: - print("No Tropo application returned for user. Please check that the Tropo user and password are correct, and the user has applications.") - return app_id - - + app_id=None + # Content type must be included in the header + header = {"content-type": "application/json"} + api_call= "/applications" + url= tropo_api + api_call + response = requests.get(url,auth=(tropo_user,tropo_pass),headers=header,verify=False) + if(response): + resp=response.json() + for app in resp: + if(app["name"]==app_name): + app_id=app["id"] + break + if(app_id == None): + print("The Tropo application with name " + app_name + " was not found!") + else: + print("No Tropo application returned for user. Please check that the Tropo user and password are correct, and the user has applications.") + return app_id + + # Function to retrieve Tropo application's phone number. def get_tropo_phone_number(tropo_api, tropo_app_id, tropo_user, tropo_pass): - phone_num=None - # Content type must be included in the header - header = {"content-type": "application/json"} - # Create the URI string for our Tropo application - url = "{api}{address}{app}{addr}".format(api=tropo_api, - address="/applications/", - app=tropo_app_id, - addr="/addresses") - response = requests.get(url,auth=(tropo_user,tropo_pass),headers=header,verify=False) - if(response): - resp=response.json() - for data in resp: - # Retrieve the value for "displayNumber" when "type" is "number" - if (data["type"] == "number"): - phone_num = data["displayNumber"] - break - - if(phone_num == None): - print("The phone number for application id " + tropo_app_id + " was not found.") - - return phone_num + phone_num=None + # Content type must be included in the header + header = {"content-type": "application/json"} + # Create the URI string for our Tropo application + url = "{api}{address}{app}{addr}".format(api=tropo_api, + address="/applications/", + app=tropo_app_id, + addr="/addresses") + response = requests.get(url,auth=(tropo_user,tropo_pass),headers=header,verify=False) + if(response): + resp=response.json() + for data in resp: + # Retrieve the value for "displayNumber" when "type" is "number" + if (data["type"] == "number"): + phone_num = data["displayNumber"] + break + + if(phone_num == None): + print("The phone number for application id " + tropo_app_id + " was not found.") + + return phone_num # Function to get the ID of the Spark room def get_spark_room_id(token,room_name): - room_id=None - accessToken_hdr = 'Bearer ' + token - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json'} - uri = 'https://api.ciscospark.com/v1/rooms' - response = requests.get(uri,headers=spark_header) - resp = response.json() - for room in resp["items"]: - if(room["title"] == room_name): - room_id=room["id"] - break; - if(room_id==None): - print("Could not find Spark room " + room_name) - - return (room_id) + room_id=None + accessToken_hdr = 'Bearer ' + token + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json'} + uri = 'https://api.ciscospark.com/v1/rooms' + response = requests.get(uri,headers=spark_header) + resp = response.json() + for room in resp["items"]: + if(room["title"] == room_name): + room_id=room["id"] + break; + if(room_id==None): + print("Could not find Spark room " + room_name) + + return (room_id) # Function to send a Spark message to a Spark Room def send_spark_message(token,roomId,message): - accessToken_hdr = 'Bearer ' + token - spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json'} - message = '{"roomId":"' + roomId + '","text":"'+message+'"}' - uri = 'https://api.ciscospark.com/v1/messages' - resp = requests.post(uri, data=message, headers=spark_header) - if(resp.status_code!= STATUS_OK): - print("Failed to send message to roomId: {room_id} ".format(room_id=roomId)) - + accessToken_hdr = 'Bearer ' + token + spark_header = {'Authorization': accessToken_hdr, 'Content-Type': 'application/json'} + message = '{"roomId":"' + roomId + '","text":"'+message+'"}' + uri = 'https://api.ciscospark.com/v1/messages' + resp = requests.post(uri, data=message, headers=spark_header) + if(resp.status_code!= STATUS_OK): + print("Failed to send message to roomId: {room_id} ".format(room_id=roomId)) + #Main engine function -def main(): - app_id=get_tropo_app_id(TROPO_API,TROPO_APP_NAME,TROPO_USER,TROPO_PASS) - if(app_id != None): - phone_num = get_tropo_phone_number(TROPO_API,app_id,TROPO_USER,TROPO_PASS) - if(phone_num != None): - room_id = get_spark_room_id(SPARK_TOKEN,SPARK_ROOM) - if(room_id != None): - send_spark_message(SPARK_TOKEN,room_id,"Hi! This is {name}. I just finished my first Tropo application!".format(name=YOUR_NAME)) - send_spark_message(SPARK_TOKEN,room_id,"Dial this number to try it out: {num}.".format(num=phone_num)) - else: - print("The Spark Room " + SPARK_ROOM + " was not found!") - - if(app_id!=None and phone_num != None and room_id != None): - print('Awesome! Check the Spark room "' + SPARK_ROOM + '" for your message.') +def main(): + app_id=get_tropo_app_id(TROPO_API,TROPO_APP_NAME,TROPO_USER,TROPO_PASS) + if(app_id != None): + phone_num = get_tropo_phone_number(TROPO_API,app_id,TROPO_USER,TROPO_PASS) + if(phone_num != None): + room_id = get_spark_room_id(SPARK_TOKEN,SPARK_ROOM) + if(room_id != None): + send_spark_message(SPARK_TOKEN,room_id,"Hi! This is {name}. I just finished my first Tropo application!".format(name=YOUR_NAME)) + send_spark_message(SPARK_TOKEN,room_id,"Dial this number to try it out: {num}.".format(num=phone_num)) + else: + print("The Spark Room " + SPARK_ROOM + " was not found!") + + if(app_id!=None and phone_num != None and room_id != None): + print('Awesome! Check the Spark room "' + SPARK_ROOM + '" for your message.') if __name__ == '__main__': - sys.exit(main()) + sys.exit(main()) diff --git a/LM-4901/active_macs.py b/LM-4901/active_macs.py index c851bdf..07dfea4 100644 --- a/LM-4901/active_macs.py +++ b/LM-4901/active_macs.py @@ -5,25 +5,24 @@ import base64 def main(): - try: - username = 'learning' - password = 'learning' - restURL = 'https://cmxlocationsandbox.cisco.com/api/location/v2/clients?sortBy=macAddress:ASC' - request = requests.get( - url = restURL, - auth = HTTPBasicAuth(username,password), - verify=False) + try: + username = 'learning' + password = 'learning' + restURL = 'https://cmxlocationsandbox.cisco.com/api/location/v2/clients?sortBy=macAddress:ASC' + request = requests.get(url = restURL, + auth = HTTPBasicAuth(username,password), + verify=False) - macValues=[] - jdata = json.loads(request.text) - for d in jdata: - for key, value in d.items(): - if key == "macAddress": - macValues.append(value) + macValues=[] + jdata = json.loads(request.text) + for d in jdata: + for key, value in d.items(): + if key == "macAddress": + macValues.append(value) - print (macValues) + print (macValues) - except requests.exceptions.RequestException as e: - print(e) + except requests.exceptions.RequestException as e: + print(e) if __name__ == "__main__": main() diff --git a/LM-4901/clientcount.py b/LM-4901/clientcount.py index 2df0630..56211d2 100644 --- a/LM-4901/clientcount.py +++ b/LM-4901/clientcount.py @@ -6,21 +6,20 @@ import time def main(): - try: - username = 'learning' - password = 'learning' - restURL = 'https://cmxlocationsandbox.cisco.com/api/location/v2/clients/count' - request = requests.get( - url = restURL, - auth = HTTPBasicAuth(username,password), - verify=False) + try: + username = 'learning' + password = 'learning' + restURL = 'https://cmxlocationsandbox.cisco.com/api/location/v2/clients/count' + request = requests.get(url = restURL, + auth = HTTPBasicAuth(username,password), + verify=False) - str_request = request.json() - clientcount = str_request['count'] + str_request = request.json() + clientcount = str_request['count'] - print (clientcount) + print (clientcount) - except requests.exceptions.RequestException as e: - print(e) + except requests.exceptions.RequestException as e: + print(e) if __name__ == "__main__": main() diff --git a/LM-4901/mac_history.py b/LM-4901/mac_history.py index 41d3804..ca90f8d 100644 --- a/LM-4901/mac_history.py +++ b/LM-4901/mac_history.py @@ -7,63 +7,62 @@ import time def main(): - print("********************************************************"); - print("* Cisco CMX MAC History Python 3 Utility *"); - print("* Please provide the input in the following format *"); - print("* *"); - print("* macAddress: 00:00:2a:01:00:06 *"); - print("* *"); - print("* Control C to exit *"); - print("********************************************************"); + print("********************************************************"); + print("* Cisco CMX MAC History Python 3 Utility *"); + print("* Please provide the input in the following format *"); + print("* *"); + print("* macAddress: 00:00:2a:01:00:06 *"); + print("* *"); + print("* Control C to exit *"); + print("********************************************************"); - username = 'learning' - password = 'learning' - restURL1 = 'https://cmxlocationsandbox.cisco.com/api/location/v1/historylite/clients/' + username = 'learning' + password = 'learning' + restURL1 = 'https://cmxlocationsandbox.cisco.com/api/location/v1/historylite/clients/' - x = None - y = None - chgOn = None - flr = None - macAddress = None + x = None + y = None + chgOn = None + flr = None + macAddress = None - macAddress = input("macAddress: ") - try: - response = requests.get( - url = restURL1 +"/"+ macAddress, - auth = HTTPBasicAuth(username,password), - verify=False) + macAddress = input("macAddress: ") + try: + response = requests.get(url = restURL1 +"/"+ macAddress, + auth = HTTPBasicAuth(username,password), + verify=False) - json_data = response.json() + json_data = response.json() - ActCount = json_data["Count"] #actual count could be thousands, ie. 3000 - count = 0 - l = [] - while (count < 10): + ActCount = json_data["Count"] #actual count could be thousands, ie. 3000 + count = 0 + l = [] + while (count < 10): - macAddress= json_data["Macaddress"] - x = json_data["Data"][count]["x"] - y = json_data["Data"][count]["y"] - chgOn = json_data["Data"][count]["chgOn"] - timestamp = time.ctime(int(chgOn)/1000) - flr = json_data["Data"][count]["flr"] + macAddress= json_data["Macaddress"] + x = json_data["Data"][count]["x"] + y = json_data["Data"][count]["y"] + chgOn = json_data["Data"][count]["chgOn"] + timestamp = time.ctime(int(chgOn)/1000) + flr = json_data["Data"][count]["flr"] - s = [timestamp, str(x), str(y), str(flr)] - l.append(s) + s = [timestamp, str(x), str(y), str(flr)] + l.append(s) - count = count + 1 + count = count + 1 - print("----------------------------------------------------------------") - print(" Actual Count: ", ActCount, " (only showing 10 events)") - print(" Macaddress: ", macAddress) - print(" List contains timestamp, xCoordinates, yCoordinates , FloorId") - print("----------------------------------------------------------------") - for s in l: - print(list(s)) + print("----------------------------------------------------------------") + print(" Actual Count: ", ActCount, " (only showing 10 events)") + print(" Macaddress: ", macAddress) + print(" List contains timestamp, xCoordinates, yCoordinates , FloorId") + print("----------------------------------------------------------------") + for s in l: + print(list(s)) - except requests.exceptions.RequestException as e: - print(e) + except requests.exceptions.RequestException as e: + print(e) if __name__ == '__main__': @@ -74,18 +73,18 @@ def main(): https:///api/location/v1/historylite/clients/00:00:2a:01:00:06 { - "Data": [ - { - "x": 209.99107, - "y": 38.91461, - "flr": "723413320329068590", - "chgOn": "1492780699608", - "s": "1", - "ssid": "test", - "ap": "00:2b:01:00:02:00", - "un": "", - "ip": "10.10.20.165", - "lat": -999, - "long": -999 - }, + "Data": [ + { + "x": 209.99107, + "y": 38.91461, + "flr": "723413320329068590", + "chgOn": "1492780699608", + "s": "1", + "ssid": "test", + "ap": "00:2b:01:00:02:00", + "un": "", + "ip": "10.10.20.165", + "lat": -999, + "long": -999 + }, ''' diff --git a/LM-4901/mac_info.py b/LM-4901/mac_info.py index 88cd6aa..8a024f5 100644 --- a/LM-4901/mac_info.py +++ b/LM-4901/mac_info.py @@ -7,57 +7,55 @@ import time def main(): - print("********************************************************"); - print("* Cisco CMX MAC Info Python 3 Utility *"); - print("* Please provide the input in the following format *"); - print("* *"); - print("* macAddress: 00:00:2a:01:00:06 *"); - print("* *"); - print("* Control C to exit *"); - print("********************************************************"); - - username = 'learning' - password = 'learning' - restURL1 = 'https://cmxlocationsandbox.cisco.com/api/location/v1/historylite/clients/' - restURL2 = 'https://cmxlocationsandbox.cisco.com/api/location/v1/compliance/clientcompliance/floor/' - - while True: - - x = None - y = None - chgOn = None - hierarchy = None - macAddress = None - - macAddress = input("macAddress: ") - - try: - response = requests.get( - url = restURL1 +"/"+ macAddress, - auth = HTTPBasicAuth(username,password), - verify=False) - - json_data = response.json() - - x = json_data["Data"][0]["x"] - y = json_data["Data"][0]["y"] - chgOn = json_data["Data"][0]["chgOn"] - timestamp = time.ctime(int(chgOn)/1000) - - response = requests.get( - url = restURL2 +"/"+ macAddress, - auth = HTTPBasicAuth(username,password), - verify=False) - - except requests.exceptions.RequestException as e: - print(e) - - print("----------------------------------------------------------------") - print("x, y coordinates: ", x , ", " , y) - print("timestamp (lastLocatedTime): "+ timestamp) - print("map hierarchy string: ", response.text) - print("----------------------------------------------------------------") - print("\nControl C to Exit"); + print("********************************************************"); + print("* Cisco CMX MAC Info Python 3 Utility *"); + print("* Please provide the input in the following format *"); + print("* *"); + print("* macAddress: 00:00:2a:01:00:06 *"); + print("* *"); + print("* Control C to exit *"); + print("********************************************************"); + + username = 'learning' + password = 'learning' + restURL1 = 'https://cmxlocationsandbox.cisco.com/api/location/v1/historylite/clients/' + restURL2 = 'https://cmxlocationsandbox.cisco.com/api/location/v1/compliance/clientcompliance/floor/' + + while True: + + x = None + y = None + chgOn = None + hierarchy = None + macAddress = None + + macAddress = input("macAddress: ") + + try: + response = requests.get(url = restURL1 +"/"+ macAddress, + auth = HTTPBasicAuth(username,password), + verify=False) + + json_data = response.json() + + x = json_data["Data"][0]["x"] + y = json_data["Data"][0]["y"] + chgOn = json_data["Data"][0]["chgOn"] + timestamp = time.ctime(int(chgOn)/1000) + + response = requests.get(url = restURL2 +"/"+ macAddress, + auth = HTTPBasicAuth(username,password), + verify=False) + + except requests.exceptions.RequestException as e: + print(e) + + print("----------------------------------------------------------------") + print("x, y coordinates: ", x , ", " , y) + print("timestamp (lastLocatedTime): "+ timestamp) + print("map hierarchy string: ", response.text) + print("----------------------------------------------------------------") + print("\nControl C to Exit"); if __name__ == '__main__': main() @@ -69,20 +67,20 @@ def main(): https:///api/location/v1/historylite/clients/00:00:2a:01:00:06 { - "Data": [ - { - "x": 209.99107, - "y": 38.91461, - "flr": "723413320329068590", - "chgOn": "1492780699608", - "s": "1", - "ssid": "test", - "ap": "00:2b:01:00:02:00", - "un": "", - "ip": "10.10.20.165", - "lat": -999, - "long": -999 - }, + "Data": [ + { + "x": 209.99107, + "y": 38.91461, + "flr": "723413320329068590", + "chgOn": "1492780699608", + "s": "1", + "ssid": "test", + "ap": "00:2b:01:00:02:00", + "un": "", + "ip": "10.10.20.165", + "lat": -999, + "long": -999 + }, ''' ''' diff --git a/LM-4901/sampleRESTcode.py b/LM-4901/sampleRESTcode.py index 7655fa2..807f329 100644 --- a/LM-4901/sampleRESTcode.py +++ b/LM-4901/sampleRESTcode.py @@ -5,48 +5,47 @@ import base64 def main(): - print("*********************************************************************************"); - print("* Cisco CMX Command Line REST API Python 3 Utility *"); - print("* Please provide the input in the following format *"); - print("* *"); - print("* REST URL: https://cmxlocationsandbox.cisco.com/api/location/v2/clients/count *"); - print("* Username: learning *"); - print("* Password: learning *"); - print("* *"); - print("* *"); - print("* Control C to exit *"); - print("*********************************************************************************"); - - storedCredentials = False - username = None - password = None - - while True: - restURL = input("\nREST URL: ") - - if not storedCredentials: - username = input("Username: ") - password = input("Password: ") - storedCredentials = True - - print("----------------------------------") - print(repr(restURL)) - print("Authentication string: "+ username+":"+password) - print("----------------------------------") - - try: - request = requests.get( - url = restURL, - auth = HTTPBasicAuth(username,password), - verify=False) - - parsed = request.json - print(json.dumps(parsed(), indent=2)) - - except requests.exceptions.RequestException as e: - print(e) - - print("\nControl C to Exit"); + print("*********************************************************************************"); + print("* Cisco CMX Command Line REST API Python 3 Utility *"); + print("* Please provide the input in the following format *"); + print("* *"); + print("* REST URL: https://cmxlocationsandbox.cisco.com/api/location/v2/clients/count *"); + print("* Username: learning *"); + print("* Password: learning *"); + print("* *"); + print("* *"); + print("* Control C to exit *"); + print("*********************************************************************************"); + + storedCredentials = False + username = None + password = None + + while True: + restURL = input("\nREST URL: ") + + if not storedCredentials: + username = input("Username: ") + password = input("Password: ") + storedCredentials = True + + print("----------------------------------") + print(repr(restURL)) + print("Authentication string: "+ username+":"+password) + print("----------------------------------") + + try: + request = requests.get(url = restURL, + auth = HTTPBasicAuth(username,password), + verify=False) + + parsed = request.json + print(json.dumps(parsed(), indent=2)) + + except requests.exceptions.RequestException as e: + print(e) + + print("\nControl C to Exit"); if __name__ == "__main__": - main() + main() diff --git a/NWPLab/apic-em-1.1-device-count-to-spark-sample.py b/NWPLab/apic-em-1.1-device-count-to-spark-sample.py index 72e11ce..96d5944 100755 --- a/NWPLab/apic-em-1.1-device-count-to-spark-sample.py +++ b/NWPLab/apic-em-1.1-device-count-to-spark-sample.py @@ -24,14 +24,14 @@ # # TECHNICAL ASSISTANCE CENTER (TAC) SUPPORT IS NOT AVAILABLE FOR THIS SCRIPT. # -# Always check for the latest Version of this script via http://cs.co/NWPLab +# Always check for the latest Version of this script via http://cs.co/NWPLab # ############################################################################ -# -# This sample script illustrates how to -# 1) query the number of network devices from the APIC-EM network information +# +# This sample script illustrates how to +# 1) query the number of network devices from the APIC-EM network information # base via the APIC-EM REST APIs and # 2) post the result into Spark using a predefined function in _LabEnv -# +# # ############################################################################ import _LabEnv from pprint import pprint @@ -39,9 +39,9 @@ import requests # Disable Certificate warning try: - requests.packages.urllib3.disable_warnings() + requests.packages.urllib3.disable_warnings() except: - pass + pass # ############################################################################ # Start API Session diff --git a/NWPLab/apic-em-1.1-path-trace-sample.py b/NWPLab/apic-em-1.1-path-trace-sample.py index dbcf0b2..6f5a1a7 100755 --- a/NWPLab/apic-em-1.1-path-trace-sample.py +++ b/NWPLab/apic-em-1.1-path-trace-sample.py @@ -24,14 +24,14 @@ # # TECHNICAL ASSISTANCE CENTER (TAC) SUPPORT IS NOT AVAILABLE FOR THIS SCRIPT. # -# Always check for the latest Version of this script via http://cs.co/NWPLab +# Always check for the latest Version of this script via http://cs.co/NWPLab # ############################################################################ -# +# # This sample script illustrates how to run a Path Trace in APIC-EM via it's # REST APIs. This includes # 1) posting a path trace request # 2) querying and parsing the resulting path trace JSON document -# +# # ############################################################################ import _LabEnv from pprint import pprint @@ -42,9 +42,9 @@ import requests # Disable Certificate warning try: - requests.packages.urllib3.disable_warnings() + requests.packages.urllib3.disable_warnings() except: - pass + pass ############################################################################## # Variables below @@ -102,7 +102,7 @@ print('Parsed JSON Response - subset Python Dict object: ') my_nodes_on_path = my_parsed_response['response']['networkElementsInfo'] -pprint(my_nodes_on_path, depth=2) +pprint(my_nodes_on_path, depth=2) ############################################################################## # EOF diff --git a/NWPLab/apic-em-1.1-path-trace-to-spark-sample.py b/NWPLab/apic-em-1.1-path-trace-to-spark-sample.py index ddd05ab..b6e4702 100755 --- a/NWPLab/apic-em-1.1-path-trace-to-spark-sample.py +++ b/NWPLab/apic-em-1.1-path-trace-to-spark-sample.py @@ -24,15 +24,15 @@ # # TECHNICAL ASSISTANCE CENTER (TAC) SUPPORT IS NOT AVAILABLE FOR THIS SCRIPT. # -# Always check for the latest Version of this script via http://cs.co/NWPLab +# Always check for the latest Version of this script via http://cs.co/NWPLab # ############################################################################ -# +# # This sample script illustrates how to run a Path Trace in APIC-EM via it's # REST APIs. This includes # 1) posting a path trace request # 2) querying and parsing the resulting path trace JSON document # 3) extracting host names and posting them into Spark -# +# # ############################################################################ import _LabEnv from pprint import pprint @@ -43,9 +43,9 @@ import requests # Disable Certificate warning try: - requests.packages.urllib3.disable_warnings() + requests.packages.urllib3.disable_warnings() except: - pass + pass ############################################################################## # Variables below @@ -102,8 +102,8 @@ my_nodes = [] for p in my_nodes_on_path: - my_nodes.append( p.get('name', '.') ) - my_nodes.append( " " ) + my_nodes.append( p.get('name', '.') ) + my_nodes.append( " " ) my_path = ''.join(my_nodes) print('Hostnames on the path from %s to %s are: \n %s' % (PATH_SOURCE_IP, PATH_DEST_IP, my_path) ) diff --git a/NWPLab/restconf-to-spark.py b/NWPLab/restconf-to-spark.py index d899887..0053c90 100755 --- a/NWPLab/restconf-to-spark.py +++ b/NWPLab/restconf-to-spark.py @@ -24,13 +24,13 @@ # # TECHNICAL ASSISTANCE CENTER (TAC) SUPPORT IS NOT AVAILABLE FOR THIS SCRIPT. # -# Always check for the latest Version of this script via http://cs.co/NWPLab +# Always check for the latest Version of this script via http://cs.co/NWPLab # ############################################################################ -# -# This sample script illustrates how to query operational data from a router -# via the RESTCONF API and then post the results into an existing Spark room +# +# This sample script illustrates how to query operational data from a router +# via the RESTCONF API and then post the results into an existing Spark room # via the Spark REST APIs. -# +# # Initial Version by Joe Clarke - thanks Joe! # ############################################################################ import _LabEnv @@ -61,7 +61,7 @@ if in_octets == -1 or out_octets == -1: print("Failed to find statistics for interface " + INTF) sys.exit(1) - + # ############################################################################ # Post to Spark Room # ############################################################################ @@ -71,4 +71,4 @@ # ############################################################################ # EOF -# ############################################################################ \ No newline at end of file +# ############################################################################ diff --git a/NWPLab/spark-post-full.py b/NWPLab/spark-post-full.py index 3da450f..c1c69e3 100755 --- a/NWPLab/spark-post-full.py +++ b/NWPLab/spark-post-full.py @@ -24,11 +24,11 @@ # # TECHNICAL ASSISTANCE CENTER (TAC) SUPPORT IS NOT AVAILABLE FOR THIS SCRIPT. # -# Always check for the latest Version of this script via http://cs.co/NWPLab +# Always check for the latest Version of this script via http://cs.co/NWPLab # ############################################################################ -# -# This script illustrates how to find a spark room by name and post a message -# +# +# This script illustrates how to find a spark room by name and post a message +# # ############################################################################ import _LabEnv import json @@ -47,14 +47,14 @@ j = json.loads(r.text) for tmproom in j['items']: - if tmproom['title'] == _LabEnv.SPARK_ROOM_NAME: - SPARK_ROOM_ID = tmproom['id'] - print("Found room ID for '" + _LabEnv.SPARK_ROOM_NAME + "' : " + SPARK_ROOM_ID) - break - + if tmproom['title'] == _LabEnv.SPARK_ROOM_NAME: + SPARK_ROOM_ID = tmproom['id'] + print("Found room ID for '" + _LabEnv.SPARK_ROOM_NAME + "' : " + SPARK_ROOM_ID) + break + if SPARK_ROOM_ID is None: - print("Failed to find room ID for '" + _LabEnv.SPARK_ROOM_NAME + "'") - sys.exit(1) + print("Failed to find room ID for '" + _LabEnv.SPARK_ROOM_NAME + "'") + sys.exit(1) # ############################################################################ # Post to Spark Room diff --git a/NWPLab/spark-post-simple.py b/NWPLab/spark-post-simple.py index d66912e..776dce0 100755 --- a/NWPLab/spark-post-simple.py +++ b/NWPLab/spark-post-simple.py @@ -24,11 +24,11 @@ # # TECHNICAL ASSISTANCE CENTER (TAC) SUPPORT IS NOT AVAILABLE FOR THIS SCRIPT. # -# Always check for the latest Version of this script via http://cs.co/NWPLab +# Always check for the latest Version of this script via http://cs.co/NWPLab # ############################################################################ -# -# This is a simple script leveraging _LabEnv to post into a Spark Room -# +# +# This is a simple script leveraging _LabEnv to post into a Spark Room +# # ############################################################################ import _LabEnv import json