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)


  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个SecureCRT脚本示例,可以用于更改锐捷交换机的主机名: ```python # $language = "Python" # $interface = "1.0" def main(): # 连接到锐捷交换机 cmd = "/SSH2 /L username /PASSWORD password /C aes256-cbc /M hmac-sha2-256 ip_address" crt.Session.Connect(cmd) # 切换到特权模式 crt.Screen.WaitForString("Username:") crt.Screen.Send("username\r") crt.Screen.WaitForString("Password:") crt.Screen.Send("password\r") crt.Screen.WaitForString(">") crt.Screen.Send("enable\r") crt.Screen.WaitForString("Password:") crt.Screen.Send("enable_password\r") # 更改主机名 crt.Screen.WaitForString("#") crt.Screen.Send("system-view\r") crt.Screen.WaitForString("[system-view]") crt.Screen.Send("hostname new_hostname\r") crt.Screen.WaitForString("[new_hostname]") crt.Screen.Send("quit\r") # 保存配置并退出 crt.Screen.WaitForString("[~") crt.Screen.Send("save\r") crt.Screen.WaitForString("Y/N") crt.Screen.Send("y\r") crt.Screen.WaitForString("[~") crt.Screen.Send("quit\r") # 断开连接 crt.Screen.WaitForString("$ ") crt.Session.Disconnect() main() ``` 这个脚本连接到IP地址为ip_address的锐捷交换机,使用用户名、密码和特权密码进行身份验证。然后,它使用system-view命令进入配置模式,并使用hostname命令更改主机名为new_hostname。接下来,它使用save命令保存配置,并使用quit命令退出特权模式。最后,它断开SSH连接。 请注意,此示例脚本仅供参考。实际使用中,您可能需要根据自己的需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值