Published 5月 12, 2019 by with 0 comment

11 - Using Telnet in Python - v4



Scenario:
1. Customer want to use python to auto Telnet to Cisco devices.
2. Using one Execl file(AutoBackup.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.

20190511 Update:
1. Some device will not ask user name, setup username timeout.
2. If user account privilege level is 15. The user will not ask enable password. setup enable password timeout

20190504 Update:
1. If the device is not reachable, it will auto pass next and create a file (Unreachable_IP_vyyyymmdd.log).

Feature Update:
1. If the username and password wrong, it will auto pass next and create a file (Auth_Failed_vyyyymmdd.log).
2. SSH version.

# -*- coding: UTF-8 -*-
# v20190511
# https://juilin77.blogspot.com
# All devices must can be Telnet.
# All user must be have a username and password in each Cisco devices (e.g.: username cisco password cisco123)
# All user must be have the enable password or enable secret
# Telnet Optional port.
# Using an Excel file(AutoBackup.xlsx) to auto import the devices IP, user name, password, enable password and Cisco commands.
# Each devices output will imported to a log file.

import openpyxl
import telnetlib
import time
import socket

# Open the Excel file.
wb = openpyxl.load_workbook('AutoBackup.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())
    print('Starting Telnet to Device: ' + IP)
    try:
        tn = telnetlib.Telnet(IP, Port, 5)
    except socket.timeout:
        print('Device is not reachable: ' + IP + '\n')
        with open('Unreachable_IP_v' + str(Date) + '.log', 'a', newline='') as unreach:
            unreach.write(str(IP) + '\n')
    else:
        tn.read_until(b'Username: ', 3)
        tn.write(UName.encode('ascii') + b'\n')
        tn.read_until(b'Password: ')
        tn.write(PW.encode('ascii') + b'\n')
        tn.read_until(b'>', 3)
        tn.write(b'enable\n')
        tn.read_until(b'Password: ', 3)
        tn.write(EN.encode('ascii') + b'\n')

        # 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)
            tn.read_until(b'')
            tn.write(ShowCmds.encode('ascii') + b'\n' + b'\n')
            time.sleep(1)
            ShowCmdsOutput = ''
            ShowCmdsOutput += tn.read_very_eager().decode('ascii')
            print(ShowCmdsOutput)
            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(str(ShowCmdsOutput))


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

@ECHO OFF
:: v20190502
:: Point to backup folder for Python to run,python uses AutoBackup.xlsx to run equipments
set srcPATH="D:\Accrets\TPC_PCS\PCS_Auto_Backup"
set dstPATH="C:\Users\Peter\Backup"

:: Change directory
pushd %srcPATH% 
"C:\Users\Peter\AppData\Local\Programs\Python\Python37\python.exe" "%srcPATH%\Backup_v20190429.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 5 /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%"

:: 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(BK_Conf_v20190502.bat).

Resource:
1. The example Excel and log files:
https://drive.google.com/drive/folders/12gMB-P0O6EhYotmHJNL-Nx5HsLEkvUN3?usp=sharing

2. Using Telnet in Python - v2
http://juilin77.blogspot.com/2019/04/09-using-telnet-in-python-v2.html

3. Using Telnet in Python - v3
http://juilin77.blogspot.com/2019/05/10-using-telnet-in-python-v3.html


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

0 comments:

張貼留言