配合secureCRT实现自动化控制简单协议的交互_Python

发现secureCRT 从8.0版本开始,支持内建Python解释器,可以直接运行脚本来控制窗口的交互,这真是极好的自动化工具,

经过一番研究,实现下面几个demo,已备后用:

1. 获得串口的数据

    # $language = "python"
    # $interface = "1.0"
     
    def main():
        # Send the unix "date" command and wait for the prompt that
        # indicating that it completed. In general we want to be in
        # synchronous mode before doing send/wait operations.
        #
        crt.Screen.Synchronous = True
        crt.Screen.Send("date\r")
     
        promptString = "linux$"
        crt.Screen.WaitForString(promptString)
     
        # When we get here the cursor should be one line below the output of
        # the 'date' command. Subtract one line and use that value to read a
        # chunk of text (1 row, 40 characters) from the screen.
        #
        screenrow = crt.Screen.CurrentRow - 1
        result = crt.Screen.Get(screenrow, 1, screenrow, 40)
     
        # Get() reads a fixed size of the screen. So you may need to use a
        # regular expression function or the str.split() method to do some
        # simple parsing if necessary. Just print it out here.
        #
        crt.Dialog.MessageBox(result)
        crt.Screen.Synchronous = False
     
    main()


2.从串口获得数据,放入excel里

  

  # $language = "python"
    # $interface = "1.0"
     
    # This script demonstrates how Python scripting can be used to interact
    # with CRT and manipulate an spreadsheet file (for reading by other
    # programs such as Microsoft Excel). This script uses Python's csv library
    # to create a spreadsheet, then it sends a command to a remote server
    # (assuming we're already connected). It reads the output, parses it and
    # writes out some of the data to the spreadsheet and saves it.  This
    # script also demonstrates how the WaitForStrings function can be used to
    # wait for more than one output string.
    #
    import os
    import csv
     
    def main():
     
        crt.Screen.Synchronous = True
     
        # Create an Excel compatible spreadsheet
        #
        filename = os.path.join(os.environ['TEMP'], 'chart.csv')
        fileobj = open(filename, 'wb')
     
        worksheet = csv.writer(fileobj)
     
        # Send the initial command to run and wait for the first linefeed
        #
        crt.Screen.Send("cat /etc/passwd\r")
        crt.Screen.WaitForString("\n")
     
        # Create an array of strings to wait for.
        #
        promptStr = "linux$"
        waitStrs = [ "\n", promptStr ]
     
        row = 1
     
        while True:
     
            # Wait for the linefeed at the end of each line, or the shell
            # prompt that indicates we're done.
            #    
            result = crt.Screen.WaitForStrings( waitStrs )
     
            # We saw the prompt, we're done.
            #
            if result == 2:
                break
     
            # Fetch current row and read the first 40 characters from the
            # screen on that row. Note, since we read a linefeed character
            # subtract 1 from the return value of CurrentRow to read the
            # actual line.
            #
            screenrow = crt.Screen.CurrentRow - 1
            readline = crt.Screen.Get(screenrow, 1, screenrow, 40)
     
            # Split the line ( ":" delimited) and put some fields into Excel
            #
            items = readline.split(":")
            worksheet.writerow(items[:2])
     
            row = row + 1
     
     
        fileobj.close()
        crt.Screen.Synchronous = False
     
     
    main()


3. 从串口读取简单的字符串

    # $language = "python"
    # $interface = "1.0"
     
    # ReadString.py
    #
    # Description:
    #     This example script captures the output of a command (ls -l) sent to a
    #     remote machine by using the Screen.ReadString() method.  The captured
    #     text is then displayed in a messagebox window.
    #
    # This example demonstrates:
    #     - How to use the basic functionality of the Screen.ReadString()
    #       method to easily capture data from a remote system.
    #     - How to use the Screen.IgnoreEscape property to change the way ReadString
    #       (also applies to WaitForString() and WaitForStrings()) handles
    #       non-printable characters.
    #       By default, ReadString() will capture all data sent from the remote
    #       during the time in which ReadString is capturing data, including escape
    #       sequences.  If you do not want to capture escape sequences and instead
    #       only capture visible ASCII text, set the Screen.IgnoreEscape property to
    #       True, as in this example.
    #
    # This script example assumes the user has logged in and is sitting at a command
    # prompt as the script is launched from SecureCRT's 'Script -> Run' menu.
     
    def Main():
        # Here is where we will set the value of the string that will indicate that
        # we have reached the end of the data that we wanted capture with the
        # ReadString method.
        szPrompt = "]->"
     
        # Using GetScriptTab() will make this script 'tab safe' in that all of the
        # script's functionality will be carried out on the correct tab. From here
        # on out we'll use the objTab object instead of the crt object.
        objTab = crt.GetScriptTab()
        objTab.Screen.Synchronous = True
     
        # Instruct WaitForString and ReadString to ignore escape sequences when
        # detecting and capturing data received from the remote (this doesn't
        # affect the way the data is displayed to the screen, only how it is handled
        # by the WaitForString, WaitForStrings, and ReadString methods associated
        # with the Screen object.
        objTab.Screen.IgnoreEscape = True
     
        # We begin the process by sending some a command. In this example script,
        # we're simply getting a file listing from a remote UNIX system using the
        # "ls -l" command.
        szCommand = "ls -l"
        objTab.Screen.Send(szCommand + "\r\n")
     
        # Wait for the command and the trailing CR to be echoed back from the remote
        # before we start capturing data... Otherwise, we'll capture the command we
        # issued, as well as the results, and in this example, we only want to
        # capture the results.
        objTab.Screen.WaitForString(szCommand + "\r\n")
     
        # This will cause ReadString() to capture data until we see the szPrompt
        # value.
        szResult = objTab.Screen.ReadString(szPrompt)
     
        # Display the results in a messagebox
        crt.Dialog.MessageBox(szResult)
     
    Main()

4.发送一条命令,并获得反馈的字符串

    # $language = "python"
    # $interface = "1.0"
     
    def Main():
        szPrompt = ">"
     
        objTab = crt.GetScriptTab()    #生成一个当前选项卡对象,以后所有的操作都,基于在此选项卡内工作
        objTab.Screen.Synchronous = True
     
        objTab.Screen.IgnoreEscape = True
        sendCmd = "1"
        objTab.Screen.Send(sendCmd + "\r\n")  #发送一个命令到shell, 注意要加换行符,才可以真正发出去
     
        objTab.Screen.WaitForString(sendCmd + "\r\n")  #这个命令的作用是,如果下面要截取ack的文本则不包含send部分,如果注掉,则截取的text包含send部分
     
        szResult = objTab.Screen.ReadString(szPrompt) #截取到提示符的所有文本
        
        if '1' not in szResult:
            crt.Dialog.MessageBox('not!')
        else:
            crt.Dialog.MessageBox('yes!')
            
        # 弹出消息显示读到的信息,只适合作简单的判断,不适合做全自动脚本,因为提示框只有按下yes,才可以继续
     
    Main()


5. 发送一串命令

    #$language = "python"
    #$interface = "1.0"
     
    import os
    import subprocess
     
    LOG_DIRECTORY = os.path.join(
        os.path.expanduser('~'), 'LogOutputOfSpecificCommand')
     
    LOG_FILE_TEMPLATE = os.path.join(
        LOG_DIRECTORY, "Command_%(NUM)s_Results.txt")
     
    SCRIPT_TAB = crt.GetScriptTab()
     
    COMMANDS = [
        "1",
        "2",
        "3",
        "4",
    #    "sh run",
    #    "",
    #    "",
        ]
     
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def main():
     
        if not os.path.exists(LOG_DIRECTORY):
            os.mkdir(LOG_DIRECTORY)
     
        if not os.path.isdir(LOG_DIRECTORY):
            crt.Dialog.MessageBox(
                "Log output directory %r is not a directory" % LOG_DIRECTORY)
            return
     
        if not SCRIPT_TAB.Session.Connected:
            crt.Dialog.MessageBox(
                "Not Connected.  Please connect before running this script.")
            return
     
        SCRIPT_TAB.Screen.IgnoreEscape = True
        SCRIPT_TAB.Screen.Synchronous = True
     
        while True:
            if not SCRIPT_TAB.Screen.WaitForCursor(1):
                break
        
        rowIndex = SCRIPT_TAB.Screen.CurrentRow
        colIndex = SCRIPT_TAB.Screen.CurrentColumn - 1
     
        prompt = SCRIPT_TAB.Screen.Get(rowIndex, 0, rowIndex, colIndex)
        prompt = prompt.strip()
     
        for (index, command) in enumerate(COMMANDS):
            command = command.strip()
     
            # Set up the log file for this specific command
            logFileName = LOG_FILE_TEMPLATE % {"NUM" : NN(index + 1, 2)}
            
            # Send the command text to the remote
            SCRIPT_TAB.Screen.Send(command + '\r')
     
            # Wait for the command to be echo'd back to us.
            SCRIPT_TAB.Screen.WaitForString('\r', 1)
            SCRIPT_TAB.Screen.WaitForString('\n', 1)
     
            result = SCRIPT_TAB.Screen.ReadString(prompt)
            result = result.strip()
            
            filep = open(logFileName, 'wb+')
     
            filep.write("Results of command: " + command + os.linesep)
     
            # Write out the results of the command to our log file
            filep.write(result + os.linesep)
            
            # Close the log file
            filep.close()
     
        LaunchViewer(LOG_DIRECTORY)
     
     
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def LaunchViewer(filename):
        try:
            os.startfile(filename)
        except AttributeError:
            subprocess.call(['open', filename])
     
     
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def NN(number, digitCount):
        # Normalizes a single digit number to have digitCount 0s in front of it
        format = "%0" + str(digitCount) + "d"
        return format % number
     
     
    main()


6.发送命令,读取反馈值

    # $language = "python"
    # $interface = "1.0"
     
    def Main():
        szPrompt = ">"
     
        objTab = crt.GetScriptTab()    #生成一个当前选项卡对象,以后所有的操作都,基于在此选项卡内工作
        objTab.Screen.Synchronous = True
     
        objTab.Screen.IgnoreEscape = True
        sendCmd = "1"
        objTab.Screen.Send(sendCmd + "\r\n")  #发送一个命令到shell, 注意要加换行符,才可以真正发出去
     
        objTab.Screen.WaitForString(sendCmd + "\r\n")  #这个命令的作用是,如果下面要截取ack的文本则不包含send部分,如果注掉,则截取的text包含send部分
     
        szResult = objTab.Screen.ReadString(szPrompt) #截取到提示符的所有文本
        
        if '1' not in szResult:
            crt.Dialog.MessageBox('not!')
        else:
            crt.Dialog.MessageBox('yes!')
            
        # 弹出消息显示读到的信息,只适合作简单的判断,不适合做全自动脚本,因为提示框只有按下yes,才可以继续
     
    Main()

https://wenku.baidu.com/view/6263eddf960590c69ec376b5.html

发布了165 篇原创文章 · 获赞 46 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/f2157120/article/details/104233806
今日推荐