Published 5月 16, 2019 by with 0 comment

12 - Using SSH in Python - v4



Scenario:
1. Customer want to use python to auto SSH to Cisco devices.
2. Using one Execl file(AutoBackup_SSH.xlsx) to save the devices IP, username, password, commands.
3. The output commands need to save as a log file.
4. Windows server will auto zip these log files.
5. If user account privilege level is 15. The user will not ask enable password. setup enable password timeout
6. If the device is not reachable, it will auto pass next and create a file (Unreachable_IP_vyyyymmdd.log).

# -*- coding: UTF-8 -*-
# v20190519
# https://juilin77.blogspot.com
# All devices must can be SSH.
# All user must be have a username and password in each Cisco devices (e.g.: username cisco password cisco123)
# SSH Optional port.
# Using an Excel file to auto import the devices IP, user name, password, enable password and Cisco commands.
# Each devices output will imported to a log file (e.g.BK_Conf_192.168.80.204_v20190514.log).
# When SSH time-out, bypass the device and create a doc 'Unreachable_IP_vyyyymmdd.log' to log this IP.
# When SSH Authentication Failed, bypass the device and create a doc 'Auth_Failed.log_vyyyymmdd' to log this IP.

import openpyxl
import time
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException

# Open the Excel file.
wb = openpyxl.load_workbook('AutoBackup_SSH.xlsx')
Sheet1 = wb['Devices']
Sheet2 = wb['Conf']

# From sheet1 import the device IP, username, password, enable password.
for Sheet1Row in range(2, Sheet1.max_row + 1):
    IP = Sheet1['A' + str(Sheet1Row)].value
    UName = Sheet1['B' + str(Sheet1Row)].value
    PW = Sheet1['C' + str(Sheet1Row)].value
    EN = Sheet1['D' + str(Sheet1Row)].value
    Port = 23
    Date = time.strftime('%Y%m%d', time.localtime())

    #  Setup SSH Parameters
    cisco_ios = {
        'device_type': 'cisco_ios',
        'ip': IP,
        'username': UName,
        'password': PW,
        'port': 22,  # optional, defaults to 22
        'secret': EN,  # Cisco enable password
        'verbose': False,  # optional, defaults to False
    }

    # SSH  Login
    all_devices = [cisco_ios]
    for devices in all_devices:
        try:
            print('Starting SSH to Cisco_IOS: ' + devices['ip'])
            net_connect = ConnectHandler(**cisco_ios)
            net_connect.enable()

        # When SSH time-out, bypass the device and create a doc 'Unreachable_IP_vyyyymmdd.log' to log this IP.
        except NetMikoTimeoutException:
            print('Device Unreachable: ' + devices['ip'] + '\n')
            with open('Unreachable_IP_v' + str(Date) + '.log', 'a', newline='') as unreach:
                unreach.write(devices['ip'] + '\n')
            continue

        # When SSH Authentication Failed, bypass the device and create a doc 'Auth_Failed.log_vyyyymmdd' to log this IP.
        except NetMikoAuthenticationException:
            print('Authentication Failed: ' + devices['ip'] + '\n')
            with open('Auth_Failed_v' + str(Date) + '.log', 'a', newline='') as auth_f:
                auth_f.write(devices['ip'] + '\n')
            continue

        # From sheet2 import the commands.
        for Sheet2Row in range(1, Sheet2.max_row + 1):
            ShowCmds = Sheet2['A' + str(Sheet2Row)].value
            print('Runing Show Commands: ' + ShowCmds)
            cmds_output = net_connect.send_command(ShowCmds, delay_factor=2)
            print(cmds_output)
            Date = time.strftime('%Y%m%d', time.localtime())

            # Creating a log file to save the output.
            with open('BK_Conf_' + str(IP) + '_v' + str(Date) + '.log', 'a', newline='') as SaveOutput:
                SaveOutput.write(f'#{ShowCmds}\n{cmds_output}\n')


Install 7zip on the Windows.
Creating a bat script (SSH_BK_Conf_v20190515.bat). It will auto run python and then after 30 mins auto zip these log file.
@ECHO OFF

:: v20190515
:: Point to backup folder for Python to run,python uses AutoBackup_SSH.xlsx to run equipments
set srcPATH="D:\Accrets\TPC_PCS\PCS_Auto_Backup"
set dstPATH="C:\Users\Peter\Backup"
pushd %srcPATH% 

"C:\Users\Peter\AppData\Local\Programs\Python\Python37\python.exe" "%srcPATH%\SSH_Backup_v20190515.py"

:: This bat will sleep 10 seconds,waiting for python running. 
:: After 10 seconds, will move backup config to subfolder named "BK_Conf_vYYYYMMDD"
choice /T 10 /D y /N > nul

:: This folder is your backup file location.
mkdir "%dstPATH%\BK_Conf_v%date:~0,4%%date:~5,2%%date:~8,2%"
move "%srcPATH%\BK_Conf_*.log" "%dstPATH%\BK_Conf_v%date:~0,4%%date:~5,2%%date:~8,2%"
move "%srcPATH%\Auth_Failed_v*.log" "%dstPATH%\BK_Conf_v%date:~0,4%%date:~5,2%%date:~8,2%"
move "%srcPATH%\Unreachable_IP_v*.log" "%dstPATH%\BK_Conf_v%date:~0,4%%date:~5,2%%date:~8,2%"

:: Using 7z to ZIP these backup file.
"C:\Program Files\7-Zip\7z.exe" a -tzip "%dstPATH%\BK_Conf_v%date:~0,4%%date:~5,2%%date:~8,2%.zip" "%dstPATH%\BK_Conf_v*"
rmdir /Q /S "%dstPATH%\BK_Conf_v%date:~0,4%%date:~5,2%%date:~8,2%"

ECHO finish

In the Windows, use the Search option to search for “Schedule” and choose “Schedule Task” to open the Task Scheduler.
Every 1AM Monday run this bat file(SSH_BK_Conf_v20190515.bat).

Resource:
1. The example Excel and log files:
https://drive.google.com/open?id=1-FWWgJjfeG3_y_uTzU10Pv2zGGUW7wRe

2. 08 - Using SSH in Python - v3
https://juilin77.blogspot.com/2018/10/08-using-ssh-in-python-v3.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

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

0 comments:

張貼留言