Published 10月 10, 2018 by with 2 comments

07 - Using SSH in Python - v2




我試著用Python在Cisco設備上做些事.
這個練習是用Python去SSH登入Cisco設備.
下面程式能做到:
1. SSH(可選port).
2. 登入的設備清單用另外一份文件導入(txt).
3. 自動輸入SSH的帳密.
4. show的指令用另外一份文件導入(txt).
5. show的輸出結果用另外一份文件輸出(txt).

範例檔我是參考:
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_v1.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*-
# http://juilin77.blogspot.com/
# v20181010
# 下面程式能做到:
# 1. SSH(可選port).
# 2. 登入的設備清單用另外一份文件導入(txt).
# 3. 自動輸入SSH的帳密.
# 4. show的指令用另外一份文件導入(txt).
# 5. show的輸出結果用另外一份文件輸出(txt).

from netmiko import ConnectHandler

# 打開SW清單
with open("SW_List.txt") as sw_ip_file:

    # 從SW_List中依次提取IP.
    for sw_ip_line in sw_ip_file.readlines():
        sw_ip = sw_ip_line.strip()
   
        # 設定SSH登入Cisco設備的參數.
        cisco_sw = {
            "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_sw]
        for devices in all_devices:
            print("Starting SSH to SW: " + devices["ip"])
            net_connect = ConnectHandler(**cisco_sw)
   
            # 打開一個檔案叫show.txt.
            with open("show.txt") as show_cmd_file:
                # 根據show.txt的指令, 逐一執行, 並輸出執行結果.
                for show_line in show_cmd_file:
                    show_cmds = show_line.strip()
                    print ("Runing Show Commands: " + show_cmds)
                    show_cmds_output = net_connect.send_command(show_cmds)
                    print(show_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"#{show_cmds}\n{show_cmds_output}\n")

然後用Windows的cmd, 執行python.
D:\Tech\Python\PY_Cisco>python PY_SSH_Cisco_v1.py
Starting SSH to SW: 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           177              R S   Linux Uni Eth 1/0
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
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
service compress-config
.
.
中略
.
.
interface Vlan1
 ip address 192.168.80.204 255.255.255.0
!
!
no ip http server
!
!
!
!
!
control-plane
!
!
line con 0
 logging synchronous
line aux 0
line vty 0 4
 logging synchronous
 login local
 transport input all
!
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. 08 - Using SSH in Python - v3
https://juilin77.blogspot.com/2018/10/08-using-ssh-in-python-v3.html

4. 06 - Using SSH in Python - v1
https://juilin77.blogspot.com/2018/10/06-using-ssh-in-python-v1.html

最初發表 / 最後更新: 2018.10.10 / 2019.05.16

2 則留言:

  1. 我在指令集裡測試
    sh run
    sh logg
    皆會出現疑似字元問題 "^",可往甚麼方向來處理?
    但其他如sh ver就很正常
    *執行環境:spyder, python3

    回覆刪除
  2. 不好意思 我剛剛才發現您的留言.
    Cisco 設備 應該sh run 或 show logg 應該都OK的呀~
    您要不要先試看看下列做法
    1. 補上完整設定 show running-config,
    2. 直接用您設定的帳號, 登入Cisco設備, 直接在設備上敲sh run (我猜可能您忘記需要先打上"enable"<<您的權限不足)

    回覆刪除