debian

Debian SecureCRT脚本编写入门

小樊
40
2025-11-27 01:58:47
栏目: 智能运维

入门概览

环境准备与脚本执行

Python 入门脚本模板

# $language = "Python"
# $interface = "1.0"

import time

def log_name():
    return time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())

def main():
    # 基本配置
    user = 'admin'
    passwd = 'your_password'
    host = '192.0.2.10'
    prompt = '#'  # 设备命令提示符,按需改为 '>' 等

    # 连接参数(示例为 SSH2)
    # 注意:SecureCRT 的 ConnectInTab 参数语法依版本而异,以下为常见形式
    connect_cmd = f"/SSH2 /L {user} /PASSWORD {passwd} {host}"
    tab = crt.Session.ConnectInTab(connect_cmd)
    time.sleep(1)

    # 等待登录完成(出现提示符)
    tab.Screen.WaitForString(prompt)

    # 开启日志
    ts = log_name()
    tab.Session.LogFileName = f"{ts}_{host}.log"
    tab.Session.Log(True)

    # 执行命令
    commands = [
        "show version",
        "show ip interface brief"
    ]
    for cmd in commands:
        tab.Screen.Send(cmd + "\r")
        # 等待命令回显完成:匹配提示符或分页提示
        idx = tab.Screen.WaitForStrings([prompt, "---- More ----"], 10)
        while idx == 2:  # 遇到分页
            tab.Screen.Send(" ")  # 继续翻页
            idx = tab.Screen.WaitForStrings([prompt, "---- More ----"], 5)

    # 结束
    tab.Session.Log(False)
    crt.Dialog.MessageBox("Done.")

main()

VBScript 入门脚本模板

# $language = "VBScript"
# $interface = "1.0"

Sub Main
    Dim user, passwd, host, prompt
    user = "admin"
    passwd = "your_password"
    host = "192.0.2.10"
    prompt = "#"   ' 设备命令提示符,按需改为 '>'

    ' 连接
    crt.Session.Connect "/SSH2 /L " & user & " /PASSWORD " & passwd & " " & host
    crt.Screen.WaitForString "ogin:"

    ' 登录
    crt.Screen.Send "admin" & vbCrLf
    crt.Screen.WaitForString "assword:"
    crt.Screen.Send passwd & vbCrLf
    crt.Screen.WaitForString prompt

    ' 日志
    crt.Session.LogFileName = "c:\temp\" & host & "_" & Replace(Now, "/", "-") & ".log"
    crt.Session.Log True

    ' 命令
    crt.Screen.Send "show version" & vbCrLf
    crt.Screen.WaitForString prompt

    crt.Screen.Send "show ip interface brief" & vbCrLf
    crt.Screen.WaitForString prompt

    ' 分页处理
    Do
        Dim idx
        idx = crt.Screen.WaitForStrings(Array(prompt, "---- More ----"), 5)
        If idx = 2 Then
            crt.Screen.Send " "
        Else
            Exit Do
        End If
    Loop

    crt.Session.Log False
    MsgBox "Done."
End Sub

调试与最佳实践

0
看了该问题的人还看了