1. 程式人生 > >secureCRT思科路由器交換機專用指令碼

secureCRT思科路由器交換機專用指令碼

為了工作方便,自己寫了個指令碼用

不過只能在secureCRT上支援Cisco的裝置,因為其中的詞法分析只適用於Cisco的配置

指令碼的功能還行,可以自動識別SSH2和Telnet登入,因為我的工作環境有些裝置不支援SSH2,所以只能用Telnet

可以自定義需要批量使用的命令,並會按照日期自動儲存在不同的log檔案中,方便檢查

也可以開啟自動生成關鍵資訊excel的功能,這會在剛剛儲存的log檔案中提取關鍵資訊,例如hostname,ip address,model,SN,image,uptime

#$language = "VBScript"
#$interface = "1.0"
crt.Screen.Synchronous = True

'------------------------------------------------------------------------------------------------------'
'全域性常量在整個程式中均有效

'設定SSH使用者名稱和密碼
Const UserName1 = """Mr Right""" , PassWord1 = "Michael123!" , EnablePassWD1 = "Michael123!"
'設定Telnet使用者名稱和密碼以及enable密碼
Const UserName2 = "Mr Right", PassWord2 = "Michael123!", EnablePassWD2 = "Michael123!"

'設定地址表位置
Const LstFileLK = "D:\Desktop\scripts\123.txt"
'設定思科命令表位置
Const CmdFileForCISCO = "D:\Desktop\scripts\testcmd.txt"
'設定回顯儲存的位置(此處只要設定儲存到的資料夾位置,命令產生的回顯會自動以IP.TXT儲存在不同檔案中)
Const LogFileLK = "D:\Desktop\scripts\LOG\" 

' 是否建立Excel檔案,自動提取關鍵資訊(HostName、IP Address、Model、SN、Image、UpTime)
const isCreateExcelFile = true

'設定常量Read為1,Write為2
Const Read = 1, Write = 2

'每條命令重新整理時間(機器比較好的時候,可以改小點)
const waitingForCmd = 5

'------------------------------------------------------------------------------------------------------'
'主函式
Sub Main

	'定義兩個變數(注:fso為區域性變數僅在此函式中有效)
	Dim fso, LstFile
	
	'呼叫函式建立檔案系統物件
	Set fso = CreateObject("Scripting.FileSystemObject")
	'呼叫函式建立物件的屬性(讀取地址表中的內容)
	Set LstFile = fso.OpenTextFile(LstFileLK, Read, False)
	
	'呼叫Login子函式,以地址作為引數做登入方式檢測
	Do While (LstFile.AtEndOfStream <> True)
		if Login(LstFile.ReadLine) then
			RunCommand()
		end if
	Loop

	'是否建立Excel檔案
	if isCreateExcelFile then
		dateTime = date()
		dateTime = Replace(dateTime,"/","-")
		createExcel LogFileLK & dateTime & ".xlsx", LogFileLK & date() & "\"
		MsgBox("Create " & LogFileLK & dateTime & ".xlsx" & " successful!")
	end if
	
	'Crt執行完畢
	Crt.Screen.Synchronous = False
	
'程式結束
End Sub

'------------------------------------------------------------------------------------------------------'
'Login子函式(登入檢測)
function Login(IP)
	'函式返回值
	Login = True	
	'建立回顯儲存的檔名(IP.TXT)
	Crt.Session.LogFileName = LogFileLK & date() & "/" & IP & ".txt"
	
	'登入方式
	Login = SSH2Connect(IP)
	if NOT Login then
		Login = TelnetConnect(IP)

		dim fso, file
		set fso = CreateObject("Scripting.FileSystemObject")
		if Login then 
			set file = fso.GetFile(LogFileLK & date() & "\" & "SSH2Fail-" & IP & ".txt")
			file.Delete
		else
			set file = fso.GetFile(LogFileLK & date() & "\" & IP & ".txt")
			file.Delete
		end if
		
	end if
	
'MsgBox Login
	
'返回主函式
End function

'------------------------------------------------------------------------------------------------------'
function SSH2Connect(IP)

	'函式返回值
	SSH2Connect = True
	Crt.Session.Log(True)
	'此部分例項程式碼在scripting_essentials.pdf的P31有詳細解釋
	On Error Resume Next 
	crt.Session.Connect("/SSH2 /L " & UserName1 & " /PASSWORD " & PassWord1 & " " & IP)	
	nError = Err.Number 
	strErr = Err.Description 
	' Now, tell the script host that it should handle errors as usual now: 
	On Error Goto 0 
	If nError <> 0 Then     
	' Handle the error (log to a file, etc.) 

		SSH2Connect = false
		Crt.Session.Log(false)
		Crt.Session.LogFileName = LogFileLK & date() & "\" & "SSH2Fail-" & IP & ".txt"
		crt.Session.Disconnect
	Else    
	' Do work on the remote machine

		Select Case Crt.Screen.WaitForStrings(">","#",10)
		'需要輸入enable密碼		
			Case 1
				SendEnablePasswd()
		'特權模式
			Case 2
				Crt.Screen.Send vbCr
		End Select	
	End If
end function 

'------------------------------------------------------------------------------------------------------'
function TelnetConnect(IP)

	'函式返回值
	TelnetConnect = True
	Crt.Session.Log(True)
	On Error Resume Next 
	crt.Session.Connect("/Telnet" & " " & IP)
	nError = Err.Number 
	strErr = Err.Description 
	' Now, tell the script host that it should handle errors as usual now: 
	On Error Goto 0 
	If nError <> 0 Then     
	' Handle the error (log to a file, etc.) 

		TelnetConnect = false
		Crt.Session.Log(false)
		Crt.Session.LogFileName = LogFileLK & date() & "\" & "TelnetFail-" & IP & ".txt"
		crt.Session.Disconnect
	Else    
		Select Case crt.Screen.WaitForStrings("ame",10)
		'輸入使用者名稱和密碼
			Case 1

				Crt.Session.Log(false)
				Crt.Screen.Send UserName2
				crt.Screen.Send vbcr
				Crt.Screen.WaitForString("assword: ")
				Crt.Screen.Send(PassWord2 & vbcr)
				Crt.Screen.Send vbCr
				Crt.Session.Log(true)
				if (crt.Screen.WaitForStrings(">","#") <> 2) then
					SendEnablePasswd()
				else
					Crt.Screen.Send vbCr
				end if
		end Select
	End If
	
end function

'------------------------------------------------------------------------------------------------------'
'傳送enable密碼
sub SendEnablePasswd()
	Crt.Screen.Send "enable" & vbCr
	Crt.Screen.WaitForString("assword: ")
	Crt.Screen.Send EnablePassWD1 & vbCr
	Crt.Screen.Send vbCr
end sub

'------------------------------------------------------------------------------------------------------'
'RunCommand子函式
Sub RunCommand()
	
	'此處fso變數屬於區域性變數,所以不會和主函式中的fso變數衝突
	Dim fso, CmdFile, CMD
	'建立物件
	Set fso = CreateObject("Scripting.FileSystemObject")		
	Set CmdFile = fso.OpenTextFile(CmdFileForCISCO, Read, False)

	'迴圈執行命令表中的命令直到結束
	Do While CmdFile.AtEndOfStream <> True
		
		CMD = CmdFile.ReadLine
		'執行命令表中的命令
		crt.Screen.Send CMD & vbcr
		'超過螢幕時,按空格
		Do While (crt.Screen.WaitForString("More",waitingForCmd) = True)
			crt.Screen.Send(" ")
		Loop 

		crt.Screen.Send vbCr
	'迴圈結束
	Loop

	Crt.Session.Log(false)
	
	'關閉CRT對話方塊
	crt.Session.Disconnect
	
'返回Login子函式

End Sub

'------------------------------------------------------------------------------------------------------'
' 建立Excel
function createExcel(fileName, dirName)
	createExcel = true
    createExcelHeard fileName, dirName
end function

'------------------------------------------------------------------------------------------------------'
' 建立Excel表頭
' 格式:
'   No  HostName        IP Address  Model	              SN	        Image	                            UpTime
'   1   P03-S-3750G-2   10.93.1.32  WS-C3750G-24TS-S1U    FOC**0223ST   c3750-ipbasek9-mz.122-55.SE11.bin   8w4d21h51m
'   2   P03-S-3750G-2   10.93.1.32  WS-C3750G-24TS-S1U    FOC**0223ST   c3750-ipbasek9-mz.122-55.SE11.bin   8w4d21h51m
function createExcelHeard(fileName, dirName)

	createExcelHeard = true

    dim objExcelApp, objExcelBook, objExcelSheet
    'fileName = 

    set objExcelApp = CreateObject("excel.application")
    set objExcelBook = objExcelApp.WorkBooks.Add
    set objExcelSheet = objExcelBook.ActiveSheet
' 生成excl表頭
    objExcelSheet.Cells(1,1) = "No"
	objExcelsheet.Cells(1,2) = "FileName"
    objExcelSheet.Cells(1,3) = "HostName"
    objExcelSheet.Cells(1,4) = "IP Address"
    objExcelSheet.Cells(1,5) = "Model"
    objExcelSheet.Cells(1,6) = "SN"
    objExcelSheet.Cells(1,7) = "Image"
    objExcelSheet.Cells(1,8) = "UpTime"
' 讀取檔案中的詳細資訊
    
    ' 建立檔案系統物件
    set fso = CreateObject("Scripting.FileSystemObject")
    ' 獲得檔案物件
    set objFolder = fso.GetFolder(dirName)
    ' 獲得檔案清單
    set objFiles = objFolder.Files

    dim row, column, number
    row = 2
    column = 1
    ' 迴圈獲得每個檔案
    for each file in objFiles
        ' 填寫No
        objExcelSheet.Cells(row,column) = row - 1
		' 填寫提取檔名
		column = column + 1
		objExcelSheet.Cells(row,column) = file.name
        ' 填寫HostName 
        column = column + 1
        objExcelSheet.Cells(row,column) = getInformation(dirname & file.name, "HostName")
        ' 填寫IP Address
        column = column + 1
        objExcelSheet.Cells(row,column) = getInformation(dirname & file.name, "IP Address")
        ' 填寫Model
        column = column + 1
        objExcelSheet.Cells(row,column) = getInformation(dirname & file.name, "Model")
        ' 填寫SN
        column = column + 1
        objExcelSheet.Cells(row,column) = getInformation(dirname & file.name, "SN")
        ' 填寫Image
        column = column + 1
        objExcelSheet.Cells(row,column) = getInformation(dirname & file.name, "Image")
        ' 填寫UpTime
        column = column + 1
        objExcelSheet.Cells(row,column) = getInformation(dirname & file.name, "UpTime")
        ' 下一行
        column = 1
        row = row + 1
    next  

    ' 調整excl格式
    for i = 65 to 72
        objExcelSheet.Columns(chr(i)).AutoFit
    next

    objExcelBook.SaveAs(fileName)
    objExcelBook.Close
    objExcelApp.Quit

end function


'------------------------------------------------------------------------------------------------------'
' 函式功能:獲得關鍵資訊
' szFileName:檔名
' szInformation:需要獲取的資訊,支援五種資訊的獲取HostName、Image、SN、Model和UpTime
' 返回值:根據不同的szInformation返回不同的資訊,如果未找到需要的資訊則返回N/A
' 用法1獲得檔案中裝置IOS型號:  getInformation("D:\DeskTop\10.93.1.32.txt", "Image")
' 用法2獲得檔案中裝置SN號:     getInformation("D:\DeskTop\10.93.1.32.txt", "SN")
' 用法3獲得檔案中裝置型號:     getInformation("D:\DeskTop\10.93.1.32.txt", "Model")
' 用法4獲得檔案中裝置啟動時長: getInformation("D:\DeskTop\10.93.1.32.txt", "UpTime")
' 用法5獲得檔案中裝置HostName: getInformation("D:\DeskTop\10.93.1.32.txt", "HostName")

function getInformation(szFileName,szInformation)
    dim fso, objFile
    dim szLine, isInforLine
    getInformation = "N/A"
    isInforLine = 0

    set fso = CreateObject("Scripting.FileSystemObject")
    ' 檢查檔案是否存在
    if fso.FileExists(szFileName) then 
        set objFile = fso.OpenTextFile(szFileName, 1, false)
        ' 迴圈讀行
        do While(objFile.AtEndOfStream <> true) 
            szline = objFile.ReadLine
            ' 資訊篩選
            select case szInformation
                ' 需要IOS資訊
                ' 搜尋System image file is字串
                ' 例如:System image file is "flash:/c3750-ipbasek9-mz.122-55.SE11.bin"
                case "Image"
                    ' 如果該行有需要的資訊則傳遞給專用詞法分析函式,做進一步資訊提取
                    isInforLine = InStr(szline,"System image file is")
                    if isInforLine then
                        getInformation = getImage(szline)
                        objFile.close()
                        ' 找到資訊退出函式
                        exit function
                    end if
                ' 需要SN資訊
                ' 搜尋Processor board ID字串
                ' 例如Processor board ID FOC1102Z8FE
                case "SN"
                    ' 如果該行有需要的資訊則傳遞給專用詞法分析函式,做進一步資訊提取
                    isInforLine = InStr(szline,"Processor board ID")
                    if isInforLine then
                        getInformation = getSN(szline)
                        objFile.close()
                        ' 找到資訊退出函式
                        exit function
                    end if
                ' 需要裝置型號資訊
                ' 搜尋bytes of memory.字串
                ' 例如:cisco WS-C3750G-24TS-1U (PowerPC405) processor (revision D0) with 131072K bytes of memory.
                case "Model"
                    ' 如果該行有需要的資訊則傳遞給專用詞法分析函式,做進一步資訊提取
                    isInforLine = InStr(szline,"bytes of memory.")
                    if isInforLine then
                        getInformation = getModel(szline)
                        objFile.close()
                        ' 找到資訊退出函式
                        exit function
                    end if
                ' 需要啟動時間資訊
                ' 搜尋UpTime is字串
                ' 例如:P03-S-3750G-2 uptime is 8 weeks, 4 days, 21 hours, 51 minutes
                case "UpTime"
                    ' 如果該行有需要的資訊則傳遞給專用詞法分析函式,做進一步資訊提取
                    isInforLine = InStr(szline,"uptime is")
                    if isInforLine then
                        getInformation = getUptime(szline)
                        objFile.close()
                        ' 找到資訊退出函式
                        exit function
                    end if
                    ' 需要啟動時間資訊
                ' 搜尋#字串
                ' 例如:P03-S-3750G-2#sh ver
                case "HostName"
                    ' 如果該行有需要的資訊則傳遞給專用詞法分析函式,做進一步資訊提取
                    isInforLine = InStr(szline,"#")
                    if isInforLine then
                        getInformation = getHostName(szline)
                        objFile.close()
                        ' 找到資訊退出函式
                        exit function
                    end if
            end select
        loop
        ' 如果沒找到資訊則返回 "N/A"
    else
        ' 檔案不存才時
        getInformation = "No this file!"
    end if

end function

'------------------------------------------------------------------------------------------------------'
' 提取IOS
' 例如:System image file is "flash:/c3750-ipbasek9-mz.122-55.SE11.bin"
function getImage(szline)
    dim tmpImage1, tmpImage2, tmpImage3, image
    ' 先以空格分割每個單詞
    tmpImage1 = Split(szline," ")
    ' 得到陣列中最後一個單詞,即"flash:/c3750-ipbasek9-mz.122-55.SE11.bin"
    tmpImage2 = tmpImage1(UBound(tmpImage1))
    ' 替換單詞中的"號為空格,並使用/分割字串
    ' 注:chr(34)就是"的ASCII碼
    tmpImage3 = Split(Replace(tmpImage2,chr(34)," "),"/")
    ' 返回陣列中最後一個單詞,即c3750-ipbasek9-mz.122-55.SE11.bin
    getImage = tmpImage3(UBound(tmpImage3))
	if InStr(getImage,":") then 
		tmpImage1 = Split(getImage,":")
		getImage = tmpImage1(UBound(tmpImage1))
	end if
end function

'------------------------------------------------------------------------------------------------------'
' 提取裝置SN號碼
' 例如Processor board ID FOC1102Z8FE
function getSN(szline)
    dim SN
    ' 先以空格分割每個單詞
    SN = Split(szline," ")
    ' 返回陣列中最後一個單詞,即FOC1102Z8FE
    getSN = SN(UBound(SN))
end function

'------------------------------------------------------------------------------------------------------'
' 提取裝置型號
' 例如:cisco WS-C3750G-24TS-1U (PowerPC405) processor (revision D0) with 131072K bytes of memory.
function getModel(szline)
    dim Model
    ' 先以空格分割每個單詞
    Model = Split(szline, " ")
    ' 返回陣列中第二個單詞(陣列是從0開始的,所以1是第二個),即WS-C3750G-24TS-1U
    getModel = Model(1)
end function

'------------------------------------------------------------------------------------------------------'
' 提取裝置啟動時長
' 例如:P03-S-3750G-2 uptime is 8 weeks, 4 days, 21 hours, 51 minutes
' 返回值的格式為 8w4d21h51m
function getUptime(szline)
    dim uptime, tmpUptime1
    ' 先以空格分割每個單詞
    tmpUptime1 = Split(szline," ")
    ' 迴圈找出對應的時間資訊,並拼接字串
    for i = 0 to UBound(tmpUptime1)
        select case tmpUptime1(i)
            case "weeks,"
                uptime = tmpUptime1(i-1) & "w"
            case "days,"
                uptime = uptime & tmpUptime1(i-1) & "d"
            case "hours,"
                uptime = uptime & tmpUptime1(i-1) & "h"
            case "minutes"
                uptime = uptime & tmpUptime1(i-1) & "m"
        end select
    next
    getUptime = uptime 
end function

'------------------------------------------------------------------------------------------------------'
' 提取裝置名字
function getHostName(szline)
    dim HostName
    HostName = Split(szline,"#")
    getHostName = HostName(0)
end function


'------------------------------------------------------------------------------------------------------'


'Mr Right 2018.1.2編寫
'版本2.1.0
'SSH2 & Telnet
'可自動識別SSH2和Telnet登入方式
'回顯超過螢幕顯示時(出現--More--)會自動按空格
'可自動生成excel,提取關鍵資訊(關鍵資訊包括HostName、IP Address、Model、SN、Image、UpTime)