From e9e9ceba5fcf2b88010d02f28a9cb56ecff24ae3 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 12 Feb 2020 18:11:24 +0700 Subject: [PATCH 01/44] Create controller.py --- controller.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 controller.py diff --git a/controller.py b/controller.py new file mode 100644 index 0000000..47fb2ca --- /dev/null +++ b/controller.py @@ -0,0 +1,4 @@ +APICEM_IP = "10.215.26.9" #Địa chỉ IP của APIC-EM +USERNAME ="vnpro" # Tên đăng nhập trong APIC-EM +PASSWORD ="VnPro123" # Mật khẩu của tài khoản APIC-EM +VERSION = "v1" # Phiên bản APIC-EM version 1 From 3eb1f2d1a57eed0e0f5ddc657911c2394fecaea3 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 12 Feb 2020 18:12:02 +0700 Subject: [PATCH 02/44] Create pgpd.py --- pgpd.py | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 pgpd.py diff --git a/pgpd.py b/pgpd.py new file mode 100644 index 0000000..70e67c0 --- /dev/null +++ b/pgpd.py @@ -0,0 +1,80 @@ +import requests +import json + +import controller # Lấy các thông tin về controller + +#Tắt tin nhắn cảnh báo; +requests.packages.urllib3.disable_warnings() +'''Tạo hàm để lấy token; +các tham số ip,ver,uname,pword được gắn giá trị đã khai báo ở trên''' +def get_auth_token(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD): +#Tạo 1 jsonObject có 2 key username,password có value tương ứng là uname,pword + r_json = { + "username": uname, + "password": pword + } + post_url = "https://"+ip+"/api/"+ver+"/ticket" #khai báo URL để post + headers = {"Content-Type" : "application/json"} #khai báo headers +#try:...except: nghĩa là nếu code xảy ra lỗi ở trong phần try thì thực hiện phần except + try: + r=requests.post(post_url,data = json.dumps(r_json),headers = headers,verify=False) #gửi requests đến server và gán response vào biến r + #post là tạo dữ liệu ,post_url là địa chỉ ta muốn gửi đến, + #json.dumps dùng để mã hóa username và password, + #verify=False để không xác thực SSL + r.raise_for_status() # Lấy mã trạng thái, 200 là thành công, 404 là not found + token = r.json()["response"]["serviceTicket"] #Lấy ticket từ r + # Trả về giá trị + return { + "token" : token + } + except: + print("Status: %s" %r.status_code) + print("Response: %s" %r.text) + +ticket=get_auth_token() +print(ticket) + +# Tạo hàm get để lấy thông tin +def get(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): + ticket = get_auth_token(ip,ver,uname,pword) #Lấy ticket bằng cách gọi hàm + headers = {"X-Auth-Token": ticket['token']} #Khai báo headers để gắn ticket vào + url = "https://"+ip+"/api/"+ver+"/"+api + print("\nExecuting GET '%s'\n"%url) #In ra thông tin để người dùng biết đang lấy dữ liệu + try: + #gửi request đến server, resp là lời đáp lại của yêu cầu, get là lấy dữ liệu + resp = requests.get(url,headers=headers,params=params,verify=False) + print("GET '%s' status" %api,resp.status_code,'\n') #In ra trạng thái + return(resp) + except: + print("Something wrong",api) + sys.exit() + +# Tạo hàm put chỉnh sửa thông tin +def put(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): + ticket = get_auth_token(ip,ver,uname,pword) + headers = {"X-Auth-Token": ticket['token']} + url = "https://"+ip+"/api/"+ver+"/"+api + print("\nExecuting PUT '%s'\n"%url) + try: + resp = requests.put(url,headers=headers,params=params,verify=False) + print("PUT '%s' status" %api,resp.status_code,'\n') + return(resp) + except: + print("Something wrong",api) + sys.exit() + +def delete(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): + + ticket = get_auth_token(ip,ver,uname,pword) + headers = {"content-type" : "application/json","X-Auth-Token": ticket['token']} + url = "https://"+ip+"/api/"+ver+"/"+api + print ("\nExecuting DELETE '%s'\n"%url) + try: + # The request and response of "DELETE" request + resp= requests.delete(url,headers=headers,params=params,verify = False) + print ("DELETE '%s' Status: "%api,resp.status_code,'\n') # This is the http request status + return(resp) + except: + print ("Something wrong with DELETE /",api) + sys.exit() + From 53a33bb0cc24bf34dc77a7a24b48673e10b57d4b Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 12 Feb 2020 18:12:56 +0700 Subject: [PATCH 03/44] Create get_network_device.py --- get_network_device.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 get_network_device.py diff --git a/get_network_device.py b/get_network_device.py new file mode 100644 index 0000000..3baea29 --- /dev/null +++ b/get_network_device.py @@ -0,0 +1,39 @@ +import requests #Gửi các loại yêu cầu http đến server và nhận response +import json #Là định dạng dữ liệu để truyền và nhận dữ liệu với server +import sys # Để tương tác với hệ thống +from tabulate import tabulate #cung cấp các format bảng + +import pgpd #Lấy các phương thức như get_auth_token, get +def network_device_list(): + device =[] + try: + resp = pgpd.get(api="network-device") # Lấy thông tin về network-device + status = resp.status_code #Lấy trạng thái của yêu cầu trên + response_json = resp.json() #Lấy nội dung json đã mã hóa từ lời đáp lại + device = response_json["response"] #Gán thông tin từ lời đáp lại vào device + except: + print("Something wrong,cannot get network device info") + sys.exit() + # Nếu status khác 200(nghĩa là không thành công) thì in lời đáp lại và thoát chương trình + if status !=200: + print (resp.text) + sys.exit() + # Nếu chuỗi trống thi in ra không có thiết bị được tìm thấy và thoát chương trình + if device == []: + print("No network device found") + sys.exit() + + device_list =[] + i=0 + #Tạo một vòng lặp để dò từng item và thực hiện gán các giá trị vào device_list + #item["hostname"] là dò tìm key hostname trong item và lấy ra value + for item in device: + i+=1 + device_list.append([i,item["hostname"],item["managementIpAddress"], + item["type"],item["instanceUuid"],item["id"]]) + #thư viện tabulate dùng để khi in dữ liệu ra theo format đã được xây dựng sẵn + return (device_list) + +result = network_device_list() +print(tabulate(result, + headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) From 2f1e59176d5dffda7a6ab461d9fe177f5cd8747b Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 12 Feb 2020 18:17:16 +0700 Subject: [PATCH 04/44] Update controller.py --- controller.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller.py b/controller.py index 47fb2ca..a5a6994 100644 --- a/controller.py +++ b/controller.py @@ -1,4 +1,4 @@ APICEM_IP = "10.215.26.9" #Địa chỉ IP của APIC-EM USERNAME ="vnpro" # Tên đăng nhập trong APIC-EM -PASSWORD ="VnPro123" # Mật khẩu của tài khoản APIC-EM +PASSWORD ="Vnpro123" # Mật khẩu của tài khoản APIC-EM VERSION = "v1" # Phiên bản APIC-EM version 1 From 08bbe94c2cfcb745fef428c3b3214259a2eb48c3 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Mon, 17 Feb 2020 11:18:43 +0700 Subject: [PATCH 05/44] Update get_network_device.py --- get_network_device.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/get_network_device.py b/get_network_device.py index 3baea29..727b09b 100644 --- a/get_network_device.py +++ b/get_network_device.py @@ -34,6 +34,20 @@ def network_device_list(): #thư viện tabulate dùng để khi in dữ liệu ra theo format đã được xây dựng sẵn return (device_list) +def get_device_id(): + inputString= input("Nhap so thu tu cua thiet bi can xoa:") + number=0 + device =[] + resp = pgpd.get(api="network-device") + response_json = resp.json() + device = response_json["response"] + for item in device: + number +=1 + if number==int(inputString): + id_selete= item["id"] + return id_selete +""" result = network_device_list() print(tabulate(result, headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) +""" From 98cddddf4bbaf1fa02b816115e45cfc242235725 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Mon, 17 Feb 2020 11:22:10 +0700 Subject: [PATCH 06/44] Update get_network_device.py --- get_network_device.py | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/get_network_device.py b/get_network_device.py index 727b09b..3baea29 100644 --- a/get_network_device.py +++ b/get_network_device.py @@ -34,20 +34,6 @@ def network_device_list(): #thư viện tabulate dùng để khi in dữ liệu ra theo format đã được xây dựng sẵn return (device_list) -def get_device_id(): - inputString= input("Nhap so thu tu cua thiet bi can xoa:") - number=0 - device =[] - resp = pgpd.get(api="network-device") - response_json = resp.json() - device = response_json["response"] - for item in device: - number +=1 - if number==int(inputString): - id_selete= item["id"] - return id_selete -""" result = network_device_list() print(tabulate(result, headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) -""" From 973b851a1bc2cf449703775019452e0e6b4a4912 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Mon, 17 Feb 2020 11:23:07 +0700 Subject: [PATCH 07/44] Create delete_device.py --- delete_device.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 delete_device.py diff --git a/delete_device.py b/delete_device.py new file mode 100644 index 0000000..839c95c --- /dev/null +++ b/delete_device.py @@ -0,0 +1,39 @@ +import requests +import json +import sys +from tabulate import tabulate + +import pgpd +import get_network_device + +#Lay danh sach cac thiet bi +result = get_network_device.network_device_list() +print(tabulate(result, + headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) +##################################### +def get_device_id(): + inputString= input("Nhap so thu tu cua thiet bi can xoa:") + number=0 + device =[] + resp = pgpd.get(api="network-device") + response_json = resp.json() + device = response_json["response"] + for item in device: + number +=1 + if number==int(inputString): + id_selete= item["id"] + return id_selete +#Xoa thiet bi +def delete_device(): + id=get_device_id() + try: + resp = pgpd.delete(api="network-device/"+id) + status = resp.status_code + response_json = resp.json() + r = response_json["response"] + print(r) + except: + print("Something wrong") + sys.exit() + +result2 = delete_device() From cad4617949ac229acdd38bdd451092afe1489bc8 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Mon, 17 Feb 2020 11:38:22 +0700 Subject: [PATCH 08/44] Update delete_device.py --- delete_device.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/delete_device.py b/delete_device.py index 839c95c..bae2c78 100644 --- a/delete_device.py +++ b/delete_device.py @@ -6,11 +6,6 @@ import pgpd import get_network_device -#Lay danh sach cac thiet bi -result = get_network_device.network_device_list() -print(tabulate(result, - headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) -##################################### def get_device_id(): inputString= input("Nhap so thu tu cua thiet bi can xoa:") number=0 @@ -35,5 +30,8 @@ def delete_device(): except: print("Something wrong") sys.exit() - +#Lay danh sach cac thiet bi +result = get_network_device.network_device_list() +print(tabulate(result, + headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) result2 = delete_device() From 7dd722c8856005709739552553b7dc55b55f8a3c Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Mon, 17 Feb 2020 11:39:50 +0700 Subject: [PATCH 09/44] Update delete_device.py --- delete_device.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/delete_device.py b/delete_device.py index bae2c78..7f74045 100644 --- a/delete_device.py +++ b/delete_device.py @@ -7,8 +7,8 @@ import get_network_device def get_device_id(): - inputString= input("Nhap so thu tu cua thiet bi can xoa:") - number=0 + inputString = input("Nhap so thu tu cua thiet bi can xoa:") + number =0 device =[] resp = pgpd.get(api="network-device") response_json = resp.json() @@ -16,11 +16,11 @@ def get_device_id(): for item in device: number +=1 if number==int(inputString): - id_selete= item["id"] + id_selete = item["id"] return id_selete #Xoa thiet bi def delete_device(): - id=get_device_id() + id = get_device_id() try: resp = pgpd.delete(api="network-device/"+id) status = resp.status_code From bb7cad56debeb43fdc1912baf20808b34c8e73f5 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 09:52:05 +0700 Subject: [PATCH 10/44] Update delete_device.py --- delete_device.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/delete_device.py b/delete_device.py index 7f74045..b05cce7 100644 --- a/delete_device.py +++ b/delete_device.py @@ -6,18 +6,20 @@ import pgpd import get_network_device +#Lay so id cua thiet bi def get_device_id(): inputString = input("Nhap so thu tu cua thiet bi can xoa:") - number =0 device =[] resp = pgpd.get(api="network-device") response_json = resp.json() device = response_json["response"] + + number = 0 for item in device: number +=1 if number==int(inputString): - id_selete = item["id"] - return id_selete + id_seleted = item["id"] + return id_seleted #Xoa thiet bi def delete_device(): id = get_device_id() @@ -30,8 +32,13 @@ def delete_device(): except: print("Something wrong") sys.exit() -#Lay danh sach cac thiet bi -result = get_network_device.network_device_list() -print(tabulate(result, + +def main(): + #Lay danh sach cac thiet bi + result = get_network_device.network_device_list() + print(tabulate(result, headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) -result2 = delete_device() + result2 = delete_device() + +if __name__ == '__main__': + sys.exit(main()) From 307d69e19010809f1249dce8113019570a772931 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 11:12:24 +0700 Subject: [PATCH 11/44] Add files via upload --- Network Controller( APIC-EM)/controller.py | 4 + Network Controller( APIC-EM)/delete_device.py | 44 ++++++++++ .../get_network_device.py | 40 ++++++++++ Network Controller( APIC-EM)/pgpd.py | 80 +++++++++++++++++++ 4 files changed, 168 insertions(+) create mode 100644 Network Controller( APIC-EM)/controller.py create mode 100644 Network Controller( APIC-EM)/delete_device.py create mode 100644 Network Controller( APIC-EM)/get_network_device.py create mode 100644 Network Controller( APIC-EM)/pgpd.py diff --git a/Network Controller( APIC-EM)/controller.py b/Network Controller( APIC-EM)/controller.py new file mode 100644 index 0000000..4bcc056 --- /dev/null +++ b/Network Controller( APIC-EM)/controller.py @@ -0,0 +1,4 @@ +APICEM_IP = "10.215.26.9" #Địa chỉ IP của APIC-EM +VERSION = "v1" # Phiên bản APIC-EM version 1 +USERNAME ="vnpro" # Tên đăng nhập trong APIC-EM +PASSWORD ="Vnpro123" # Mật khẩu của tài khoản APIC-EM diff --git a/Network Controller( APIC-EM)/delete_device.py b/Network Controller( APIC-EM)/delete_device.py new file mode 100644 index 0000000..15b9032 --- /dev/null +++ b/Network Controller( APIC-EM)/delete_device.py @@ -0,0 +1,44 @@ +import requests +import json +import sys +from tabulate import tabulate + +import pgpd +import get_network_device + +#Lay so id cua thiet bi +def get_device_id(): + inputString = input("Nhap so thu tu cua thiet bi can xoa:") + device =[] + resp = pgpd.get(api="network-device") + response_json = resp.json() + device = response_json["response"] + + number = 0 + for item in device: + number +=1 + if number==int(inputString): + id_seleted = item["id"] + return id_seleted +#Xoa thiet bi +def delete_device(): + id = get_device_id() + try: + resp = pgpd.delete(api="network-device/"+id) + status = resp.status_code + response_json = resp.json() + r = response_json["response"] + print(r) + except: + print("Something wrong") + sys.exit() + +def main(): + #Lay danh sach cac thiet bi + result = get_network_device.network_device_list() + print(tabulate(result, + headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) + result2 = delete_device() + +if __name__ == '__main__': + sys.exit(main()) diff --git a/Network Controller( APIC-EM)/get_network_device.py b/Network Controller( APIC-EM)/get_network_device.py new file mode 100644 index 0000000..0cf4146 --- /dev/null +++ b/Network Controller( APIC-EM)/get_network_device.py @@ -0,0 +1,40 @@ +import requests #Gửi các loại yêu cầu http đến server và nhận response +import json #Là định dạng dữ liệu để truyền và nhận dữ liệu với server +import sys # Để tương tác với hệ thống +from tabulate import tabulate #cung cấp các format bảng + +import pgpd #Lấy các phương thức như get_auth_token, get +def network_device_list(): + device =[] + try: + resp = pgpd.get(api="network-device") # Lấy thông tin về network-device + status = resp.status_code #Lấy trạng thái của yêu cầu trên + response_json = resp.json() #Lấy nội dung json đã mã hóa từ lời đáp lại + device = response_json["response"] #Gán thông tin từ lời đáp lại vào device + except: + print("Something wrong,cannot get network device info") + sys.exit() + # Nếu status khác 200(nghĩa là không thành công) thì in lời đáp lại và thoát chương trình + if status !=200: + print (resp.text) + sys.exit() + # Nếu chuỗi trống thi in ra không có thiết bị được tìm thấy và thoát chương trình + if device == []: + print("No network device found") + sys.exit() + + device_list =[] + i=0 + #Tạo một vòng lặp để dò từng item và thực hiện gán các giá trị vào device_list + #item["hostname"] là dò tìm key hostname trong item và lấy ra value + for item in device: + i+=1 + device_list.append([i,item["hostname"],item["managementIpAddress"], + item["type"],item["instanceUuid"],item["id"]]) + #thư viện tabulate dùng để khi in dữ liệu ra theo format đã được xây dựng sẵn + return (device_list) +""" +result = network_device_list() +print(tabulate(result, + headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) +""" diff --git a/Network Controller( APIC-EM)/pgpd.py b/Network Controller( APIC-EM)/pgpd.py new file mode 100644 index 0000000..4353861 --- /dev/null +++ b/Network Controller( APIC-EM)/pgpd.py @@ -0,0 +1,80 @@ +import requests +import json + +import controller # Lấy các thông tin về controller + +#Tắt tin nhắn cảnh báo; +requests.packages.urllib3.disable_warnings() +'''Tạo hàm để lấy token; +các tham số ip,ver,uname,pword được gắn giá trị đã khai báo ở trên''' +def get_auth_token(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD): +#Tạo 1 jsonObject có 2 key username,password có value tương ứng là uname,pword + r_json = { + "username": uname, + "password": pword + } + post_url = "https://"+ip+"/api/"+ver+"/ticket" #khai báo URL để post + headers = {"Content-Type" : "application/json"} #khai báo headers +#try:...except: nghĩa là nếu code xảy ra lỗi ở trong phần try thì thực hiện phần except + try: + r=requests.post(post_url,data = json.dumps(r_json),headers = headers,verify=False) #gửi requests đến server và gán response vào biến r + #post là tạo dữ liệu ,post_url là địa chỉ ta muốn gửi đến, + #json.dumps dùng để mã hóa username và password, + #verify=False để không xác thực SSL + r.raise_for_status() # Lấy mã trạng thái, 200 là thành công, 404 là not found + token = r.json()["response"]["serviceTicket"] #Lấy ticket từ r + # Trả về giá trị + return { + "token" : token + } + except: + print("Status: %s" %r.status_code) + print("Response: %s" %r.text) + +ticket=get_auth_token() +print(ticket) + +# Tạo hàm get để lấy thông tin +def get(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): + ticket = get_auth_token(ip,ver,uname,pword) #Lấy ticket bằng cách gọi hàm + headers = {"X-Auth-Token": ticket['token']} #Khai báo headers để gắn ticket vào + url = "https://"+ip+"/api/"+ver+"/"+api + print("\nExecuting GET '%s'\n"%url) #In ra thông tin để người dùng biết đang lấy dữ liệu + try: + #gửi request đến server, resp là lời đáp lại của yêu cầu, get là lấy dữ liệu + resp = requests.get(url,headers=headers,params=params,verify=False) + print("GET '%s' status" %api,resp.status_code,'\n') #In ra trạng thái + return(resp) + except: + print("Something wrong",api) + sys.exit() + +# Tạo hàm put chỉnh sửa thông tin +def put(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): + ticket = get_auth_token(ip,ver,uname,pword) + headers = {"X-Auth-Token": ticket['token']} + url = "https://"+ip+"/api/"+ver+"/"+api + print("\nExecuting PUT '%s'\n"%url) + try: + resp = requests.put(url,headers=headers,params=params,verify=False) + print("PUT '%s' status" %api,resp.status_code,'\n') + return(resp) + except: + print("Something wrong",api) + sys.exit() + +def delete(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): + + ticket = get_auth_token(ip,ver,uname,pword) + headers = {"content-type" : "application/json","X-Auth-Token": ticket['token']} + url = "https://"+ip+"/api/"+ver+"/"+api + print ("\nExecuting DELETE '%s'\n"%url) + try: + # The request and response of "DELETE" request + resp= requests.delete(url,headers=headers,params=params,verify = False) + print ("DELETE '%s' Status: "%api,resp.status_code,'\n') # This is the http request status + return(resp) + except: + print ("Something wrong with DELETE /",api) + sys.exit() + From 10df23418c657d13ea749c8cb66bbfcb64e6784e Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 11:13:45 +0700 Subject: [PATCH 12/44] Delete controller.py --- controller.py | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 controller.py diff --git a/controller.py b/controller.py deleted file mode 100644 index a5a6994..0000000 --- a/controller.py +++ /dev/null @@ -1,4 +0,0 @@ -APICEM_IP = "10.215.26.9" #Địa chỉ IP của APIC-EM -USERNAME ="vnpro" # Tên đăng nhập trong APIC-EM -PASSWORD ="Vnpro123" # Mật khẩu của tài khoản APIC-EM -VERSION = "v1" # Phiên bản APIC-EM version 1 From ab49ea8fa73f1985450c4d097991b6f339a4c84e Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 11:13:59 +0700 Subject: [PATCH 13/44] Delete delete_device.py --- delete_device.py | 44 -------------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 delete_device.py diff --git a/delete_device.py b/delete_device.py deleted file mode 100644 index b05cce7..0000000 --- a/delete_device.py +++ /dev/null @@ -1,44 +0,0 @@ -import requests -import json -import sys -from tabulate import tabulate - -import pgpd -import get_network_device - -#Lay so id cua thiet bi -def get_device_id(): - inputString = input("Nhap so thu tu cua thiet bi can xoa:") - device =[] - resp = pgpd.get(api="network-device") - response_json = resp.json() - device = response_json["response"] - - number = 0 - for item in device: - number +=1 - if number==int(inputString): - id_seleted = item["id"] - return id_seleted -#Xoa thiet bi -def delete_device(): - id = get_device_id() - try: - resp = pgpd.delete(api="network-device/"+id) - status = resp.status_code - response_json = resp.json() - r = response_json["response"] - print(r) - except: - print("Something wrong") - sys.exit() - -def main(): - #Lay danh sach cac thiet bi - result = get_network_device.network_device_list() - print(tabulate(result, - headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) - result2 = delete_device() - -if __name__ == '__main__': - sys.exit(main()) From 54b171762311cb0f421fe6162f39eed4dfcecfd9 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 11:14:10 +0700 Subject: [PATCH 14/44] Delete pgpd.py --- pgpd.py | 80 --------------------------------------------------------- 1 file changed, 80 deletions(-) delete mode 100644 pgpd.py diff --git a/pgpd.py b/pgpd.py deleted file mode 100644 index 70e67c0..0000000 --- a/pgpd.py +++ /dev/null @@ -1,80 +0,0 @@ -import requests -import json - -import controller # Lấy các thông tin về controller - -#Tắt tin nhắn cảnh báo; -requests.packages.urllib3.disable_warnings() -'''Tạo hàm để lấy token; -các tham số ip,ver,uname,pword được gắn giá trị đã khai báo ở trên''' -def get_auth_token(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD): -#Tạo 1 jsonObject có 2 key username,password có value tương ứng là uname,pword - r_json = { - "username": uname, - "password": pword - } - post_url = "https://"+ip+"/api/"+ver+"/ticket" #khai báo URL để post - headers = {"Content-Type" : "application/json"} #khai báo headers -#try:...except: nghĩa là nếu code xảy ra lỗi ở trong phần try thì thực hiện phần except - try: - r=requests.post(post_url,data = json.dumps(r_json),headers = headers,verify=False) #gửi requests đến server và gán response vào biến r - #post là tạo dữ liệu ,post_url là địa chỉ ta muốn gửi đến, - #json.dumps dùng để mã hóa username và password, - #verify=False để không xác thực SSL - r.raise_for_status() # Lấy mã trạng thái, 200 là thành công, 404 là not found - token = r.json()["response"]["serviceTicket"] #Lấy ticket từ r - # Trả về giá trị - return { - "token" : token - } - except: - print("Status: %s" %r.status_code) - print("Response: %s" %r.text) - -ticket=get_auth_token() -print(ticket) - -# Tạo hàm get để lấy thông tin -def get(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): - ticket = get_auth_token(ip,ver,uname,pword) #Lấy ticket bằng cách gọi hàm - headers = {"X-Auth-Token": ticket['token']} #Khai báo headers để gắn ticket vào - url = "https://"+ip+"/api/"+ver+"/"+api - print("\nExecuting GET '%s'\n"%url) #In ra thông tin để người dùng biết đang lấy dữ liệu - try: - #gửi request đến server, resp là lời đáp lại của yêu cầu, get là lấy dữ liệu - resp = requests.get(url,headers=headers,params=params,verify=False) - print("GET '%s' status" %api,resp.status_code,'\n') #In ra trạng thái - return(resp) - except: - print("Something wrong",api) - sys.exit() - -# Tạo hàm put chỉnh sửa thông tin -def put(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): - ticket = get_auth_token(ip,ver,uname,pword) - headers = {"X-Auth-Token": ticket['token']} - url = "https://"+ip+"/api/"+ver+"/"+api - print("\nExecuting PUT '%s'\n"%url) - try: - resp = requests.put(url,headers=headers,params=params,verify=False) - print("PUT '%s' status" %api,resp.status_code,'\n') - return(resp) - except: - print("Something wrong",api) - sys.exit() - -def delete(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): - - ticket = get_auth_token(ip,ver,uname,pword) - headers = {"content-type" : "application/json","X-Auth-Token": ticket['token']} - url = "https://"+ip+"/api/"+ver+"/"+api - print ("\nExecuting DELETE '%s'\n"%url) - try: - # The request and response of "DELETE" request - resp= requests.delete(url,headers=headers,params=params,verify = False) - print ("DELETE '%s' Status: "%api,resp.status_code,'\n') # This is the http request status - return(resp) - except: - print ("Something wrong with DELETE /",api) - sys.exit() - From 299f07543d19352971df285a2c45cc3ee4b523d0 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 11:14:21 +0700 Subject: [PATCH 15/44] Delete get_network_device.py --- get_network_device.py | 39 --------------------------------------- 1 file changed, 39 deletions(-) delete mode 100644 get_network_device.py diff --git a/get_network_device.py b/get_network_device.py deleted file mode 100644 index 3baea29..0000000 --- a/get_network_device.py +++ /dev/null @@ -1,39 +0,0 @@ -import requests #Gửi các loại yêu cầu http đến server và nhận response -import json #Là định dạng dữ liệu để truyền và nhận dữ liệu với server -import sys # Để tương tác với hệ thống -from tabulate import tabulate #cung cấp các format bảng - -import pgpd #Lấy các phương thức như get_auth_token, get -def network_device_list(): - device =[] - try: - resp = pgpd.get(api="network-device") # Lấy thông tin về network-device - status = resp.status_code #Lấy trạng thái của yêu cầu trên - response_json = resp.json() #Lấy nội dung json đã mã hóa từ lời đáp lại - device = response_json["response"] #Gán thông tin từ lời đáp lại vào device - except: - print("Something wrong,cannot get network device info") - sys.exit() - # Nếu status khác 200(nghĩa là không thành công) thì in lời đáp lại và thoát chương trình - if status !=200: - print (resp.text) - sys.exit() - # Nếu chuỗi trống thi in ra không có thiết bị được tìm thấy và thoát chương trình - if device == []: - print("No network device found") - sys.exit() - - device_list =[] - i=0 - #Tạo một vòng lặp để dò từng item và thực hiện gán các giá trị vào device_list - #item["hostname"] là dò tìm key hostname trong item và lấy ra value - for item in device: - i+=1 - device_list.append([i,item["hostname"],item["managementIpAddress"], - item["type"],item["instanceUuid"],item["id"]]) - #thư viện tabulate dùng để khi in dữ liệu ra theo format đã được xây dựng sẵn - return (device_list) - -result = network_device_list() -print(tabulate(result, - headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) From 821597f2461a235a702aba6ff188b98b96584409 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 11:27:29 +0700 Subject: [PATCH 16/44] Add files via upload --- Netconf_iosxe/add_loopback.py | 75 +++++++++++++++++++++++++++++ Netconf_iosxe/device_info.py | 8 +++ Netconf_iosxe/get_interface_list.py | 49 +++++++++++++++++++ 3 files changed, 132 insertions(+) create mode 100644 Netconf_iosxe/add_loopback.py create mode 100644 Netconf_iosxe/device_info.py create mode 100644 Netconf_iosxe/get_interface_list.py diff --git a/Netconf_iosxe/add_loopback.py b/Netconf_iosxe/add_loopback.py new file mode 100644 index 0000000..273c5f5 --- /dev/null +++ b/Netconf_iosxe/add_loopback.py @@ -0,0 +1,75 @@ +from ncclient import manager +import sys +import xmltodict +import xml.dom.minidom + +from device_info import iosxe as device + +# Khai bao kieu cong +IETF_INTERFACE_TYPES = { + "loopback": "ianaift:softwareLoopback", + "ethernet": "ianaift:ethernetCsmacd" + } + +#Tao template XML cho cong +netconf_interface_template = """ + + + + {name} + {desc} + + {type} + + {status} + +
+ {ip_address} + {mask} +
+
+
+
+
""" + +#Yeu cau nhap thong tin cong Loopback +new_loopback = {} +new_loopback["name"] = "Loopback" + input("What loopback number to add? ") +new_loopback["desc"] = input("What description to use? ") +new_loopback["type"] = IETF_INTERFACE_TYPES["loopback"] +new_loopback["status"] = "true" +new_loopback["ip_address"] = input("What IP address? ") +new_loopback["mask"] = input("What network mask? ") + +# Tao Netconf payload chua du lieu cho cong +netconf_data = netconf_interface_template.format( + name = new_loopback["name"], + desc = new_loopback["desc"], + type = new_loopback["type"], + status = new_loopback["status"], + ip_address = new_loopback["ip_address"], + mask = new_loopback["mask"] + ) + +print("The configuration payload to be sent over NETCONF.\n") +print(netconf_data) + +print("Opening NETCONF Connection to {}".format(device["address"])) + +# Tao ket noi den thiet bi bang thu vien ncclient +with manager.connect( + host=device["address"], + port=device["netconf_port"], + username=device["username"], + password=device["password"], + hostkey_verify=False + ) as m: + + print("Sending a operation to the device.\n") + # tao cau truy van Netconf su dung bo loc tren (netconf_data) + netconf_reply = m.edit_config(netconf_data, target = 'running') + +print("Here is the raw XML data returned from the device.\n") +#In ket qua tra ve +print(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml()) +print("") diff --git a/Netconf_iosxe/device_info.py b/Netconf_iosxe/device_info.py new file mode 100644 index 0000000..2350222 --- /dev/null +++ b/Netconf_iosxe/device_info.py @@ -0,0 +1,8 @@ +iosxe = { + "address": "ios-xe-mgmt.cisco.com", + "netconf_port": 10000, + "restconf_port": 9443, + "ssh_port": 8181, + "username": "developer", + "password": "C1sco12345" + } diff --git a/Netconf_iosxe/get_interface_list.py b/Netconf_iosxe/get_interface_list.py new file mode 100644 index 0000000..662fb1e --- /dev/null +++ b/Netconf_iosxe/get_interface_list.py @@ -0,0 +1,49 @@ +from ncclient import manager +import sys +import xmltodict +import xml.dom.minidom + +from device_info import iosxe as device #noqa + +# Tao bo loc XML cho truy van NETCONF +netconf_filter = """ + + + + +""" + +# Mo ket noi den thiet bi mang bang ncclient +print("Opening NETCONF Connection to {}".format(device["address"])) +with manager.connect( + host=device["address"], + port=device["netconf_port"], + username=device["username"], + password=device["password"], + hostkey_verify=False + ) as m: +# Tao cau truy van NETCONF su dung bo loc tren + print("Sending a operation to the device.\n") + netconf_reply = m.get_config(source = 'running', filter = netconf_filter) + +# In ket qua tra ve dang xml +print("Here is the raw XML data returned from the device.\n") +print(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml()) +#print(netconf_reply) +print("") + +# Chuyen ket qua tra ve tu XML sang Dictionary +netconf_data = xmltodict.parse(netconf_reply.xml)["rpc-reply"]["data"] + +# Tao danh sach interfaces +interfaces = netconf_data["interfaces"]["interface"] + +print("The interface status of the device is: ") +# Chay vong lap cho moi interface va bao cao trang thai +for interface in interfaces: + print("Interface {} enabled status is {}".format( + interface["name"], + interface["enabled"] + ) + ) +print("\n") From da96557b483921779ed41b9a07436fbed10def12 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Wed, 19 Feb 2020 11:27:49 +0700 Subject: [PATCH 17/44] Add files via upload --- Restconf_iosxe/get_interfaces_list.py | 33 +++++++ Restconf_iosxe/update_ip.py | 119 ++++++++++++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 Restconf_iosxe/get_interfaces_list.py create mode 100644 Restconf_iosxe/update_ip.py diff --git a/Restconf_iosxe/get_interfaces_list.py b/Restconf_iosxe/get_interfaces_list.py new file mode 100644 index 0000000..a949701 --- /dev/null +++ b/Restconf_iosxe/get_interfaces_list.py @@ -0,0 +1,33 @@ +import requests +import sys + +requests.packages.urllib3.disable_warnings() + +HOST = 'ios-xe-mgmt.cisco.com' +PORT = '9443' +USER = 'developer' +PASS = 'C1sco12345' + +def get_configured_interfaces(): + """Lay thong tin qua RESTCONF.""" + url = "https://{h}:{p}/restconf/data/ietf-interfaces:interfaces".format(h=HOST, p=PORT) + #Dat header cho cau truy van restconf + headers = {'Content-Type': 'application/yang-data+json', + 'Accept': 'application/yang-data+json'} + #Chay phuong thuc get voi url duoc khai bao o tren + response = requests.get(url, auth=(USER, PASS), + headers=headers, verify=False) + + #tra ve du lieu dang text + return response.text + + +def main(): + """Simple main method calling our function.""" + interfaces = get_configured_interfaces() + + #In du lieu tra ve + print(interfaces) + +if __name__ == '__main__': + sys.exit(main()) diff --git a/Restconf_iosxe/update_ip.py b/Restconf_iosxe/update_ip.py new file mode 100644 index 0000000..bd6766e --- /dev/null +++ b/Restconf_iosxe/update_ip.py @@ -0,0 +1,119 @@ +import json +import requests +import sys + +# Tắt cảnh báo sSL +requests.packages.urllib3.disable_warnings() +#Thong tin cua Router tren sandbox always-on +HOST = 'ios-xe-mgmt.cisco.com' +PORT = '9443' +USER = 'developer' +PASS = 'C1sco12345' +# Xác định cổng management, không cho sửa cấu hình trên cổng này +MANAGEMENT_INTERFACE = "GigabitEthernet1" + +# Tạo URL cho cau truy vấn RESTCONF +url_base = "https://{h}:{p}/restconf".format(h=HOST, p=PORT) + +#Khai báo headers +headers = {'Content-Type': 'application/yang-data+json', + 'Accept': 'application/yang-data+json'} + +#Hàm lấy danh sách các cổng +def get_configured_interfaces(): + url = url_base + "/data/ietf-interfaces:interfaces" + response = requests.get(url,auth=(USER, PASS),headers=headers,verify=False) + + return response.json()["ietf-interfaces:interfaces"]["interface"] + +#Cấu hình ip cổng +def configure_ip_address(interface, ip): + # RESTCONF URL của cổng + url = url_base + "/data/ietf-interfaces:interfaces/interface={i}".format(i=interface) + + #Tạo payload để sửa IP + data = { + "ietf-interfaces:interface":{ + "name": interface, + "type": "iana-if-type:ethernetCsmacd", + "ietf-ip:ipv4":{ + "address":{ + "ip": ip["address"], + "netmask": ip["mask"] + } + } + } + } + #Dùng PUT để chỉnh sửa + response = requests.put(url,auth=(USER, PASS),headers=headers,verify=False, + json=data) + print(response.text) + + +#Hàm lấy thông tin chi tiết của cổng đã chọn +def print_interface_details(interface): + url = url_base + "/data/ietf-interfaces:interfaces/interface={i}".format(i=interface) + response = requests.get(url,auth=(USER, PASS),headers=headers,verify=False) + + intf = response.json()["ietf-interfaces:interface"] + print("Name: ", intf["name"]) + try: + print("IP Address: ", intf["ietf-ip:ipv4"]["address"][0]["ip"], "/", + intf["ietf-ip:ipv4"]["address"][0]["netmask"]) + except KeyError: + print("IP Address: UNCONFIGURED") + print() + + return(intf) + +# Hỏi người dùng chọn cổng nào(Nếu chọn cổng Management thì phải chọn lại) +def interface_selection(interfaces): + sel = input("Bạn muốn cấu hình với cổng nào? ") + + while sel == MANAGEMENT_INTERFACE or not sel in [intf["name"] for intf in interfaces]: + print("INVALID: Select an available interface.") + print(" " + MANAGEMENT_INTERFACE + " is used for management.") + print(" Choose another Interface") + sel = input("Bạn muốn cấu hình với cổng nào? ") + + return(sel) + + +#Yêu cầu người dùng nhập IP và Mask +def get_ip_info(): + ip = {} + ip["address"] = input("Nhập IP address: ") + ip["mask"] = input("Nhập subnet mask: ") + return(ip) + + +def main(): + #Lấy danh sách các cổng + interfaces = get_configured_interfaces() + + print("Router có những cổng sau: \n") + for interface in interfaces: + print(" * {name}".format(name=interface["name"])) + print("") + + #Hỏi user chọn cổng nào + selected_interface = interface_selection(interfaces) + print(selected_interface) + + #In ra thông tin của cổng đã chọn + print("Thông tin cổng hiện tại:") + print_interface_details(selected_interface) + + #Yêu cầu người dùng nhập IP và Mask + ip = get_ip_info() + + #Gửi cấu hình cổng lên server + configure_ip_address(selected_interface, ip) + + #In kết quả + print("Thông tin cổng sau cấu hình:") + print_interface_details(selected_interface) + + +if __name__ == '__main__': + sys.exit(main()) From 4648be3fe8785728cfd1b3f32c5260fa119c5525 Mon Sep 17 00:00:00 2001 From: vnpro149 <57343987+vnpro149@users.noreply.github.com> Date: Mon, 9 Mar 2020 18:21:42 +0700 Subject: [PATCH 18/44] Add files via upload --- .../get_device_config.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Network Controller( APIC-EM)/get_device_config.py diff --git a/Network Controller( APIC-EM)/get_device_config.py b/Network Controller( APIC-EM)/get_device_config.py new file mode 100644 index 0000000..2396f35 --- /dev/null +++ b/Network Controller( APIC-EM)/get_device_config.py @@ -0,0 +1,43 @@ +import requests +import json +import sys +from tabulate import tabulate + +import pgpd +import get_network_device +import delete_device + +def get_device_config(): + id= delete_device.get_device_id() + try: + resp = pgpd.get(api="network-device/"+id+"/config") + status = resp.status_code + response_json = resp.json() + r = response_json["response"] + print(r) + except: + print("Something wrong") + sys.exit() +def get_device_list_interfaces(): + id= delete_device.get_device_id() + try: + resp = pgpd.get(api="interface/network-device/"+id) + status = resp.status_code + response_json = resp.json() + r = json.dumps(response_json, indent = 4) + print(r) + except: + print("Something wrong") + sys.exit() +def main(): + result = get_network_device.network_device_list() + print(tabulate(result, + headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) + print("Gets the device config: ") + result2 = get_device_config() + print("Gets list of interfaces:") + result3 = get_device_list_interfaces() + + +if __name__ == '__main__': + sys.exit(main()) From 2e0239ec50a27c2c58696bc1db4716f24f5adc72 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Fri, 13 Mar 2020 11:30:30 +0700 Subject: [PATCH 19/44] abc --- Network Controller( APIC-EM)/controller.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Network Controller( APIC-EM)/controller.py b/Network Controller( APIC-EM)/controller.py index 4bcc056..d1515fb 100644 --- a/Network Controller( APIC-EM)/controller.py +++ b/Network Controller( APIC-EM)/controller.py @@ -2,3 +2,4 @@ VERSION = "v1" # Phiên bản APIC-EM version 1 USERNAME ="vnpro" # Tên đăng nhập trong APIC-EM PASSWORD ="Vnpro123" # Mật khẩu của tài khoản APIC-EM +### From 7352920d7684e2c2d2817236b27c07748aebcc06 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Fri, 13 Mar 2020 11:36:59 +0700 Subject: [PATCH 20/44] 1 --- Network Controller( APIC-EM)/controller.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Network Controller( APIC-EM)/controller.py b/Network Controller( APIC-EM)/controller.py index d1515fb..4bcc056 100644 --- a/Network Controller( APIC-EM)/controller.py +++ b/Network Controller( APIC-EM)/controller.py @@ -2,4 +2,3 @@ VERSION = "v1" # Phiên bản APIC-EM version 1 USERNAME ="vnpro" # Tên đăng nhập trong APIC-EM PASSWORD ="Vnpro123" # Mật khẩu của tài khoản APIC-EM -### From 30dea630724adf9dc91454817ed9a7390a0f65ad Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Mon, 23 Mar 2020 16:35:47 +0700 Subject: [PATCH 21/44] Update delete_device.py --- Network Controller( APIC-EM)/delete_device.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Network Controller( APIC-EM)/delete_device.py b/Network Controller( APIC-EM)/delete_device.py index 15b9032..b4982f2 100644 --- a/Network Controller( APIC-EM)/delete_device.py +++ b/Network Controller( APIC-EM)/delete_device.py @@ -8,7 +8,7 @@ #Lay so id cua thiet bi def get_device_id(): - inputString = input("Nhap so thu tu cua thiet bi can xoa:") + inputString = input("Nhap so thu tu cua thiet bi can chon:") device =[] resp = pgpd.get(api="network-device") response_json = resp.json() From 503f6fd83475f5d1f79103961be9c9a0113dc8f6 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Mon, 23 Mar 2020 16:48:23 +0700 Subject: [PATCH 22/44] Update delete_device.py --- Network Controller( APIC-EM)/delete_device.py | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Network Controller( APIC-EM)/delete_device.py b/Network Controller( APIC-EM)/delete_device.py index b4982f2..b7908ed 100644 --- a/Network Controller( APIC-EM)/delete_device.py +++ b/Network Controller( APIC-EM)/delete_device.py @@ -23,14 +23,18 @@ def get_device_id(): #Xoa thiet bi def delete_device(): id = get_device_id() - try: - resp = pgpd.delete(api="network-device/"+id) - status = resp.status_code - response_json = resp.json() - r = response_json["response"] - print(r) - except: - print("Something wrong") + choose = input('Xoa thiet bi vua chon? (y/n):') + if choose == 'y': + try: + resp = pgpd.delete(api="network-device/"+id) + status = resp.status_code + response_json = resp.json() + r = response_json["response"] + print(r) + except: + print("Something wrong") + sys.exit() + if choose == 'n': sys.exit() def main(): @@ -38,6 +42,7 @@ def main(): result = get_network_device.network_device_list() print(tabulate(result, headers = ['number','hostname','ip','type','mac address','id'], tablefmt="rst")) + print("Delete device") result2 = delete_device() if __name__ == '__main__': From a312bb975717f83c21447df58e87fb3cf441e0b7 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Sat, 4 Apr 2020 07:55:25 +0700 Subject: [PATCH 23/44] Delete Netconf_IOSXE_Sandbox --- Netconf_IOSXE_Sandbox | 49 ------------------------------------------- 1 file changed, 49 deletions(-) delete mode 100644 Netconf_IOSXE_Sandbox diff --git a/Netconf_IOSXE_Sandbox b/Netconf_IOSXE_Sandbox deleted file mode 100644 index 1d74db6..0000000 --- a/Netconf_IOSXE_Sandbox +++ /dev/null @@ -1,49 +0,0 @@ -from ncclient import manager -import sys -import xmltodict -import xml.dom.minidom - -from device_info import iosxe as device #noqa - -# Tao bo loc XML cho truy van NETCONF -netconf_filter = """ - - - - -""" - -# Mo ket noi den thiet bi mang bang ncclient -print("Opening NETCONF Connection to {}".format(device["address"])) -with manager.connect( - host=device["address"], - port=device["netconf_port"], - username=device["username"], - password=device["password"], - hostkey_verify=False - ) as m: -# Tao cau truy van NETCONF su dung bo loc tren - print("Sending a operation to the device.\n") - netconf_reply = m.get_config(source = 'running', filter = netconf_filter) - -# In ket qua tra ve dang xml -print("Here is the raw XML data returned from the device.\n") -print(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml()) -#print(netconf_reply) -print("") - -# Chuyen ket qua tra ve tu XML sang Dictionary -netconf_data = xmltodict.parse(netconf_reply.xml)["rpc-reply"]["data"] - -# Tao danh sach interface -interfaces = netconf_data["interfaces"]["interface"] - -print("The interface status of the device is: ") -# Chay vong lap cho moi interface va bao cao trang thai -for interface in interfaces: - print("Interface {} enabled status is {}".format( - interface["name"], - interface["enabled"] - ) - ) -print("\n") From 3c796e86ae3666c107abc6535022446e6e9b441d Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Sat, 4 Apr 2020 07:56:00 +0700 Subject: [PATCH 24/44] Delete Restconf_IOSXE_Sandbox --- Restconf_IOSXE_Sandbox | 34 ---------------------------------- 1 file changed, 34 deletions(-) delete mode 100644 Restconf_IOSXE_Sandbox diff --git a/Restconf_IOSXE_Sandbox b/Restconf_IOSXE_Sandbox deleted file mode 100644 index bb3cb98..0000000 --- a/Restconf_IOSXE_Sandbox +++ /dev/null @@ -1,34 +0,0 @@ -import requests -import sys - -requests.packages.urllib3.disable_warnings() - -HOST = 'ios-xe-mgmt.cisco.com' -PORT = '9443' -USER = 'developer' -PASS = 'C1sco12345' - -def get_configured_interfaces(): - """Lay thong tin qua RESTCONF.""" - url = "https://{h}:{p}/restconf/data/ietf-interfaces:interfaces".format(h=HOST, p=PORT) - #Dat header cho cau truy van restconf - headers = {'Content-Type': 'application/yang-data+json', - 'Accept': 'application/yang-data+json'} - #Chay phuong thuc get voi url duoc khai bao o tren - response = requests.get(url, auth=(USER, PASS), - headers=headers, verify=False) - - #tra ve du lieu dang text - return response.text - - -def main(): - """Simple main method calling our function.""" - interfaces = get_configured_interfaces() - - #In du lieu tra ve - print(interfaces) - -if __name__ == '__main__': - sys.exit(main()) - From dc83faf1d4278bce62f6445708bbc9aaec543194 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Sat, 4 Apr 2020 08:48:31 +0700 Subject: [PATCH 25/44] Add files via upload --- .../flask_app.py | 27 +++ .../passwords.txt | 2 + .../welcome.txt | 1 + Parse API Data Formats/helper.py | 38 ++++ Parse API Data Formats/item.xml | 15 ++ Parse API Data Formats/lab01(edited).py | 173 ++++++++++++++++++ Parse API Data Formats/lab01.py | 169 +++++++++++++++++ Parse API Data Formats/user.xml | 22 +++ Parse API Data Formats/user.yaml | 16 ++ SD_WAN/SD_WAN_INFO.py | 3 + SD_WAN/sdwan.py | 81 ++++++++ Unittest/calc/calc.py | 11 ++ Unittest/calc/test_calc.py | 22 +++ Unittest/name/device_name.py | 11 ++ Unittest/name/test_device_name.py | 18 ++ 15 files changed, 609 insertions(+) create mode 100644 Exploit Insufficient Parameter Sanitization/flask_app.py create mode 100644 Exploit Insufficient Parameter Sanitization/passwords.txt create mode 100644 Exploit Insufficient Parameter Sanitization/welcome.txt create mode 100644 Parse API Data Formats/helper.py create mode 100644 Parse API Data Formats/item.xml create mode 100644 Parse API Data Formats/lab01(edited).py create mode 100644 Parse API Data Formats/lab01.py create mode 100644 Parse API Data Formats/user.xml create mode 100644 Parse API Data Formats/user.yaml create mode 100644 SD_WAN/SD_WAN_INFO.py create mode 100644 SD_WAN/sdwan.py create mode 100644 Unittest/calc/calc.py create mode 100644 Unittest/calc/test_calc.py create mode 100644 Unittest/name/device_name.py create mode 100644 Unittest/name/test_device_name.py diff --git a/Exploit Insufficient Parameter Sanitization/flask_app.py b/Exploit Insufficient Parameter Sanitization/flask_app.py new file mode 100644 index 0000000..3ccb868 --- /dev/null +++ b/Exploit Insufficient Parameter Sanitization/flask_app.py @@ -0,0 +1,27 @@ +import re +from flask import Flask, request + +app = Flask(__name__) + +def sanitize_string(filename): + if re.search('^[\w\-\.]+$', filename): + pass + else: + raise ValueError('Can not use special characters') + +def cat(filename): + sanitize_string(filename) + with open(filename) as file: + data = file.read() + return data + + +@app.route('/get_file', methods=['GET']) +def get_file(): + filename = request.args['filename'] + return '''Content of the file {} is...\n\n {}'''.format(filename, cat(filename)) + + +if __name__ == "__main__": + app.run(host="127.0.0.1", port=int("5000"))#, debug=True) + diff --git a/Exploit Insufficient Parameter Sanitization/passwords.txt b/Exploit Insufficient Parameter Sanitization/passwords.txt new file mode 100644 index 0000000..23ed1af --- /dev/null +++ b/Exploit Insufficient Parameter Sanitization/passwords.txt @@ -0,0 +1,2 @@ +username=cisco +password=cisco \ No newline at end of file diff --git a/Exploit Insufficient Parameter Sanitization/welcome.txt b/Exploit Insufficient Parameter Sanitization/welcome.txt new file mode 100644 index 0000000..9e42ee2 --- /dev/null +++ b/Exploit Insufficient Parameter Sanitization/welcome.txt @@ -0,0 +1 @@ +Hello Student!! diff --git a/Parse API Data Formats/helper.py b/Parse API Data Formats/helper.py new file mode 100644 index 0000000..d987155 --- /dev/null +++ b/Parse API Data Formats/helper.py @@ -0,0 +1,38 @@ +# Helper module with User class and additional functions +from datetime import date + +## User Class +class User: + def __init__(self): + self.id = None + self.first_name = None + self.last_name = None + self.birth_date = None + self.address = None + self.score = None + + # Print the object + def __repr__(self): + return str(self.__dict__) + +# User object serialization +def serializeUser(object): + if isinstance(object, User): + return object.__dict__ + + if isinstance(object, date): + return object.__str__() + +## Used For MiniDom +# Print the tags of a nodeList object +def printTags(nodeList): + for node in nodeList: + if node.nodeName != '#text': + print(node.nodeName) + +# Recursively print the node list childern's name (tag) and its value +def printNodes (nodeList, level=0): + for node in nodeList: + if node.nodeName != '#text': + print( (" ")*level + node.nodeName + ':' + node.firstChild.data) + printNodes(node.childNodes, level+1) \ No newline at end of file diff --git a/Parse API Data Formats/item.xml b/Parse API Data Formats/item.xml new file mode 100644 index 0000000..90ffb4d --- /dev/null +++ b/Parse API Data Formats/item.xml @@ -0,0 +1,15 @@ + + + + + Router + Switch + + + + + Coffee Table + 180 + 80 + + \ No newline at end of file diff --git a/Parse API Data Formats/lab01(edited).py b/Parse API Data Formats/lab01(edited).py new file mode 100644 index 0000000..99c2a81 --- /dev/null +++ b/Parse API Data Formats/lab01(edited).py @@ -0,0 +1,173 @@ +# Import modules +import sys +from helper import * +from ruamel import yaml +import json + +import xml.etree.ElementTree as ET + +import xml.dom.minidom as MD + +# Main function +if __name__ == "__main__": + ######################################### + # Procedure 1 # + ######################################### + # Add print statement here + print('Devnet') + + + ######################################### + # Procedure 2 # + ######################################### + print('##################') + print('###### YAML ######') + print('##################') + + # Open the user.yaml file as read only + with open('user.yaml','r') as stream: + # Load the stream using safe_load + user_yaml = yaml.safe_load(stream) + + # Print the object type + print("Type of user_yaml variable:") + print(type(user_yaml)) + print('----------------------') + + # Iterate over the keys of the user_yaml and print them + print('Keys in user_yaml:') + for key in user_yaml: + print(key) + print('----------------------') + + # Create a new instance of class User + user = User() + # Assign values form the user_yaml to the object user + user.id = user_yaml['id'] + user.first_name = user_yaml['first_name'] + user.last_name = user_yaml['last_name'] + user.birth_date = user_yaml['birth_date'] + user.address = user_yaml['address'] + user.score = user_yaml['score'] + # Print the user object + print('User object:') + print(user) + + ######################################### + # Procedure 3 # + ######################################### + print('##################') + print('###### JSON ######') + print('##################') + + # Create JSON structure from the user object + user_json = json.dumps(user, default = serializeUser) + # Print the created JSON structure + print('Print user_json:') + print(user_json) + print('----------------------') + + # Create JSON structre with indents and soreted keys + print('JSON with indents and sorted keys') + user_json = json.dumps(user, default = serializeUser, indent = 4, sort_keys = True) + print(user_json) + # Print to file user.json + file = open("user.json","w") + file.write(user_json) + file.close() + ######################################### + # Procedure 4 # + ######################################### + print('######################') + print('# XML - Element Tree #') + print('######################') + + # Parse the user.xml file + tree = ET.parse('user.xml') + # Get the root element + root = tree.getroot() + # Print the tags + print('Tags in the XML:') + for element in root: + print(element.tag) + print('----------------------') + + # Print the value of id tag + print('id tag value:') + print(root.find('id').text) + print('----------------------') + + # Find all elements with the tag address in root + addresses = root.findall('address') + # Print the adresses in the xml + print('Addresses:') + for address in addresses: + for i in address: + print(i.tag + ':' + i.text) + print('----------------------') + + # Print the elements in root with their tags and values + print('Print the structure') + for k in root.iter(): #Lấy từng phần tử của nó tại thời điểm nhất định + print(k.tag + ':' + k.text) + # Parsing XML files with MiniDOM + print('######################') + print('### XML - MiniDOM ####') + print('######################') + + # Parse the user.xml file + dom = MD.parse('user.xml') + # Print the tags + print('Tags in the XML:') + for node in dom.childNodes: + printTags(node.childNodes) + print('----------------------') + + # Accessing element value + print('Accessing element value') + idElements = dom.getElementsByTagName('id') + print(idElements) + elementId= idElements.item(0) + print(elementId.childNodes) + idValue = elementId.firstChild.data + print(idValue) + print('----------------------') + + # Print elements from the DOM with tag name 'address' + print('Addresses:') + for node in dom.getElementsByTagName('address'): + printNodes(node.childNodes) + print('----------------------') + + # Print the entire structure with printNodes + print('The structure:') + for node in dom.childNodes: + printNodes(node.childNodes) + + ######################################### + # Procedure 5 # + ######################################### + print('######################') + print('# Use Namespaces #') + print('######################') + + # Parse the item.xml file + itemTree = ET.parse('item.xml') + # Get the root element + root = itemTree.getroot() + # Define namespaces + namespaces = {'a':'https://www.example.com/network','b':'https://www.example.com/furniture'} + # Set table as the root element + elementsInNSa = root.findall('a:table',namespaces) + elementsInNSb = root.findall('b:table',namespaces) + # Elements in NS a + print('Elements in NS a:') + for e in elementsInNSa: + for i in e.iter(): + print(i.tag + ':'+ i.text) + print('----------------------') + + # Elements in NS b + print('Elements in NS b:') + for element in list(elementsInNSb[0]): + print(element.tag + ":" + element.text) diff --git a/Parse API Data Formats/lab01.py b/Parse API Data Formats/lab01.py new file mode 100644 index 0000000..31b1937 --- /dev/null +++ b/Parse API Data Formats/lab01.py @@ -0,0 +1,169 @@ +# Import modules +import sys +from helper import * +from ruamel import yaml +import json + +import xml.etree.ElementTree as ET + +import xml.dom.minidom as MD + +# Main function +if __name__ == "__main__": + ######################################### + # Procedure 1 # + ######################################### + # Add print statement here + print('Devnet') + + + ######################################### + # Procedure 2 # + ######################################### + print('##################') + print('###### YAML ######') + print('##################') + + # Open the user.yaml file as read only + with open('user.yaml','r') as stream: + # Load the stream using safe_load + user_yaml = yaml.safe_load(stream) + + # Print the object type + print("Type of user_yaml variable:") + print(type(user_yaml)) + print('----------------------') + + # Iterate over the keys of the user_yaml and print them + print('Keys in user_yaml:') + for key in user_yaml: + print(key) + print('----------------------') + + # Create a new instance of class User + user = User() + # Assign values form the user_yaml to the object user + user.id = user_yaml['id'] + user.first_name = user_yaml['first_name'] + user.last_name = user_yaml['last_name'] + user.birth_date = user_yaml['birth_date'] + user.address = user_yaml['address'] + user.score = user_yaml['score'] + # Print the user object + print('User object:') + print(user) + + ######################################### + # Procedure 3 # + ######################################### + print('##################') + print('###### JSON ######') + print('##################') + + # Create JSON structure from the user object + user_json = json.dumps(user, default = serializeUser) + # Print the created JSON structure + print('Print user_json:') + print(user_json) + print('----------------------') + + # Create JSON structre with indents and soreted keys + print('JSON with indents and sorted keys') + user_json = json.dumps(user, default = serializeUser, indent = 4, sort_keys = True) + print(user_json) + ######################################### + # Procedure 4 # + ######################################### + print('######################') + print('# XML - Element Tree #') + print('######################') + + # Parse the user.xml file + tree = ET.parse('user.xml') + # Get the root element + root = tree.getroot() + # Print the tags + print('Tags in the XML:') + for element in root: + print(element.tag) + print('----------------------') + + # Print the value of id tag + print('id tag value:') + print(root.find('id').text) + print('----------------------') + + # Find all elements with the tag address in root + addresses = root.findall('address') + # Print the adresses in the xml + print('Addresses:') + for address in addresses: + for i in address: + print(i.tag + ':' + i.text) + print('----------------------') + + # Print the elements in root with their tags and values + print('Print the structure') + for k in root.iter(): + print(k.tag + ':' + k.text) + # Parsing XML files with MiniDOM + print('######################') + print('### XML - MiniDOM ####') + print('######################') + + # Parse the user.xml file + dom = MD.parse('user.xml') + # Print the tags + print('Tags in the XML:') + for node in dom.childNodes: + printTags(node.childNodes) + print('----------------------') + + # Accessing element value + print('Accessing element value') + idElements = dom.getElementsByTagName('id') + print(idElements) + elementId= idElements.item(0) + print(elementId.childNodes) + idValue = elementId.firstChild.data + print(idValue) + print('----------------------') + + # Print elements from the DOM with tag name 'address' + print('Addresses:') + for node in dom.getElementsByTagName('address'): + printNodes(node.childNodes) + print('----------------------') + + # Print the entire structure with printNodes + print('The structure:') + for node in dom.childNodes: + printNodes(node.childNodes) + + ######################################### + # Procedure 5 # + ######################################### + print('######################') + print('# Use Namespaces #') + print('######################') + + # Parse the user.xml file + itemTree = ET.parse('item.xml') + # Get the root element + root = itemTree.getroot() + # Define namespaces + namespaces = {'a':'https://www.example.com/network','b':'https://www.example.com/furniture'} + # Set table as the root element + elementsInNSa = root.findall('a:table',namespaces) + elementsInNSb = root.findall('b:table',namespaces) + # Elements in NS a + print('Elements in NS a:') + for e in elementsInNSa: + for i in e.iter(): + print(i.tag + ':'+ i.text) + print('----------------------') + + # Elements in NS b + print('Elements in NS b:') + for element in list(elementsInNSb[0]): + print(element.tag + ":" + element.text) diff --git a/Parse API Data Formats/user.xml b/Parse API Data Formats/user.xml new file mode 100644 index 0000000..486163b --- /dev/null +++ b/Parse API Data Formats/user.xml @@ -0,0 +1,22 @@ + + + 3242 + Ray + Smith + 1979-08-15 +
+ 94873 Ledner Rue + Royal Oak + 44663 + OH + 1 +
+
+ 832 William Ave + Elnaville + 17319 + EL + 0 +
+ 18.3 +
\ No newline at end of file diff --git a/Parse API Data Formats/user.yaml b/Parse API Data Formats/user.yaml new file mode 100644 index 0000000..d50eca1 --- /dev/null +++ b/Parse API Data Formats/user.yaml @@ -0,0 +1,16 @@ +id: 3242 +first_name: 'Ray' +last_name: 'Smith' +birth_date: 1979-08-15 +address: + - street: '94873 Ledner Rue' + city: 'Royal Oak' + postal_code: 44663 + state: 'OH' + primary: 1 + - street: '832 William Ave' + city: 'Elnaville' + postal_code: 17319 + state: 'EL' + primary: 0 +score: 18.3 \ No newline at end of file diff --git a/SD_WAN/SD_WAN_INFO.py b/SD_WAN/SD_WAN_INFO.py new file mode 100644 index 0000000..eea3b88 --- /dev/null +++ b/SD_WAN/SD_WAN_INFO.py @@ -0,0 +1,3 @@ +IP = "sandboxsdwan.cisco.com" +USERNAME = "devnetuser" +PASSWORD = "Cisco123!" diff --git a/SD_WAN/sdwan.py b/SD_WAN/sdwan.py new file mode 100644 index 0000000..202c5ab --- /dev/null +++ b/SD_WAN/sdwan.py @@ -0,0 +1,81 @@ +import requests +import sys +import json +import click +from tabulate import tabulate +import SD_WAN_INFO +requests.packages.urllib3.disable_warnings() + +SDWAN_IP = SD_WAN_INFO.IP +SDWAN_USERNAME = SD_WAN_INFO.USERNAME +SDWAN_PASSWORD = SD_WAN_INFO.PASSWORD + + +class rest_api_lib: + def __init__(self, vmanage_ip, username, password): + self.vmanage_ip = vmanage_ip + self.session = {} + self.login(self.vmanage_ip, username, password) + + def login(self, vmanage_ip, username, password): + """Login to vmanage""" + base_url_str = 'https://%s:8443/'%vmanage_ip + login_action = '/j_security_check' + login_url = base_url_str + login_action + + login_data = {'j_username' : username, 'j_password' : password} + sess = requests.session() + login_response = sess.post(url=login_url, data=login_data, verify=False) + + if b'' in login_response.content: + print ("Login Failed") + #print(login_response.content) + sys.exit(0) + + self.session[vmanage_ip] = sess + + def get_request(self, api): + url = "https://%s:8443/dataservice/%s"%(self.vmanage_ip, api) + #print url + response = self.session[self.vmanage_ip].get(url, verify=False) + data = response.content + return data + + def post_request(self, api, payload, headers={'Content-Type': 'application/json'}): + url = "https://%s:8443/dataservice/%s"%(self.vmanage_ip, api) + payload = json.dumps(payload) + print(payload) + + response = self.session[self.vmanage_ip].post(url=url, data=payload, headers=headers, verify=False) + data = response.json() + return data + +sdwanp = rest_api_lib(SDWAN_IP, SDWAN_USERNAME, SDWAN_PASSWORD) + +@click.group() +def cli(): + pass + +@click.command() +def device_list(): + """Retrieve and return network devices list.""" + click.echo("Retrieving the devices.") + + response = json.loads(sdwanp.get_request('device')) + items = response['data'] + + headers = ["Host-Name", "Device Type", "Device ID", "System IP", "Site ID", "Version", "Device Model"] + table = list() + + for item in items: + tr = [item['host-name'], item['device-type'], item['uuid'], item['system-ip'], item['site-id'], item['version'], item['device-model']] + table.append(tr) + try: + click.echo(tabulate(table, headers, tablefmt="fancy_grid")) + except UnicodeEncodeError: + click.echo(tabulate(table, headers, tablefmt="grid")) + +cli.add_command(device_list) + +if __name__ == "__main__": + cli() diff --git a/Unittest/calc/calc.py b/Unittest/calc/calc.py new file mode 100644 index 0000000..2d0fb55 --- /dev/null +++ b/Unittest/calc/calc.py @@ -0,0 +1,11 @@ +def add(a,b): + return a+b + +def subtract(a,b): + return a-b + +def multiply(a,b): + return a*b + +def devide(a,b): + return a/b diff --git a/Unittest/calc/test_calc.py b/Unittest/calc/test_calc.py new file mode 100644 index 0000000..18938d9 --- /dev/null +++ b/Unittest/calc/test_calc.py @@ -0,0 +1,22 @@ +import unittest +import calc + +class TestCalc(unittest.TestCase): + def test_add(self): + self.assertEqual(calc.add(5,5),10) + self.assertEqual(calc.add(-1,1),0) + + def test_subtrct(self): + self.assertEqual(calc.subtract(6,3),3) + self.assertEqual(calc.subtract(-1,1),-2) + + def test_multiply(self): + self.assertEqual(calc.multiply(3,3),9) + self.assertEqual(calc.multiply(-2,-3),6) + + def test_devide(self): + self.assertEqual(calc.devide(6,2),3) + self.assertEqual(calc.devide(-1,-1),1) + +if __name__=='__main__': + unittest.main() diff --git a/Unittest/name/device_name.py b/Unittest/name/device_name.py new file mode 100644 index 0000000..582645a --- /dev/null +++ b/Unittest/name/device_name.py @@ -0,0 +1,11 @@ +def parse_device_name(vendor, device_type, platform): + full_name = vendor + ' '+device_type+' '+platform + return full_name.title() + + +def parse_device_name(vendor, device_type,platform, spec=''): + if spec !='': + full_name = vendor +' '+device_type+' '+platform+' '+spec + else: + full_name = vendor +' '+device_type+' '+platform + return full_name.title() diff --git a/Unittest/name/test_device_name.py b/Unittest/name/test_device_name.py new file mode 100644 index 0000000..15ea5c7 --- /dev/null +++ b/Unittest/name/test_device_name.py @@ -0,0 +1,18 @@ +from device_name import parse_device_name +import unittest + +class NamesTestCase(unittest.TestCase): + + def test_parse_device_full_name_(self): + result = parse_device_name("Cisco","Router","2911","Sec") + self.assertEqual(result,"Cisco Router 2911 Sec") + +if __name__=="__main__": + unittest.main() + + +""" + def test_parse_device_name(self): + result = parse_device_name("Cisco","Router","2911") + self.assertEqual(result,"Cisco Router 2911") +""" From 246182439fd984a1e1c906343de48992d6ed6672 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Mon, 4 May 2020 16:52:36 +0700 Subject: [PATCH 26/44] Add files via upload --- Contruct a Python Unit Test/conftest.py | 27 +++++++++++ Contruct a Python Unit Test/student.py | 44 ++++++++++++++++++ Contruct a Python Unit Test/subject.py | 3 ++ .../test_grades_errorpath.py | 45 +++++++++++++++++++ .../test_grades_happypath.py | 17 +++++++ 5 files changed, 136 insertions(+) create mode 100644 Contruct a Python Unit Test/conftest.py create mode 100644 Contruct a Python Unit Test/student.py create mode 100644 Contruct a Python Unit Test/subject.py create mode 100644 Contruct a Python Unit Test/test_grades_errorpath.py create mode 100644 Contruct a Python Unit Test/test_grades_happypath.py diff --git a/Contruct a Python Unit Test/conftest.py b/Contruct a Python Unit Test/conftest.py new file mode 100644 index 0000000..f6494f1 --- /dev/null +++ b/Contruct a Python Unit Test/conftest.py @@ -0,0 +1,27 @@ +import pytest + +@pytest.fixture +def student(): + from student import Student + + stud = Student('Luka Zauber') + yield stud + del stud + + +@pytest.fixture +def subject(): + from subject import Subject + + s = Subject('Unit Testing 101') + yield s + del s + + +@pytest.fixture +def subjects(): + from subject import Subject + + s = [Subject('Unit Testing 101'), Subject('CS500')] + yield s + del s diff --git a/Contruct a Python Unit Test/student.py b/Contruct a Python Unit Test/student.py new file mode 100644 index 0000000..26000e7 --- /dev/null +++ b/Contruct a Python Unit Test/student.py @@ -0,0 +1,44 @@ +import subject + + +class Student: + def __init__(self, name): + self.name = name + self.email = None + self.subjects = [] + self.grades = [] + + def add_subject(self, subject): + if subject: + if subject not in self.subjects: + self.subjects.append(subject) + return True + else: + return False + else: + return False + + def set_grade(self, subject, grade): + if (subject and grade) or (subject and grade is int(0)): + if subject in self.subjects: + if grade < 1 or grade > 10: + raise ValueError('grade out of bound', grade) + else: + self.grades.append((subject, grade)) + return True + + else: + raise ValueError('no subject or grade', subject) + else: + return False + + def get_grades_for_subject(self, subject): + if subject: + grades = [] + for grade in self.grades: + if grade[0] is subject: + grades.append(grade[1]) + else: + return False + + return grades diff --git a/Contruct a Python Unit Test/subject.py b/Contruct a Python Unit Test/subject.py new file mode 100644 index 0000000..0fa2f4e --- /dev/null +++ b/Contruct a Python Unit Test/subject.py @@ -0,0 +1,3 @@ +class Subject: + def __init__(self, name): + self.name = name diff --git a/Contruct a Python Unit Test/test_grades_errorpath.py b/Contruct a Python Unit Test/test_grades_errorpath.py new file mode 100644 index 0000000..b65de2a --- /dev/null +++ b/Contruct a Python Unit Test/test_grades_errorpath.py @@ -0,0 +1,45 @@ +import pytest + + +@pytest.mark.usefixtures('student', 'subject') +class TestErrorPathSubject: + def test_add_empty_subject_to_student(self, student, subject): + assert student.add_subject(None) is False + + def test_add_existing_subject_to_student(self, student, subject): + student.add_subject(subject) + assert student.add_subject(subject) is False + + +@pytest.mark.usefixtures('student', 'subject') +class TestErrorPathAddGrade: + def test_add_higher_grade_to_subject(self, student, subject): + student.add_subject(subject) + with pytest.raises(ValueError): + student.set_grade(subject, 11) + + def test_add_lower_grade_to_subject(self, student, subject): + student.add_subject(subject) + with pytest.raises(ValueError): + student.set_grade(subject, -1) + + def test_add_zero_grade_to_subject(self, student, subject): + student.add_subject(subject) + with pytest.raises(ValueError): + student.set_grade(subject, 0) + + +@pytest.mark.usefixtures('student', 'subject', 'subjects') +class TestErrorPathGetGrade: + def test_get_none_subject_grade(self, student, subject): + student.add_subject(subject) + student.set_grade(subject, 8) + assert student.get_grades_for_subject(None) is False + + def test_get_missing_subject_grade(self, student, subjects): + student.add_subject(subjects[0]) + student.add_subject(subjects[1]) + student.set_grade(subjects[0], 8) + assert student.get_grades_for_subject(subjects[1]) == [] + + diff --git a/Contruct a Python Unit Test/test_grades_happypath.py b/Contruct a Python Unit Test/test_grades_happypath.py new file mode 100644 index 0000000..2782be0 --- /dev/null +++ b/Contruct a Python Unit Test/test_grades_happypath.py @@ -0,0 +1,17 @@ +import pytest + +@pytest.mark.usefixtures('student', 'subject') +class TestHappyPath: + def test_add_subject_to_student(self, student, subject): + assert student.add_subject(subject) is True + + def test_add_grade_to_subject(self, student, subject): + student.add_subject(subject) + assert student.set_grade(subject, 8) is True + + def test_get_subject_grade(self, student, subject): + student.add_subject(subject) + student.set_grade(subject, 8) + student.set_grade(subject, 9) + assert student.get_grades_for_subject(subject) == [8, 9] + From a0de3bcd4adbb240a45f34a732c8fc555f908730 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Thu, 21 May 2020 08:45:13 +0700 Subject: [PATCH 27/44] Add files via upload --- DNA Center/controller.py | 5 +++ DNA Center/get_network_device.py | 33 +++++++++++++++ DNA Center/pgpd.py | 71 ++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 DNA Center/controller.py create mode 100644 DNA Center/get_network_device.py create mode 100644 DNA Center/pgpd.py diff --git a/DNA Center/controller.py b/DNA Center/controller.py new file mode 100644 index 0000000..613327b --- /dev/null +++ b/DNA Center/controller.py @@ -0,0 +1,5 @@ +DNAC_IP = "sandboxdnac.cisco.com" +DNAC_PORT = 443 +USERNAME = "devnetuser" +PASSWORD = "Cisco123!" +VERSION = "v1" diff --git a/DNA Center/get_network_device.py b/DNA Center/get_network_device.py new file mode 100644 index 0000000..49a0069 --- /dev/null +++ b/DNA Center/get_network_device.py @@ -0,0 +1,33 @@ +from pgpd import * +from tabulate import * + +def network_device_list(): + device = [] + try: + resp = get(api="network-device") + status = resp.status_code + response_json = resp.json() + device = response_json["response"] + #print(device) + #print(json.dumps(device,indent=4)) + except ValueError: + print ("Something wrong, cannot get network device information") + sys.exit() + + if status != 200: + print (resp.text) + sys.exit() + + if device == [] : + print ("No network device found !") + sys.exit() + + device_list = [] + i=0 + for item in device: + i+=1 + device_list.append([i,item["hostname"],item["managementIpAddress"],item["type"],item["instanceUuid"]]) + return (device_list) + +result = network_device_list() +print (tabulate(result, headers=['number','hostname','ip','type'],tablefmt="rst")) diff --git a/DNA Center/pgpd.py b/DNA Center/pgpd.py new file mode 100644 index 0000000..d51c874 --- /dev/null +++ b/DNA Center/pgpd.py @@ -0,0 +1,71 @@ +import json +import sys +import requests +from requests.auth import HTTPBasicAuth + +import controller + +requests.packages.urllib3.disable_warnings() + +def get_X_auth_token(ip=controller.DNAC_IP, ver=controller.VERSION, uname=controller.USERNAME, pword=controller.PASSWORD): + post_url = "https://"+ip+"/api/system/"+ ver +"/auth/token" + headers = {'content-type': 'application/json'} + try: + r = requests.post(post_url, auth=HTTPBasicAuth(username=uname, password=pword), headers=headers,verify=False) + r.raise_for_status() + return r.json()["Token"] + except requests.exceptions.ConnectionError as e: + print ("Error: %s" % e) + sys.exit() + +def get(ip=controller.DNAC_IP, ver=controller.VERSION, uname=controller.USERNAME, pword=controller.PASSWORD, api='', params=''): + token = get_X_auth_token(ip,ver,uname,pword) + headers = {"X-Auth-Token": token} + url = "https://"+ip+"/api/"+ver+"/"+api + print ("\nExecuting GET '%s'\n"%url) + try: + resp= requests.get(url,headers=headers,params=params,verify = False) + print ("GET '%s' Status: "%api,resp.status_code,'\n') + return(resp) + except: + print ("Something wrong with GET /",api) + sys.exit() + +def post(ip=controller.DNAC_IP, ver=controller.VERSION, uname=controller.USERNAME, pword=controller.PASSWORD, api='', data=''): + token = get_X_auth_token(ip,ver,uname,pword) + headers = {"content-type" : "application/json","X-Auth-Token": token} + url = "https://"+ip+"/api/"+ver+"/"+api + print ("\nExecuting POST '%s'\n"%url) + try: + resp= requests.post(url,json.dumps(data),headers=headers,verify = False) + print ("POST '%s' Status: "%api,resp.status_code,'\n') + return(resp) + except: + print ("Something wrong with POST /",api) + sys.exit() + +def put(ip=controller.DNAC_IP, ver=controller.VERSION, uname=controller.USERNAME, pword=controller.PASSWORD, api='', data=''): + token = get_X_auth_token(ip,ver,uname,pword) + headers = {"content-type" : "application/json","X-Auth-Token": token} + url = "https://"+ip+"/api/"+ver+"/"+api + print ("\nExecuting PUT '%s'\n"%url) + try: + resp= requests.put(url,json.dumps(data),headers=headers,verify = False) + print ("PUT '%s' Status: "%api,resp.status_code,'\n') + return(resp) + except: + print ("Something wrong with PUT /",api) + sys.exit() + +def delete(ip=controller.DNAC_IP, ver=controller.VERSION, uname=controller.USERNAME, pword=controller.PASSWORD, api='', params=''): + token = get_X_auth_token(ip,ver,uname,pword) + headers = {"content-type" : "application/json","X-Auth-Token": token} + url = "https://"+ip+"/api/"+ver+"/"+api + print ("\nExecuting DELETE '%s'\n"%url) + try: + resp= requests.delete(url,headers=headers,params=params,verify = False) + print ("DELETE '%s' Status: "%api,resp.status_code,'\n') + return(resp) + except: + print ("Something wrong with DELETE /",api) + sys.exit() From 7bcc6b3b334b28cadc1fba00870b8a41b47b5020 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 24 Jun 2020 15:14:28 +0700 Subject: [PATCH 28/44] Add files via upload --- Parse API Data Formats/initial/Pipfile | 11 ++ .../initial/__pycache__/helper.cpython-38.pyc | Bin 0 -> 1309 bytes Parse API Data Formats/initial/helper.py | 38 ++++ Parse API Data Formats/initial/item.xml | 15 ++ Parse API Data Formats/initial/lab01.py | 141 ++++++++++++++ Parse API Data Formats/initial/user.xml | 22 +++ Parse API Data Formats/initial/user.yaml | 16 ++ .../solution/lab01(edited).py | 173 ++++++++++++++++++ 8 files changed, 416 insertions(+) create mode 100644 Parse API Data Formats/initial/Pipfile create mode 100644 Parse API Data Formats/initial/__pycache__/helper.cpython-38.pyc create mode 100644 Parse API Data Formats/initial/helper.py create mode 100644 Parse API Data Formats/initial/item.xml create mode 100644 Parse API Data Formats/initial/lab01.py create mode 100644 Parse API Data Formats/initial/user.xml create mode 100644 Parse API Data Formats/initial/user.yaml create mode 100644 Parse API Data Formats/solution/lab01(edited).py diff --git a/Parse API Data Formats/initial/Pipfile b/Parse API Data Formats/initial/Pipfile new file mode 100644 index 0000000..3e8b862 --- /dev/null +++ b/Parse API Data Formats/initial/Pipfile @@ -0,0 +1,11 @@ +[[source]] +name = "pypi" +url = "https://pypi.org/simple" +verify_ssl = true + +[dev-packages] + +[packages] + +[requires] +python_version = "3" diff --git a/Parse API Data Formats/initial/__pycache__/helper.cpython-38.pyc b/Parse API Data Formats/initial/__pycache__/helper.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1184deb2c8b93937498e984d1402c91cb2881d8 GIT binary patch literal 1309 zcmZ`&%}x|S5bo}oS!TywG>U@85Q2$uFPse_1_UuCX5F~rVY1p8rW=`c_J`_5g)Ap{ z5WSf22)@c(J@E>htm=Vf#n_XssjBX-pRcO6>h*}>`uXej$2Fg^-y}>f4~13S<|z`z z6wg_Y$DFg5ObO+kFy$SKSSViwCoJ|f@nXp$@8OnS<9CId87Df}&?A?0}SauH7!)^VFBNE90}SyHrwyl~WW z)OR#ctj$h&6Ag+?#nDa%#>#%u({VLVF4<^11G_6J=6EVm3bZkCVA28TQ_RKaeCL!w zh%V2czgX_PZ?@jP>7)atJFNtamTRq7awD;c+#EnJu||H)&|K@l?hg8$te@E|$ve9` zA8J?{9u%RJq?EEknbeRlUKxLfb;^9{^3MMupn_UVyUUMxn*mmpHALYV3*ZaElV&5JYXp>(MI>c!p!Rd(Yf|p*CwX}S6a&+*fUMUv`$1B3_2rLK0Q!*vO^Lvj-pF1VE=F%nn7DKX+Rj5M=2 z(X+&fF8(QC>!TEmxbjgJ;{<{x+(m1LVqxK&FQ3sAHY#ure=v*WVy4!2vs}5cPm0I| z-NbZE9Hn&N_=X2__@D@K{YB?+pDbK;jcb^B)Df;1b)ZD&Igqy5;841bLz+{Y^|Y&V hS#~OwgT!5)FzXzYUB6QH@G}C + + + + Router + Switch + + + + + Coffee Table + 180 + 80 + + \ No newline at end of file diff --git a/Parse API Data Formats/initial/lab01.py b/Parse API Data Formats/initial/lab01.py new file mode 100644 index 0000000..ddff92b --- /dev/null +++ b/Parse API Data Formats/initial/lab01.py @@ -0,0 +1,141 @@ +# Import modules +import sys +from helper import * + +import xml.etree.ElementTree as ET + +import xml.dom.minidom as MD + +# Main function +if __name__ == "__main__": + ######################################### + # Procedure 1 # + ######################################### + # Add print statement here + + + ######################################### + # Procedure 2 # + ######################################### + print('##################') + print('###### YAML ######') + print('##################') + + # Open the user.yaml file as read only + + # Load the stream using safe_load + + # Print the object type + print("Type of user_yaml variable:") + + print('----------------------') + + # Iterate over the keys of the user_yaml and print them + print('Keys in user_yaml:') + + print('----------------------') + + # Create a new instance of class User + + # Assign values form the user_yaml to the object user + + # Print the user object + print('User object:') + + + ######################################### + # Procedure 3 # + ######################################### + print('##################') + print('###### JSON ######') + print('##################') + + # Create JSON structure from the user object + + # Print the created JSON structure + print('Print user_json:') + + print('----------------------') + + # Create JSON structre with indents and soreted keys + print('JSON with indents and sorted keys') + + + ######################################### + # Procedure 4 # + ######################################### + print('######################') + print('# XML - Element Tree #') + print('######################') + + # Parse the user.xml file + + # Get the root element + + # Print the tags + print('Tags in the XML:') + + print('----------------------') + + # Print the value of id tag + print('id tag value:') + + print('----------------------') + + # Find all elements with the tag address in root + + # Print the adresses in the xml + print('Addresses:') + + print('----------------------') + + # Print the elements in root with their tags and values + print('Print the structure') + + # Parsing XML files with MiniDOM + print('######################') + print('### XML - MiniDOM ####') + print('######################') + + # Parse the user.xml file + + # Print the tags + + print('----------------------') + + # Accessing element value + print('Accessing element value') + + print('----------------------') + + # Print elements from the DOM with tag name 'address' + print('Addresses:') + + print('----------------------') + + # Print the entire structure with printNodes + print('The structure:') + + + ######################################### + # Procedure 5 # + ######################################### + print('######################') + print('# Use Namespaces #') + print('######################') + + # Parse the user.xml file + + # Get the root element + + # Define namespaces + + # Set table as the root element + + # Elements in NS a + print('Elements in NS a:') + + print('----------------------') + + # Elements in NS b + print('Elements in NS b:') \ No newline at end of file diff --git a/Parse API Data Formats/initial/user.xml b/Parse API Data Formats/initial/user.xml new file mode 100644 index 0000000..486163b --- /dev/null +++ b/Parse API Data Formats/initial/user.xml @@ -0,0 +1,22 @@ + + + 3242 + Ray + Smith + 1979-08-15 +
+ 94873 Ledner Rue + Royal Oak + 44663 + OH + 1 +
+
+ 832 William Ave + Elnaville + 17319 + EL + 0 +
+ 18.3 +
\ No newline at end of file diff --git a/Parse API Data Formats/initial/user.yaml b/Parse API Data Formats/initial/user.yaml new file mode 100644 index 0000000..d50eca1 --- /dev/null +++ b/Parse API Data Formats/initial/user.yaml @@ -0,0 +1,16 @@ +id: 3242 +first_name: 'Ray' +last_name: 'Smith' +birth_date: 1979-08-15 +address: + - street: '94873 Ledner Rue' + city: 'Royal Oak' + postal_code: 44663 + state: 'OH' + primary: 1 + - street: '832 William Ave' + city: 'Elnaville' + postal_code: 17319 + state: 'EL' + primary: 0 +score: 18.3 \ No newline at end of file diff --git a/Parse API Data Formats/solution/lab01(edited).py b/Parse API Data Formats/solution/lab01(edited).py new file mode 100644 index 0000000..99c2a81 --- /dev/null +++ b/Parse API Data Formats/solution/lab01(edited).py @@ -0,0 +1,173 @@ +# Import modules +import sys +from helper import * +from ruamel import yaml +import json + +import xml.etree.ElementTree as ET + +import xml.dom.minidom as MD + +# Main function +if __name__ == "__main__": + ######################################### + # Procedure 1 # + ######################################### + # Add print statement here + print('Devnet') + + + ######################################### + # Procedure 2 # + ######################################### + print('##################') + print('###### YAML ######') + print('##################') + + # Open the user.yaml file as read only + with open('user.yaml','r') as stream: + # Load the stream using safe_load + user_yaml = yaml.safe_load(stream) + + # Print the object type + print("Type of user_yaml variable:") + print(type(user_yaml)) + print('----------------------') + + # Iterate over the keys of the user_yaml and print them + print('Keys in user_yaml:') + for key in user_yaml: + print(key) + print('----------------------') + + # Create a new instance of class User + user = User() + # Assign values form the user_yaml to the object user + user.id = user_yaml['id'] + user.first_name = user_yaml['first_name'] + user.last_name = user_yaml['last_name'] + user.birth_date = user_yaml['birth_date'] + user.address = user_yaml['address'] + user.score = user_yaml['score'] + # Print the user object + print('User object:') + print(user) + + ######################################### + # Procedure 3 # + ######################################### + print('##################') + print('###### JSON ######') + print('##################') + + # Create JSON structure from the user object + user_json = json.dumps(user, default = serializeUser) + # Print the created JSON structure + print('Print user_json:') + print(user_json) + print('----------------------') + + # Create JSON structre with indents and soreted keys + print('JSON with indents and sorted keys') + user_json = json.dumps(user, default = serializeUser, indent = 4, sort_keys = True) + print(user_json) + # Print to file user.json + file = open("user.json","w") + file.write(user_json) + file.close() + ######################################### + # Procedure 4 # + ######################################### + print('######################') + print('# XML - Element Tree #') + print('######################') + + # Parse the user.xml file + tree = ET.parse('user.xml') + # Get the root element + root = tree.getroot() + # Print the tags + print('Tags in the XML:') + for element in root: + print(element.tag) + print('----------------------') + + # Print the value of id tag + print('id tag value:') + print(root.find('id').text) + print('----------------------') + + # Find all elements with the tag address in root + addresses = root.findall('address') + # Print the adresses in the xml + print('Addresses:') + for address in addresses: + for i in address: + print(i.tag + ':' + i.text) + print('----------------------') + + # Print the elements in root with their tags and values + print('Print the structure') + for k in root.iter(): #Lấy từng phần tử của nó tại thời điểm nhất định + print(k.tag + ':' + k.text) + # Parsing XML files with MiniDOM + print('######################') + print('### XML - MiniDOM ####') + print('######################') + + # Parse the user.xml file + dom = MD.parse('user.xml') + # Print the tags + print('Tags in the XML:') + for node in dom.childNodes: + printTags(node.childNodes) + print('----------------------') + + # Accessing element value + print('Accessing element value') + idElements = dom.getElementsByTagName('id') + print(idElements) + elementId= idElements.item(0) + print(elementId.childNodes) + idValue = elementId.firstChild.data + print(idValue) + print('----------------------') + + # Print elements from the DOM with tag name 'address' + print('Addresses:') + for node in dom.getElementsByTagName('address'): + printNodes(node.childNodes) + print('----------------------') + + # Print the entire structure with printNodes + print('The structure:') + for node in dom.childNodes: + printNodes(node.childNodes) + + ######################################### + # Procedure 5 # + ######################################### + print('######################') + print('# Use Namespaces #') + print('######################') + + # Parse the item.xml file + itemTree = ET.parse('item.xml') + # Get the root element + root = itemTree.getroot() + # Define namespaces + namespaces = {'a':'https://www.example.com/network','b':'https://www.example.com/furniture'} + # Set table as the root element + elementsInNSa = root.findall('a:table',namespaces) + elementsInNSb = root.findall('b:table',namespaces) + # Elements in NS a + print('Elements in NS a:') + for e in elementsInNSa: + for i in e.iter(): + print(i.tag + ':'+ i.text) + print('----------------------') + + # Elements in NS b + print('Elements in NS b:') + for element in list(elementsInNSb[0]): + print(element.tag + ":" + element.text) From 667c2b1d13946207bc0079344cc27fb43003b250 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 24 Jun 2020 15:15:01 +0700 Subject: [PATCH 29/44] Delete helper.py --- Parse API Data Formats/helper.py | 38 -------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 Parse API Data Formats/helper.py diff --git a/Parse API Data Formats/helper.py b/Parse API Data Formats/helper.py deleted file mode 100644 index d987155..0000000 --- a/Parse API Data Formats/helper.py +++ /dev/null @@ -1,38 +0,0 @@ -# Helper module with User class and additional functions -from datetime import date - -## User Class -class User: - def __init__(self): - self.id = None - self.first_name = None - self.last_name = None - self.birth_date = None - self.address = None - self.score = None - - # Print the object - def __repr__(self): - return str(self.__dict__) - -# User object serialization -def serializeUser(object): - if isinstance(object, User): - return object.__dict__ - - if isinstance(object, date): - return object.__str__() - -## Used For MiniDom -# Print the tags of a nodeList object -def printTags(nodeList): - for node in nodeList: - if node.nodeName != '#text': - print(node.nodeName) - -# Recursively print the node list childern's name (tag) and its value -def printNodes (nodeList, level=0): - for node in nodeList: - if node.nodeName != '#text': - print( (" ")*level + node.nodeName + ':' + node.firstChild.data) - printNodes(node.childNodes, level+1) \ No newline at end of file From ff1d75fe0ed339c06f4a11a889196062a04ec560 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 24 Jun 2020 15:15:25 +0700 Subject: [PATCH 30/44] Delete item.xml --- Parse API Data Formats/item.xml | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 Parse API Data Formats/item.xml diff --git a/Parse API Data Formats/item.xml b/Parse API Data Formats/item.xml deleted file mode 100644 index 90ffb4d..0000000 --- a/Parse API Data Formats/item.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - Router - Switch - - - - - Coffee Table - 180 - 80 - - \ No newline at end of file From 65c6254f237795ef792e8d60ad68f1a898e0b62d Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 24 Jun 2020 15:16:01 +0700 Subject: [PATCH 31/44] Delete lab01(edited).py --- Parse API Data Formats/lab01(edited).py | 173 ------------------------ 1 file changed, 173 deletions(-) delete mode 100644 Parse API Data Formats/lab01(edited).py diff --git a/Parse API Data Formats/lab01(edited).py b/Parse API Data Formats/lab01(edited).py deleted file mode 100644 index 99c2a81..0000000 --- a/Parse API Data Formats/lab01(edited).py +++ /dev/null @@ -1,173 +0,0 @@ -# Import modules -import sys -from helper import * -from ruamel import yaml -import json - -import xml.etree.ElementTree as ET - -import xml.dom.minidom as MD - -# Main function -if __name__ == "__main__": - ######################################### - # Procedure 1 # - ######################################### - # Add print statement here - print('Devnet') - - - ######################################### - # Procedure 2 # - ######################################### - print('##################') - print('###### YAML ######') - print('##################') - - # Open the user.yaml file as read only - with open('user.yaml','r') as stream: - # Load the stream using safe_load - user_yaml = yaml.safe_load(stream) - - # Print the object type - print("Type of user_yaml variable:") - print(type(user_yaml)) - print('----------------------') - - # Iterate over the keys of the user_yaml and print them - print('Keys in user_yaml:') - for key in user_yaml: - print(key) - print('----------------------') - - # Create a new instance of class User - user = User() - # Assign values form the user_yaml to the object user - user.id = user_yaml['id'] - user.first_name = user_yaml['first_name'] - user.last_name = user_yaml['last_name'] - user.birth_date = user_yaml['birth_date'] - user.address = user_yaml['address'] - user.score = user_yaml['score'] - # Print the user object - print('User object:') - print(user) - - ######################################### - # Procedure 3 # - ######################################### - print('##################') - print('###### JSON ######') - print('##################') - - # Create JSON structure from the user object - user_json = json.dumps(user, default = serializeUser) - # Print the created JSON structure - print('Print user_json:') - print(user_json) - print('----------------------') - - # Create JSON structre with indents and soreted keys - print('JSON with indents and sorted keys') - user_json = json.dumps(user, default = serializeUser, indent = 4, sort_keys = True) - print(user_json) - # Print to file user.json - file = open("user.json","w") - file.write(user_json) - file.close() - ######################################### - # Procedure 4 # - ######################################### - print('######################') - print('# XML - Element Tree #') - print('######################') - - # Parse the user.xml file - tree = ET.parse('user.xml') - # Get the root element - root = tree.getroot() - # Print the tags - print('Tags in the XML:') - for element in root: - print(element.tag) - print('----------------------') - - # Print the value of id tag - print('id tag value:') - print(root.find('id').text) - print('----------------------') - - # Find all elements with the tag address in root - addresses = root.findall('address') - # Print the adresses in the xml - print('Addresses:') - for address in addresses: - for i in address: - print(i.tag + ':' + i.text) - print('----------------------') - - # Print the elements in root with their tags and values - print('Print the structure') - for k in root.iter(): #Lấy từng phần tử của nó tại thời điểm nhất định - print(k.tag + ':' + k.text) - # Parsing XML files with MiniDOM - print('######################') - print('### XML - MiniDOM ####') - print('######################') - - # Parse the user.xml file - dom = MD.parse('user.xml') - # Print the tags - print('Tags in the XML:') - for node in dom.childNodes: - printTags(node.childNodes) - print('----------------------') - - # Accessing element value - print('Accessing element value') - idElements = dom.getElementsByTagName('id') - print(idElements) - elementId= idElements.item(0) - print(elementId.childNodes) - idValue = elementId.firstChild.data - print(idValue) - print('----------------------') - - # Print elements from the DOM with tag name 'address' - print('Addresses:') - for node in dom.getElementsByTagName('address'): - printNodes(node.childNodes) - print('----------------------') - - # Print the entire structure with printNodes - print('The structure:') - for node in dom.childNodes: - printNodes(node.childNodes) - - ######################################### - # Procedure 5 # - ######################################### - print('######################') - print('# Use Namespaces #') - print('######################') - - # Parse the item.xml file - itemTree = ET.parse('item.xml') - # Get the root element - root = itemTree.getroot() - # Define namespaces - namespaces = {'a':'https://www.example.com/network','b':'https://www.example.com/furniture'} - # Set table as the root element - elementsInNSa = root.findall('a:table',namespaces) - elementsInNSb = root.findall('b:table',namespaces) - # Elements in NS a - print('Elements in NS a:') - for e in elementsInNSa: - for i in e.iter(): - print(i.tag + ':'+ i.text) - print('----------------------') - - # Elements in NS b - print('Elements in NS b:') - for element in list(elementsInNSb[0]): - print(element.tag + ":" + element.text) From 62c32bd9be0a1539951ccb2053aeb3c080f92744 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 24 Jun 2020 15:16:16 +0700 Subject: [PATCH 32/44] Delete lab01.py --- Parse API Data Formats/lab01.py | 169 -------------------------------- 1 file changed, 169 deletions(-) delete mode 100644 Parse API Data Formats/lab01.py diff --git a/Parse API Data Formats/lab01.py b/Parse API Data Formats/lab01.py deleted file mode 100644 index 31b1937..0000000 --- a/Parse API Data Formats/lab01.py +++ /dev/null @@ -1,169 +0,0 @@ -# Import modules -import sys -from helper import * -from ruamel import yaml -import json - -import xml.etree.ElementTree as ET - -import xml.dom.minidom as MD - -# Main function -if __name__ == "__main__": - ######################################### - # Procedure 1 # - ######################################### - # Add print statement here - print('Devnet') - - - ######################################### - # Procedure 2 # - ######################################### - print('##################') - print('###### YAML ######') - print('##################') - - # Open the user.yaml file as read only - with open('user.yaml','r') as stream: - # Load the stream using safe_load - user_yaml = yaml.safe_load(stream) - - # Print the object type - print("Type of user_yaml variable:") - print(type(user_yaml)) - print('----------------------') - - # Iterate over the keys of the user_yaml and print them - print('Keys in user_yaml:') - for key in user_yaml: - print(key) - print('----------------------') - - # Create a new instance of class User - user = User() - # Assign values form the user_yaml to the object user - user.id = user_yaml['id'] - user.first_name = user_yaml['first_name'] - user.last_name = user_yaml['last_name'] - user.birth_date = user_yaml['birth_date'] - user.address = user_yaml['address'] - user.score = user_yaml['score'] - # Print the user object - print('User object:') - print(user) - - ######################################### - # Procedure 3 # - ######################################### - print('##################') - print('###### JSON ######') - print('##################') - - # Create JSON structure from the user object - user_json = json.dumps(user, default = serializeUser) - # Print the created JSON structure - print('Print user_json:') - print(user_json) - print('----------------------') - - # Create JSON structre with indents and soreted keys - print('JSON with indents and sorted keys') - user_json = json.dumps(user, default = serializeUser, indent = 4, sort_keys = True) - print(user_json) - ######################################### - # Procedure 4 # - ######################################### - print('######################') - print('# XML - Element Tree #') - print('######################') - - # Parse the user.xml file - tree = ET.parse('user.xml') - # Get the root element - root = tree.getroot() - # Print the tags - print('Tags in the XML:') - for element in root: - print(element.tag) - print('----------------------') - - # Print the value of id tag - print('id tag value:') - print(root.find('id').text) - print('----------------------') - - # Find all elements with the tag address in root - addresses = root.findall('address') - # Print the adresses in the xml - print('Addresses:') - for address in addresses: - for i in address: - print(i.tag + ':' + i.text) - print('----------------------') - - # Print the elements in root with their tags and values - print('Print the structure') - for k in root.iter(): - print(k.tag + ':' + k.text) - # Parsing XML files with MiniDOM - print('######################') - print('### XML - MiniDOM ####') - print('######################') - - # Parse the user.xml file - dom = MD.parse('user.xml') - # Print the tags - print('Tags in the XML:') - for node in dom.childNodes: - printTags(node.childNodes) - print('----------------------') - - # Accessing element value - print('Accessing element value') - idElements = dom.getElementsByTagName('id') - print(idElements) - elementId= idElements.item(0) - print(elementId.childNodes) - idValue = elementId.firstChild.data - print(idValue) - print('----------------------') - - # Print elements from the DOM with tag name 'address' - print('Addresses:') - for node in dom.getElementsByTagName('address'): - printNodes(node.childNodes) - print('----------------------') - - # Print the entire structure with printNodes - print('The structure:') - for node in dom.childNodes: - printNodes(node.childNodes) - - ######################################### - # Procedure 5 # - ######################################### - print('######################') - print('# Use Namespaces #') - print('######################') - - # Parse the user.xml file - itemTree = ET.parse('item.xml') - # Get the root element - root = itemTree.getroot() - # Define namespaces - namespaces = {'a':'https://www.example.com/network','b':'https://www.example.com/furniture'} - # Set table as the root element - elementsInNSa = root.findall('a:table',namespaces) - elementsInNSb = root.findall('b:table',namespaces) - # Elements in NS a - print('Elements in NS a:') - for e in elementsInNSa: - for i in e.iter(): - print(i.tag + ':'+ i.text) - print('----------------------') - - # Elements in NS b - print('Elements in NS b:') - for element in list(elementsInNSb[0]): - print(element.tag + ":" + element.text) From 92e2d9e3920b5c19c47213d2bbb287e75f17e1ff Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 24 Jun 2020 15:16:27 +0700 Subject: [PATCH 33/44] Delete user.xml --- Parse API Data Formats/user.xml | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 Parse API Data Formats/user.xml diff --git a/Parse API Data Formats/user.xml b/Parse API Data Formats/user.xml deleted file mode 100644 index 486163b..0000000 --- a/Parse API Data Formats/user.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - 3242 - Ray - Smith - 1979-08-15 -
- 94873 Ledner Rue - Royal Oak - 44663 - OH - 1 -
-
- 832 William Ave - Elnaville - 17319 - EL - 0 -
- 18.3 -
\ No newline at end of file From a55ae53a122b84502011aa556a2d4dc5f3df5bf6 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 24 Jun 2020 15:16:39 +0700 Subject: [PATCH 34/44] Delete user.yaml --- Parse API Data Formats/user.yaml | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 Parse API Data Formats/user.yaml diff --git a/Parse API Data Formats/user.yaml b/Parse API Data Formats/user.yaml deleted file mode 100644 index d50eca1..0000000 --- a/Parse API Data Formats/user.yaml +++ /dev/null @@ -1,16 +0,0 @@ -id: 3242 -first_name: 'Ray' -last_name: 'Smith' -birth_date: 1979-08-15 -address: - - street: '94873 Ledner Rue' - city: 'Royal Oak' - postal_code: 44663 - state: 'OH' - primary: 1 - - street: '832 William Ave' - city: 'Elnaville' - postal_code: 17319 - state: 'EL' - primary: 0 -score: 18.3 \ No newline at end of file From a4e1c755bce18b1927955ecd202037c36a87d393 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Tue, 7 Jul 2020 20:40:10 +0700 Subject: [PATCH 35/44] Add files via upload --- Token.py | 1 + Webex API.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 Token.py create mode 100644 Webex API.py diff --git a/Token.py b/Token.py new file mode 100644 index 0000000..709a539 --- /dev/null +++ b/Token.py @@ -0,0 +1 @@ +access_token = "ZDk3NTM1OWMtMTBjMy00YTE1LWE2OWMtNjUyZjdkZDRkZjFmMDdhMWMzZTAtZjNj_PF84_consumer" diff --git a/Webex API.py b/Webex API.py new file mode 100644 index 0000000..3a7e5fc --- /dev/null +++ b/Webex API.py @@ -0,0 +1,61 @@ +import requests +import sys +import Token + +url = "https://api.ciscospark.com/v1/" + +def get_room(url=url, access_token = Token.access_token): + url = url + 'rooms' + headers = {"Content-type" : "application/json", "Authorization" : "Bearer " + access_token} + queryParams = {"sortBy" : "lastactivity", "max" : "2"} + response = requests.get(url=url, headers=headers, params=queryParams) + + print("Thong tin ve cac phong chat:") + print("Status: " + str(response.status_code)) + return response.text + +def post_message(url=url, access_token = Token.access_token): + url = url + 'messages' + message = input("Nhap tin nhan muon gui:") + headers = {"Content-type" : "application/json", "Authorization" : "Bearer " + access_token} + body = {"toPersonEmail" : "hotuanhoanh8@webex.bot", "text" : "" + message} + response = requests.post(url=url, json=body, headers=headers) + + print("Tin nhan dang gui di...") + print("Status: " + str(response.status_code)) + if response.status_code == 200: + print("Tin nhan gui thanh cong") + else: + print("Xay ra loi") + return response.text + +def menu(): + print("\n******************************************************\n") + print("\t\tBai thuc hanh Webex API\nChon chuc nang can thuc hien:") + print("1.Lay thong tin ve cac phong chat cua token vua nhap") + print("2.Gui tin nhan") + print("0.Thoat") + choice = int(input("Nhap so cua chuc nang muon chon:")) + print("\n=================================") + print("Dang xu ly") + print("=================================\n") + return choice + +def main(): + while True: + choice = menu() + if choice == 0: + print("Thoat chuong trinh") + break + elif choice == 1: + result = get_room() + print(result) + elif choice == 2: + result = post_message() + print(result) + else: + print("Ban nhap so sai, moi chon lai") + print("========================================") + +if __name__ == '__main__': + sys.exit(main()) From d74440b952733ffa53fa38c24887a7c6d4fc24f0 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 8 Jul 2020 09:12:49 +0700 Subject: [PATCH 36/44] Delete Token.py --- Token.py | 1 - 1 file changed, 1 deletion(-) delete mode 100644 Token.py diff --git a/Token.py b/Token.py deleted file mode 100644 index 709a539..0000000 --- a/Token.py +++ /dev/null @@ -1 +0,0 @@ -access_token = "ZDk3NTM1OWMtMTBjMy00YTE1LWE2OWMtNjUyZjdkZDRkZjFmMDdhMWMzZTAtZjNj_PF84_consumer" From 91ee35aa09de8f629379365264a05418103d39de Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 8 Jul 2020 09:13:03 +0700 Subject: [PATCH 37/44] Delete Webex API.py --- Webex API.py | 61 ---------------------------------------------------- 1 file changed, 61 deletions(-) delete mode 100644 Webex API.py diff --git a/Webex API.py b/Webex API.py deleted file mode 100644 index 3a7e5fc..0000000 --- a/Webex API.py +++ /dev/null @@ -1,61 +0,0 @@ -import requests -import sys -import Token - -url = "https://api.ciscospark.com/v1/" - -def get_room(url=url, access_token = Token.access_token): - url = url + 'rooms' - headers = {"Content-type" : "application/json", "Authorization" : "Bearer " + access_token} - queryParams = {"sortBy" : "lastactivity", "max" : "2"} - response = requests.get(url=url, headers=headers, params=queryParams) - - print("Thong tin ve cac phong chat:") - print("Status: " + str(response.status_code)) - return response.text - -def post_message(url=url, access_token = Token.access_token): - url = url + 'messages' - message = input("Nhap tin nhan muon gui:") - headers = {"Content-type" : "application/json", "Authorization" : "Bearer " + access_token} - body = {"toPersonEmail" : "hotuanhoanh8@webex.bot", "text" : "" + message} - response = requests.post(url=url, json=body, headers=headers) - - print("Tin nhan dang gui di...") - print("Status: " + str(response.status_code)) - if response.status_code == 200: - print("Tin nhan gui thanh cong") - else: - print("Xay ra loi") - return response.text - -def menu(): - print("\n******************************************************\n") - print("\t\tBai thuc hanh Webex API\nChon chuc nang can thuc hien:") - print("1.Lay thong tin ve cac phong chat cua token vua nhap") - print("2.Gui tin nhan") - print("0.Thoat") - choice = int(input("Nhap so cua chuc nang muon chon:")) - print("\n=================================") - print("Dang xu ly") - print("=================================\n") - return choice - -def main(): - while True: - choice = menu() - if choice == 0: - print("Thoat chuong trinh") - break - elif choice == 1: - result = get_room() - print(result) - elif choice == 2: - result = post_message() - print(result) - else: - print("Ban nhap so sai, moi chon lai") - print("========================================") - -if __name__ == '__main__': - sys.exit(main()) From f3cced1665fb3753fbf0d458231d541d2603e908 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Wed, 8 Jul 2020 09:15:02 +0700 Subject: [PATCH 38/44] Add files via upload --- Webex/Token.py | 1 + Webex/Webex API.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 Webex/Token.py create mode 100644 Webex/Webex API.py diff --git a/Webex/Token.py b/Webex/Token.py new file mode 100644 index 0000000..6affd19 --- /dev/null +++ b/Webex/Token.py @@ -0,0 +1 @@ +access_token = "YzdkZWEzYzItYzcxMC00NmZiLWFkODUtZjkwZjA1MGM1NTllYzZlYmZjOGUtYTYz_PF84_consumer" diff --git a/Webex/Webex API.py b/Webex/Webex API.py new file mode 100644 index 0000000..3a7e5fc --- /dev/null +++ b/Webex/Webex API.py @@ -0,0 +1,61 @@ +import requests +import sys +import Token + +url = "https://api.ciscospark.com/v1/" + +def get_room(url=url, access_token = Token.access_token): + url = url + 'rooms' + headers = {"Content-type" : "application/json", "Authorization" : "Bearer " + access_token} + queryParams = {"sortBy" : "lastactivity", "max" : "2"} + response = requests.get(url=url, headers=headers, params=queryParams) + + print("Thong tin ve cac phong chat:") + print("Status: " + str(response.status_code)) + return response.text + +def post_message(url=url, access_token = Token.access_token): + url = url + 'messages' + message = input("Nhap tin nhan muon gui:") + headers = {"Content-type" : "application/json", "Authorization" : "Bearer " + access_token} + body = {"toPersonEmail" : "hotuanhoanh8@webex.bot", "text" : "" + message} + response = requests.post(url=url, json=body, headers=headers) + + print("Tin nhan dang gui di...") + print("Status: " + str(response.status_code)) + if response.status_code == 200: + print("Tin nhan gui thanh cong") + else: + print("Xay ra loi") + return response.text + +def menu(): + print("\n******************************************************\n") + print("\t\tBai thuc hanh Webex API\nChon chuc nang can thuc hien:") + print("1.Lay thong tin ve cac phong chat cua token vua nhap") + print("2.Gui tin nhan") + print("0.Thoat") + choice = int(input("Nhap so cua chuc nang muon chon:")) + print("\n=================================") + print("Dang xu ly") + print("=================================\n") + return choice + +def main(): + while True: + choice = menu() + if choice == 0: + print("Thoat chuong trinh") + break + elif choice == 1: + result = get_room() + print(result) + elif choice == 2: + result = post_message() + print(result) + else: + print("Ban nhap so sai, moi chon lai") + print("========================================") + +if __name__ == '__main__': + sys.exit(main()) From 9d9e639e5cb416a3370a018e09b8c64f99e2cc59 Mon Sep 17 00:00:00 2001 From: BlackDrag0n Date: Wed, 8 Jul 2020 14:48:52 +0700 Subject: [PATCH 39/44] Them bai lab netmiko 2 - kiem tra vlan da gan interface --- netmiko/check_vlan_int/device_list.py | 39 +++++++++++++++++ netmiko/check_vlan_int/main.py | 61 +++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100755 netmiko/check_vlan_int/device_list.py create mode 100755 netmiko/check_vlan_int/main.py diff --git a/netmiko/check_vlan_int/device_list.py b/netmiko/check_vlan_int/device_list.py new file mode 100755 index 0000000..0c30178 --- /dev/null +++ b/netmiko/check_vlan_int/device_list.py @@ -0,0 +1,39 @@ +from getpass import getpass +#passwd=getpass("Nhap mat khau SSH: ") +passwd="123" +sw1 = { + "device_type":"cisco_ios", + "ip":"192.168.225.138", + "username":"admin", + "password":passwd, + "secret":"321" + } +sw2 = { + "device_type":"cisco_ios", + "ip":"192.168.225.135", + "username":"admin", + "password":passwd, + "secret":"321" + } +sw3 = { + "device_type":"cisco_ios", + "ip":"192.168.225.136", + "username":"admin", + "password":passwd, + "secret":"321" + } +sw4 = { + "device_type":"cisco_ios", + "ip":"10.215.26.233", + "username":"admin", + "password":passwd, + "secret":"321" +} +sw5 = { + "device_type":"cisco_ios", + "ip":"10.215.26.233", + "username":"admin", + "password":passwd, + "secret":"321" + } +device_list=[sw1] \ No newline at end of file diff --git a/netmiko/check_vlan_int/main.py b/netmiko/check_vlan_int/main.py new file mode 100755 index 0000000..579d6ab --- /dev/null +++ b/netmiko/check_vlan_int/main.py @@ -0,0 +1,61 @@ +from netmiko import ConnectHandler +from multiprocessing import Process +from device_list import device_list as devices #Nhap danh sach thiet bi ben file device_list voi ten bien la device +from ntc_templates.parse import parse_output +def show_vlan(device,id_vlan): + ssh=ConnectHandler(**device) + ssh.enable() + data=ssh.send_command("show vlan") + data_parse=parse_output(platform="cisco_ios",command="show vlan",data=data) + + ''' + ###data_parse output### + [{'interfaces': ['Et0/1', 'Et0/2', 'Et0/3'], + 'name': 'default', + 'status': 'active', + 'vlan_id': '1'}, + {'interfaces': [], + 'name': 'fddi-default', + 'status': 'act/unsup', + 'vlan_id': '1002'}, + {'interfaces': [], + 'name': 'token-ring-default', + 'status': 'act/unsup', + 'vlan_id': '1003'}, + {'interfaces': [], + 'name': 'fddinet-default', + 'status': 'act/unsup', + 'vlan_id': '1004'}, + {'interfaces': [], + 'name': 'trnet-default', + 'status': 'act/unsup', + 'vlan_id': '1005'}] + ''' + vlan={} + ###Command + access_int=["int range e0/1-2","switchport access vlan " + id_vlan] + ###tao ra tu dien co dang vlan={"vlan_ID":"Interfaces"} + for i in data_parse: + vlan[i["vlan_id"]]=i["interfaces"] + ###Tao ham kiem tra interface cua vlan + try: + if "Et0/2" and "Et0/1" in vlan[id_vlan]: + print("vlan {} da duoc gan cac cong e0/1 va e0/2".format(id_vlan)) + ssh.disconnect() + else: + print("Vlan {} chua duoc gan cac cong e0/1 va e0/2".format(id_vlan)) + print(ssh.send_config_set(access_int)) + print(ssh.send_command("show vlan br")) + ssh.disconnect() + except KeyError: #Neu vlan id ko co trong tu dien vlan o tren se bao loi KeyError + print("Khong co vlan tien hanh tao vlan va gan cong") + print(ssh.send_config_set(access_int)) + print(ssh.send_command("show vlan br")) + ssh.disconnect() +def main(): + id_vlan=input("Nhap vlan muon kiem tra: ") + for device in devices: + my_proc=Process(target=show_vlan,args=(device,id_vlan,)) + my_proc.start() +if __name__ == "__main__": + main() From ae883d1cda6334ca0953b1245e7850432d630b30 Mon Sep 17 00:00:00 2001 From: BlackDrag0n Date: Wed, 8 Jul 2020 14:55:01 +0700 Subject: [PATCH 40/44] change name netmiko folder to netmiko_example --- netmiko_example/check_vlan_int/device_list.py | 39 ++++++++++++ netmiko_example/check_vlan_int/main.py | 61 +++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100755 netmiko_example/check_vlan_int/device_list.py create mode 100755 netmiko_example/check_vlan_int/main.py diff --git a/netmiko_example/check_vlan_int/device_list.py b/netmiko_example/check_vlan_int/device_list.py new file mode 100755 index 0000000..0c30178 --- /dev/null +++ b/netmiko_example/check_vlan_int/device_list.py @@ -0,0 +1,39 @@ +from getpass import getpass +#passwd=getpass("Nhap mat khau SSH: ") +passwd="123" +sw1 = { + "device_type":"cisco_ios", + "ip":"192.168.225.138", + "username":"admin", + "password":passwd, + "secret":"321" + } +sw2 = { + "device_type":"cisco_ios", + "ip":"192.168.225.135", + "username":"admin", + "password":passwd, + "secret":"321" + } +sw3 = { + "device_type":"cisco_ios", + "ip":"192.168.225.136", + "username":"admin", + "password":passwd, + "secret":"321" + } +sw4 = { + "device_type":"cisco_ios", + "ip":"10.215.26.233", + "username":"admin", + "password":passwd, + "secret":"321" +} +sw5 = { + "device_type":"cisco_ios", + "ip":"10.215.26.233", + "username":"admin", + "password":passwd, + "secret":"321" + } +device_list=[sw1] \ No newline at end of file diff --git a/netmiko_example/check_vlan_int/main.py b/netmiko_example/check_vlan_int/main.py new file mode 100755 index 0000000..579d6ab --- /dev/null +++ b/netmiko_example/check_vlan_int/main.py @@ -0,0 +1,61 @@ +from netmiko import ConnectHandler +from multiprocessing import Process +from device_list import device_list as devices #Nhap danh sach thiet bi ben file device_list voi ten bien la device +from ntc_templates.parse import parse_output +def show_vlan(device,id_vlan): + ssh=ConnectHandler(**device) + ssh.enable() + data=ssh.send_command("show vlan") + data_parse=parse_output(platform="cisco_ios",command="show vlan",data=data) + + ''' + ###data_parse output### + [{'interfaces': ['Et0/1', 'Et0/2', 'Et0/3'], + 'name': 'default', + 'status': 'active', + 'vlan_id': '1'}, + {'interfaces': [], + 'name': 'fddi-default', + 'status': 'act/unsup', + 'vlan_id': '1002'}, + {'interfaces': [], + 'name': 'token-ring-default', + 'status': 'act/unsup', + 'vlan_id': '1003'}, + {'interfaces': [], + 'name': 'fddinet-default', + 'status': 'act/unsup', + 'vlan_id': '1004'}, + {'interfaces': [], + 'name': 'trnet-default', + 'status': 'act/unsup', + 'vlan_id': '1005'}] + ''' + vlan={} + ###Command + access_int=["int range e0/1-2","switchport access vlan " + id_vlan] + ###tao ra tu dien co dang vlan={"vlan_ID":"Interfaces"} + for i in data_parse: + vlan[i["vlan_id"]]=i["interfaces"] + ###Tao ham kiem tra interface cua vlan + try: + if "Et0/2" and "Et0/1" in vlan[id_vlan]: + print("vlan {} da duoc gan cac cong e0/1 va e0/2".format(id_vlan)) + ssh.disconnect() + else: + print("Vlan {} chua duoc gan cac cong e0/1 va e0/2".format(id_vlan)) + print(ssh.send_config_set(access_int)) + print(ssh.send_command("show vlan br")) + ssh.disconnect() + except KeyError: #Neu vlan id ko co trong tu dien vlan o tren se bao loi KeyError + print("Khong co vlan tien hanh tao vlan va gan cong") + print(ssh.send_config_set(access_int)) + print(ssh.send_command("show vlan br")) + ssh.disconnect() +def main(): + id_vlan=input("Nhap vlan muon kiem tra: ") + for device in devices: + my_proc=Process(target=show_vlan,args=(device,id_vlan,)) + my_proc.start() +if __name__ == "__main__": + main() From 1c2657e4fed95effcf1be5501feb7e50f97b3a66 Mon Sep 17 00:00:00 2001 From: BlackDrag0n Date: Wed, 8 Jul 2020 14:58:56 +0700 Subject: [PATCH 41/44] change name netmiko folder to netmiko_example and del old folder --- netmiko/check_vlan_int/device_list.py | 39 ----------------- netmiko/check_vlan_int/main.py | 61 --------------------------- 2 files changed, 100 deletions(-) delete mode 100755 netmiko/check_vlan_int/device_list.py delete mode 100755 netmiko/check_vlan_int/main.py diff --git a/netmiko/check_vlan_int/device_list.py b/netmiko/check_vlan_int/device_list.py deleted file mode 100755 index 0c30178..0000000 --- a/netmiko/check_vlan_int/device_list.py +++ /dev/null @@ -1,39 +0,0 @@ -from getpass import getpass -#passwd=getpass("Nhap mat khau SSH: ") -passwd="123" -sw1 = { - "device_type":"cisco_ios", - "ip":"192.168.225.138", - "username":"admin", - "password":passwd, - "secret":"321" - } -sw2 = { - "device_type":"cisco_ios", - "ip":"192.168.225.135", - "username":"admin", - "password":passwd, - "secret":"321" - } -sw3 = { - "device_type":"cisco_ios", - "ip":"192.168.225.136", - "username":"admin", - "password":passwd, - "secret":"321" - } -sw4 = { - "device_type":"cisco_ios", - "ip":"10.215.26.233", - "username":"admin", - "password":passwd, - "secret":"321" -} -sw5 = { - "device_type":"cisco_ios", - "ip":"10.215.26.233", - "username":"admin", - "password":passwd, - "secret":"321" - } -device_list=[sw1] \ No newline at end of file diff --git a/netmiko/check_vlan_int/main.py b/netmiko/check_vlan_int/main.py deleted file mode 100755 index 579d6ab..0000000 --- a/netmiko/check_vlan_int/main.py +++ /dev/null @@ -1,61 +0,0 @@ -from netmiko import ConnectHandler -from multiprocessing import Process -from device_list import device_list as devices #Nhap danh sach thiet bi ben file device_list voi ten bien la device -from ntc_templates.parse import parse_output -def show_vlan(device,id_vlan): - ssh=ConnectHandler(**device) - ssh.enable() - data=ssh.send_command("show vlan") - data_parse=parse_output(platform="cisco_ios",command="show vlan",data=data) - - ''' - ###data_parse output### - [{'interfaces': ['Et0/1', 'Et0/2', 'Et0/3'], - 'name': 'default', - 'status': 'active', - 'vlan_id': '1'}, - {'interfaces': [], - 'name': 'fddi-default', - 'status': 'act/unsup', - 'vlan_id': '1002'}, - {'interfaces': [], - 'name': 'token-ring-default', - 'status': 'act/unsup', - 'vlan_id': '1003'}, - {'interfaces': [], - 'name': 'fddinet-default', - 'status': 'act/unsup', - 'vlan_id': '1004'}, - {'interfaces': [], - 'name': 'trnet-default', - 'status': 'act/unsup', - 'vlan_id': '1005'}] - ''' - vlan={} - ###Command - access_int=["int range e0/1-2","switchport access vlan " + id_vlan] - ###tao ra tu dien co dang vlan={"vlan_ID":"Interfaces"} - for i in data_parse: - vlan[i["vlan_id"]]=i["interfaces"] - ###Tao ham kiem tra interface cua vlan - try: - if "Et0/2" and "Et0/1" in vlan[id_vlan]: - print("vlan {} da duoc gan cac cong e0/1 va e0/2".format(id_vlan)) - ssh.disconnect() - else: - print("Vlan {} chua duoc gan cac cong e0/1 va e0/2".format(id_vlan)) - print(ssh.send_config_set(access_int)) - print(ssh.send_command("show vlan br")) - ssh.disconnect() - except KeyError: #Neu vlan id ko co trong tu dien vlan o tren se bao loi KeyError - print("Khong co vlan tien hanh tao vlan va gan cong") - print(ssh.send_config_set(access_int)) - print(ssh.send_command("show vlan br")) - ssh.disconnect() -def main(): - id_vlan=input("Nhap vlan muon kiem tra: ") - for device in devices: - my_proc=Process(target=show_vlan,args=(device,id_vlan,)) - my_proc.start() -if __name__ == "__main__": - main() From f23afd49b7c0cc3696a3754712fd5542a6787a99 Mon Sep 17 00:00:00 2001 From: BlackDrag0n Date: Fri, 17 Jul 2020 23:56:48 +0700 Subject: [PATCH 42/44] Add check version bang netmiko --- netmiko_example/check_version/device_list.py | 29 ++++++++++++++++++ netmiko_example/check_version/main.py | 32 ++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100755 netmiko_example/check_version/device_list.py create mode 100755 netmiko_example/check_version/main.py diff --git a/netmiko_example/check_version/device_list.py b/netmiko_example/check_version/device_list.py new file mode 100755 index 0000000..9a826bc --- /dev/null +++ b/netmiko_example/check_version/device_list.py @@ -0,0 +1,29 @@ +sw1 = { + "device_type":"cisco_ios", + "ip":"10.215.26.170", + "username":"admin", + "password":"vnpro@149", + #"secret":"321" + } +sw2 = { + "device_type":"cisco_ios", + "ip":"10.215.26.171", + "username":"admin", + "password":"vnpro@149", + #"secret":"321" + } +sw3 = { + "device_type":"cisco_ios", + "ip":"10.215.26.170", + "username":"admin", + "password":"vnpro@149", + #"secret":"321" + } +sw4 = { + "device_type":"cisco_ios", + "ip":"10.215.26.173", + "username":"admin", + "password":"vnpro@149", + #"secret":"321" + } +devices=[sw3] \ No newline at end of file diff --git a/netmiko_example/check_version/main.py b/netmiko_example/check_version/main.py new file mode 100755 index 0000000..50f9612 --- /dev/null +++ b/netmiko_example/check_version/main.py @@ -0,0 +1,32 @@ +from netmiko import ConnectHandler +from multiprocessing import Process +from ntc_templates.parse import parse_output +from device_list import devices #Nhap danh sach thiet bi ben file device_list +def check_ver(device): + ssh=ConnectHandler(**device) + data=ssh.send_command("show ver") + data_dict=parse_output(platform="cisco_ios",command="show ver",data=data) + '''#Data_dict + [{'config_register': '0x2102', + 'hardware': ['CSR1000V'], + 'hostname': 'CSR1000V', + 'mac': [], + 'reload_reason': 'Unknown reason', + 'rommon': 'IOS-XE', + 'running_image': 'packages.conf', + 'serial': ['97XPYZH1ERC'], + 'uptime': '1 week, 4 days, 19 hours, 36 minutes', + 'version': '16.12.3'}] + ''' + for i in data_dict: + if i["version"] <= "16.12.2": + print("{} IP {} version hien tai {} can update version".format(i["rommon"],device["ip"],i["version"])) + else: + print("{} IP {} version hien tai {} dang o version moi nhat".format(i["rommon"],device["ip"],i["version"])) + ssh.disconnect() +def main(): + for i in devices: + proc=Process(target=check_ver,args=(i,)) + proc.start() +if __name__ == "__main__": + main() \ No newline at end of file From ee2c5b81957ce8e387b60d73b2d5d0cea9c9d602 Mon Sep 17 00:00:00 2001 From: hotuanhoanh8 <55940179+hotuanhoanh8@users.noreply.github.com> Date: Mon, 20 Jul 2020 17:06:45 +0700 Subject: [PATCH 43/44] Update pgpd.py --- Network Controller( APIC-EM)/pgpd.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Network Controller( APIC-EM)/pgpd.py b/Network Controller( APIC-EM)/pgpd.py index 4353861..3347253 100644 --- a/Network Controller( APIC-EM)/pgpd.py +++ b/Network Controller( APIC-EM)/pgpd.py @@ -49,6 +49,19 @@ def get(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME print("Something wrong",api) sys.exit() +def post(ip=controller.APICEM_IP, ver=controller.VERSION, uname=controller.USERNAME, pword=controller.PASSWORD, api='', params=''): + token = get_auth_token(ip,ver,uname,pword) + headers = {"content-type" : "application/json","X-Auth-Token": token} + url = "https://"+ip+"/api/"+ver+"/"+api + print ("\nExecuting POST '%s'\n"%url) + try: + resp= requests.post(url,json.dumps(params),headers=headers,verify = False) + print ("POST '%s' Status: "%api,resp.status_code,'\n') + return(resp) + except: + print ("Something wrong with POST /",api) + sys.exit() + # Tạo hàm put chỉnh sửa thông tin def put(ip=controller.APICEM_IP,ver=controller.VERSION,uname=controller.USERNAME,pword=controller.PASSWORD,api='',params=''): ticket = get_auth_token(ip,ver,uname,pword) From e692f66302a78163faadb7762a96f25ed0ce97c0 Mon Sep 17 00:00:00 2001 From: BlackDrag0n Date: Mon, 27 Jul 2020 16:24:00 +0700 Subject: [PATCH 44/44] Them code scan IOS-XE tren APIC-EM --- APIC-EM_Scan_Device/create_scan.py | 66 ++++++++++++++++++++++++++++++ APIC-EM_Scan_Device/device.py | 20 +++++++++ 2 files changed, 86 insertions(+) create mode 100644 APIC-EM_Scan_Device/create_scan.py create mode 100644 APIC-EM_Scan_Device/device.py diff --git a/APIC-EM_Scan_Device/create_scan.py b/APIC-EM_Scan_Device/create_scan.py new file mode 100644 index 0000000..2e9cc6e --- /dev/null +++ b/APIC-EM_Scan_Device/create_scan.py @@ -0,0 +1,66 @@ +from device import device_list +import json +import requests +import sys +import tabulate +from pprint import pprint +requests.packages.urllib3.disable_warnings() + +def get_auth_token(ip,user,passwd): +#Tạo 1 jsonObject có 2 key username,password có value tương ứng là uname,pword + r_json = { + "username": user, + "password": passwd + } + post_url = "https://{}/api/v1/ticket".format(ip) #khai báo URL để post + headers = {"Content-Type" : "application/json"} #khai báo headers + r=requests.post(post_url,data = json.dumps(r_json),headers = headers,verify=False) #gửi requests đến server và gán response vào biến r + #post là tạo dữ liệu ,post_url là địa chỉ ta muốn gửi đến, + #json.dumps dùng để mã hóa username và password, + #verify=False để không xác thực SSL + r.raise_for_status() # Lấy mã trạng thái, 200 là thành công, 404 là not found + token = r.json()["response"]["serviceTicket"] #Lấy ticket từ r + # Trả về giá trị + return { + "token" : token + } +def scan(ip,user,passwd,token): + ticket=token + headers = {"Content-type":"application/json","X-Auth-Token": ticket['token']} + url = "https://{}/api/v1/discovery".format(ip) + body= { + "name":"Scan CSR1000V", + "ipAddressList":"10.215.26.170-10.215.26.175", + "discoveryType":"Range", + "snmpROCommunity":"vnpro", + "snmpRWCommunity":"vnpro", + "userNameList":["admin"], + "passwordList":["vnpro@149"], + "protocolOrder": "ssh" +} + try: + resp = requests.post(url,headers=headers,params='',data=json.dumps(body),verify=False) + print(resp) #In ra trạng thái + except: + print("Something wrong") + sys.exit() +def show_scan(ip,user,passwd,token): + ticket=token + headers = {"Content-type":"application/json","X-Auth-Token": ticket['token']} + url = "https://{}/api/v1/discovery".format(ip) + resp = requests.get(url,headers=headers,params='',verify=False) + data=resp.json()["response"] + list_discover=[] + #pprint(resp.json()["response"])~ + n=0 + for i in data: + n+=1 + list_discover.append([n,i["name"],i["ipAddressList"],i["id"]]) + return list_discover + print(list_discover) + #print(tabulate(list_discover,headers = ['number','Name','IP Range','ID Job'], tablefmt="rst")) +if __name__ == "__main__": + for i in device_list: + token=get_auth_token(**i) + scan(i['ip'],i['user'],i['passwd'],token) + #show_scan(i['ip'],i['user'],i['passwd'],token) diff --git a/APIC-EM_Scan_Device/device.py b/APIC-EM_Scan_Device/device.py new file mode 100644 index 0000000..96cd874 --- /dev/null +++ b/APIC-EM_Scan_Device/device.py @@ -0,0 +1,20 @@ +from getpass import getpass +#passwd=getpass("Nhap passwrd: ") +passwd="VnPro@149" +ap_1 = { + "ip" : "10.215.26.120", #Địa chỉ IP của APIC-EM + "user" :"admin", # Tên đăng nhập trong APIC-EM + "passwd":passwd # Mật khẩu của tài khoản APIC-EM +} +ap_2 = { + "ip" : "10.215.26.121", #Địa chỉ IP của APIC-EM + "user" :"admin", # Tên đăng nhập trong APIC-EM + "passwd":passwd # Mật khẩu của tài khoản APIC-EM +} +ap_3 = { + "ip" : "10.215.26.122", #Địa chỉ IP của APIC-EM + "user" :"admin", # Tên đăng nhập trong APIC-EM + "passwd":passwd # Mật khẩu của tài khoản APIC-EM +} + +device_list = [ap_1] \ No newline at end of file