我試著用Python在Cisco設備上做些事.
這個練習是用Python去SSH登入Cisco設備.
下面程式能做到:
1. SSH(可自選port).
2. 登入的設備清單用另外一份使用者自訂的文件導入(txt).
3. 登入的設備清單的文件位置, 使用者可自行指定.
4. 自動輸入SSH的帳密.
5. 設定指令用另外一份使用者自訂的文件導入(txt).
6. 設定指令的文件位置, 使用者可自行指定.
7. show的輸出結果用另外一份文件輸出(txt).
8. 當SSH time-out, 能跳過該設備, 讓設定繼續下去, 並產生一文件(Unreachable_IP.log)
9. 當SSH 認證失敗, 能跳過該設備, 讓設定繼續下去, 並產生一文件(Auth_Failed.log)
範例檔我是參考:
https://github.com/ktbyers/netmiko
https://pynet.twb-tech.com/blog/automation/netmiko.html
首先先建立一個switches清單(SW_List.txt),
內容是switch IP, 如下範例.
192.168.80.201 192.168.80.202 192.168.80.203 192.168.80.204
再建立一個設定指令文件(show.txt),
如下範例.
terminal length 0 show cdp neighbors show mac address-table show running-config
用Notepad++打下列的程式碼,
另存為PY_SSH_Cisco_v3.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*- # http://juilin77.blogspot.com/ # v20181011 # 下面程式能做到: # 1. SSH(可自選port). # 2. 登入的設備清單用另外一份使用者自訂的文件導入(txt). # 3. 登入的設備清單的文件位置, 使用者可自行指定. # 4. 自動輸入SSH的帳密. # 5. 設定指令用另外一份使用者自訂的文件導入(txt). # 6. 設定指令的文件位置, 使用者可自行指定. # 7. show的輸出結果用另外一份文件輸出(txt). # 8. 當SSH time-out, 能跳過該設備, 讓設定繼續下去, 並產生一文件(Unreachable_IP.log) # 9. 當SSH 認證失敗, 能跳過該設備, 讓設定繼續下去, 並產生一文件(Auth_Failed.log) import sys import socket from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException sw_file = sys.argv[1] cmds_file = sys.argv[2] # 打開一個參數sys.argv[1]所列的IP address. with open(sw_file) as sw_ip_file: # 從sw_file依次提取IP address. for sw_ip_line in sw_ip_file.readlines(): sw_ip = sw_ip_line.strip() # 設定SSH登入Cisco設備的參數. cisco_ios = { "device_type": "cisco_ios", "ip": (sw_ip), "username": "cisco", "password": "cisco123", "port" : 22, # optional, defaults to 22 "secret": "secret", # optional, defaults to "" "verbose": False, # optional, defaults to False } # SSH登入開始, 每一IP一個個登入 all_devices = [cisco_ios] for devices in all_devices: try: print("Starting SSH to Cisco_IOS: " + devices["ip"]) net_connect = ConnectHandler(**cisco_ios) # 當SSH time-out, 跳過該IP, 並產生一文件"Unreachable_IP.log"記錄該IP. except NetMikoTimeoutException: print("Device is not reachable: " + devices["ip"] + "\n") with open("Unreachable_IP.log", "a", newline="") as unreach: unreach.write(devices["ip"] + "\n") continue # 當SSH 認證失敗, 跳過該IP, 並產生一文件"Auth_Failed.log"記錄該IP. except NetMikoAuthenticationException: print("Authentication Failed: " + devices["ip"] + "\n") with open("Auth_Failed.log", "a", newline="") as auth_f: auth_f.write(devices["ip"] + "\n") continue # 打開一個參數sys.argv[2]所列的指令. with open(cmds_file) as cmd_file: # 根據cmds_file的指令, 逐一執行, 並輸出執行結果 for cmd_line in cmd_file: cmds = cmd_line.strip() print ("Runing Show Commands: " + cmds) cmds_output = net_connect.send_command(cmds) print(cmds_output) # 產生一個檔案叫SW_BK_{IP}.txt, 有追加(a)權限. # newline=""是解決Windows換行符問題使用, Linux 不用這參數. with open("SW_BK_" + devices["ip"] + ".log", "a", newline="") as saveoutput: # 把Switch每一行的輸出寫進SW_BK_{IP}.log saveoutput.write(f"#{cmds}\n{cmds_output}\n")
然後我用Web-IOU去建一個測試環境.
以下是預先需要設定的指令:
hostname MGMT_SW01 ! enable secret cisco123 ! no ip domain lookup ! username cisco privilege 15 password cisco123 ! interface vlan 1 ip address 192.168.80.201 255.255.255.0 no shutdown ! line vty 0 4 logging synchronous login local transport input all ! # 我故意把其中一台SW3交換機修改IP(192.168.80.213), 把另外一台SW4交換機修改password hostname SW(01-04) ! enable secret cisco123 ! no ip domain lookup ! username cisco privilege 15 password cisco123 ! interface vlan 1 ip address 192.168.80.(201-204) 255.255.255.0 no shutdown ! line vty 0 4 logging synchronous login local transport input all !
然後用Windows的cmd, 執行python.
注意這邊就要先後帶上兩個參數.
第一個是switches清單(SW_List.txt),
後面一個設定指令文件(show.txt).
D:\Tech\Python\PY_Cisco>python "PY_SSH_Cisco_v3.py" SW_List.txt show.txt Starting SSH to Cisco_IOS: 192.168.80.201 Runing Show Commands: terminal length 0 Runing Show Commands: show cdp neighbors Capability Codes: R - Router, T - Trans Bridge, B - Source Route Bridge S - Switch, H - Host, I - IGMP, r - Repeater, P - Phone, D - Remote, C - CVTA, M - Two-port Mac Relay Device ID Local Intrfce Holdtme Capability Platform Port ID MGMT_SW01.peter.net Eth 0/0 121 R S Linux Uni Eth 1/0 Runing Show Commands: show mac address-table Mac Address Table . . 中略 . . 1 aabb.cc00.0100 DYNAMIC Et0/0 Total Mac Addresses for this criterion: 2 Runing Show Commands: show running-config Building configuration... . . 中略 . . end Starting SSH to Cisco_IOS: 192.168.80.202 Device is not reachable: 192.168.80.202 Starting SSH to Cisco_IOS: 192.168.80.203 Authentication Failed: 192.168.80.203 Starting SSH to Cisco_IOS: 192.168.80.204 Runing Show Commands: terminal length 0 Runing Show Commands: show cdp neighbors Capability Codes: R - Router, T - Trans Bridge, B - Source Route Bridge S - Switch, H - Host, I - IGMP, r - Repeater, P - Phone, D - Remote, C - CVTA, M - Two-port Mac Relay Device ID Local Intrfce Holdtme Capability Platform Port ID MGMT_SW01.peter.net Eth 0/0 151 R S Linux Uni Eth 1/3 Runing Show Commands: show mac address-table Mac Address Table ------------------------------------------- Vlan Mac Address Type Ports ---- ----------- -------- ----- 1 0050.56c0.0008 DYNAMIC Et0/0 1 aabb.cc00.0100 DYNAMIC Et0/0 Total Mac Addresses for this criterion: 2 Runing Show Commands: show running-config Building configuration... Current configuration : 952 bytes ! version 15.1 . . 中略 . . ! end D:\Tech\Python\PY_Cisco>
完成
Check:
參考資料:
1. 05 - Install Paramiko and Netmiko on Windows
http://juilin77.blogspot.com/2018/10/05-install-paramiko-and-netmiko-on.html
2. 12 - Using SSH in Python - v4
https://juilin77.blogspot.com/2019/05/12-using-ssh-in-python-v4.html
3. 07 - Using SSH in Python - v2
https://juilin77.blogspot.com/2018/10/07-using-ssh-in-python-v2.html
4. 06 - Using SSH in Python - v1
https://juilin77.blogspot.com/2018/10/06-using-ssh-in-python-v1.html
最初發表 / 最後更新: 2018.10.11 / 2019.05.16
彼得,我不明白为什么创建文件SW_List.txt,因为我没有在代码中使用它。 我使用命令sw_file = sys.argv [1],但我不知道它是如何获得IP地址的。
回覆刪除