Welcome to the VanDyke Software Forums

Join the discussion today!


Go Back   VanDyke Software Forums > Scripting

Reply
 
Thread Tools Rate Thread Display Modes
  #1  
Old 04-19-2017, 08:24 AM
HSA HSA is offline
Registered User
 
Join Date: Apr 2014
Posts: 21
Get all button bar names

Hi,

Is there a way you can get the names of all button bars used?
In below vbscript code you get the current visible button bar, but I would like to get the names of all button bars?

Code:
Set objTab = crt.GetScriptTab
Set objConfig = objTab.Session.Config
szButtonBarname = objConfig.GetOption("User Button Bar Name")
Reply With Quote
  #2  
Old 04-19-2017, 10:13 AM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 765
SecureCRT doesn't provide a crt.* API for accessing all button bars currently defined.

I've added a feature request for you, such that if such an API were ever to be added to SecureCRT's scripting capabilities, we'll post here. If you want email notification rather than having to monitor this specific forum post, feel free to send email to support@vandyke.com referencing this forum thread (Forum Thread #12669).

In the mean time, you would have to read in the data from the button bar configuration file, and parse out the lines that contain the button bar names.

I've included example code below showing how it can be done in either python or vbscript (this example shows how you can cycle through button bars; a task that requires knowing all of the button bar names).

Note: The script code I've provided may only work for SecureCRT versions new enough to have button bar definitions stored in the ButtonBarV4.ini file. It's also possible that future versions of SecureCRT released years from now may have a different format that would require modification of this script (probably the regular expression that extracts the information) in order to work properly. But, you should be able to get the idea.

Python code
Code:
#$language = "Python"
#$interface = "1.0"

# CycleThroughButtonBars.py
#   Last Modified:
#     19 Apr, 2017
#        - Improved detection of current configuration folder
#     
#     05 May, 2016
#        - Initial version
#
# Description:
#   This script will cycle through all button bars, activating the "next" one
#   in sequence, and repeating starting with the first button bar when the last
#   button bar is activated.
#
# Usage:
#   You could map this to a button on the button bar, but if you do, it is
#   suggested that you add a button in the left-most position to all your
#   button bars that runs this script (so that you can click through to
#   cycle through each button bar). This might involve a lot of overhead,
#   and since buttons on the button bar currently aren't global, you may
#   wish to instead map a key to run this script (use the Default session to
#   edit Terminal -> Emulation -> Mapped Keys and then apply that to all your
#   sessions).
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import datetime, os, platform, re, sys
import codecs

MsgBox = crt.Dialog.MessageBox

# Set up a dictionary in which we'll keep track of all the button bar
# names read in from the ButtonBarV4.ini file.
g_cButtonBars = {}

# You can map one key to cycle down (forwards) through button bars
# and another key to cycle up (backwards) through button bars, by
# sending the arg "down" or "up", respectively.
g_strDirection = "down"
if crt.Arguments.Count > 0:
    strArg = crt.Arguments.GetArg(0)
    if strArg.lower() in ["up", "reverse", "backwards", "backward"]:
        g_strDirection = "up"

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():
    # Make our global variables available to us in this routine
    global g_cButtonBars
    
    # Get SecureCRT's configuration path so we can read in the button
    # bar definitions from the ButtonBarV4.ini file.
    strConfigPath = GetSecureCRTConfigPath()
    strButtonBarFilePath = "{0}/ButtonBarV4.ini".format(strConfigPath)
    
    bButtonBarOn = crt.Session.Config.GetOption("User Button Bar")
    
    if strConfigPath <> "":
        if os.path.isfile(strButtonBarFilePath):
            regexp = re.compile("(Z\:\")(.*?)(\=)([a-zA-Z0-9]+)", re.I + re.M)
            with codecs.open(strButtonBarFilePath, "r", "utf-8") as objFile:
                nCurLine = 0
                strLastButtonBarName = ""
                nSubLinesToRead = 0
                for strLine in objFile:
                    nCurLine += 1
                    objMatch = regexp.search(strLine)
                    if objMatch:
                        # Grab the name of the button bar out of the 2nd
                        # grouping match() from the regular expression
                        strLastButtonBarName = objMatch.group(2)
                        # Actually add a new item to our collection of button
                        # bar names... value of the key is an empty string,
                        # but that's by design... we are only using the
                        # collection as an associative array.
                        g_cButtonBars[strLastButtonBarName] = ""
                        
            # Button bar names might not be sorted in the .ini file, and
            # in order to cycle through in an alphabetical way, we'll sort
            # what we've read in.
            cSortedButtonBarNames = sorted(g_cButtonBars.keys())
            
            # Find out what the current button bar is:
            strCurButtonBar = crt.Session.Config.GetOption("User Button Bar Name")
            
            # Let's get the name of the next/prev button bar...
            strNextButtonBar = ""
            for i in range(0, len(g_cButtonBars)):
                # Check if this iteration through the loop has a value of 'i'
                # that matches the current button bar name:
                if cSortedButtonBarNames[i] == strCurButtonBar:
                    # Determine if we are going "down" (forwards)
                    # or "up" (backwards)...
                    if g_strDirection == "up":
                        if i < len(g_cButtonBars) - 1:
                            strNextButtonBar = cSortedButtonBarNames[i + 1]
                        else:
                            strNextButtonBar = cSortedButtonBarNames[0]
                        break
                    else:
                        if i == 0:
                            strNextButtonBar = cSortedButtonBarNames[len(g_cButtonBars) - 1]
                        else:
                            strNextButtonBar = cSortedButtonBarNames[i - 1]
            
            # It could be that this session doesn't have any button bar name set,
            # in which case, we have to start somewhere... start with the Default
            # button bar:
            if strNextButtonBar == "":
                strNextButtonBar = "Default"
                
            # Now, actually change the button bar for this session
            crt.Session.Config.SetOption("User Button Bar Name", strNextButtonBar)
            
            # Make sure this session is set to actually use a button bar (or else
            # the change above won't be realized in the UI:
            if not bButtonBarOn:
                crt.Session.Config.SetOption("User Button Bar", True)
            
            crt.Session.SetStatusText("BB: {0}".format(strNextButtonBar))
            return
            
        else:
            MsgBox("Unable to locate ButtonBarV4.ini file in config path: " +
                strConfigPath)
            return
            
    else:
        # Unable to read existing color schemes from the Color Schemes.ini file
        MsgBox(
            "Error: Unable to determine location of current configuration " + 
            "path order to load existing button bar definitions.\r\n\r\n" + 
            "You are probably running SecureCRT with a configuration folder " + 
            "that exists where SecureCRT.exe lives, or you're running with " + 
            "the /F <special_path_to_config_folder> option, and we can not " + 
            "cope with that in SecureCRT yet.\r\n\r\n"  + 
            "Script is unable to proceed further.")
        return
    
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def GetSecureCRTConfigPath():
    # Try and get at where your configuration folder is located
    strOptionName = "Upload Directory V2"
    strOrigValue = crt.Session.Config.GetOption(strOptionName)
    
    crt.Session.Config.SetOption(strOptionName, "${VDS_CONFIG_PATH}\\")
    # Make the change, so that the above templated name will get written
    # to the config...
    crt.Session.Config.Save()
    
    # Now, load a fresh copy of the config, and pull the option... so
    # that SecureCRT will convert from the template path value to the
    # actual path value:
    objConfig = crt.OpenSessionConfiguration(crt.Session.Path)
    strConfigPath = objConfig.GetOption(strOptionName)
    
    # Now, let's restore the setting to its original value
    crt.Session.Config.SetOption(strOptionName, strOrigValue)
    crt.Session.Config.Save()
    
    # Now return the config path
    return strConfigPath



main()
VBScript code
Code:
#$language = "VBScript"
#$interface = "1.0"

' CycleThroughButtonBars.vbs
'   Last Modified: 19 Apr, 2017
'     - Initial version (translated from earlier python code example)
'
' Description:
'   This script will cycle through all button bars, activating the "next" one
'   in sequence, and repeating starting with the first button bar when the last
'   button bar is activated.
'
' Usage:
'   You could map this to a button on the button bar, but if you do, it is
'   suggested that you add a button in the left-most position to all your
'   button bars that runs this script (so that you can click through to
'   cycle through each button bar). This might involve a lot of overhead,
'   and since buttons on the button bar currently aren't global, you may
'   wish to instead map a key to run this script (use the Default session to
'   edit Terminal -> Emulation -> Mapped Keys and then apply that to all your
'   sessions).
'
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

' Set up a dictionary in which we'll keep track of all the button bar
' names read in from the ButtonBarV4.ini file.
Set g_cButtonBars = CreateObject("Scripting.Dictionary")

' You can map one key to cycle down (forwards) through button bars
' and another key to cycle up (backwards) through button bars, by
' sending the arg "down" or "up", respectively.
g_strDirection = "down"
If crt.Arguments.Count > 0 Then
    strArg = crt.Arguments.GetArg(0)
    Select Case LCase(strArg)
    Case "up", "reverse", "backwards", "backward"
        g_strDirection = "up"
    End Select
End If

' Other global variables we'll need
Set g_fso = CreateObject("Scripting.FileSystemObject")
Set g_shell = CreateObject("WScript.Shell")

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sub Main():   
    ' Get SecureCRT's configuration path so we can read in the button
    ' bar definitions from the ButtonBarV4.ini file.
    strConfigPath = GetConfigPath()
    strButtonBarFilePath = strConfigPath & "\ButtonBarV4.ini"
    
    bButtonBarOn = crt.Session.Config.GetOption("User Button Bar")
    
    If strConfigPath <> "" Then
        If g_fso.FileExists(strButtonBarFilePath) Then
            Set re = New RegExp
            re.Global = True
            re.MultiLine = True
            re.Pattern = "(Z\:"")(.*?)(""=)([a-zA-Z0-9]+)"
            Set objFile = g_fso.OpenTextFile(strButtonBarFilePath, 1, False)
            strFileData = objFile.ReadAll
            objFile.Close
            nCurLine = 0
            strLastButtonBarName = ""
            nSubLinesToRead = 0
            vLines = Split(strFileData, vbcrlf)
            For Each strLine in vLines
                nCurLine = nCurLine + 1
                If re.Test(strLine) Then
                    Set objMatch = re.Execute(strLine)(0)
                    ' Grab the name of the button bar out of the 2nd
                    ' grouping match() from the regular expression
                    strLastButtonBarName = objMatch.Submatches(1)
                    ' Actually add a new item to our collection of button
                    ' bar names... value of the key is an empty string,
                    ' but that's by design... we are only using the
                    ' collection as an associative array.
                    g_cButtonBars.Add strLastButtonBarName, ""
                End If
            Next
                        
            ' Button bar names might not be sorted in the .ini file, and
            ' in order to cycle through in an alphabetical way, we'll sort
            ' what we've read in.
            SortDictionary g_cButtonBars, 1
            cSortedButtonBarNames = g_cButtonBars.keys()
            
            ' Find out what the current button bar is:
            strCurButtonBar = crt.Session.Config.GetOption("User Button Bar Name")
            
            ' Let's get the name of the next/prev button bar...
            strNextButtonBar = ""
            For i = 0 To g_cButtonBars.Count - 1
                ' Check if this iteration through the loop has a value of 'i'
                ' that matches the current button bar name:
                If cSortedButtonBarNames(i) = strCurButtonBar Then
                    ' Determine if we are going "down" (forwards)
                    ' or "up" (backwards)...
                    If g_strDirection = "up" Then
                        If i < g_cButtonBars.Count - 1 Then
                            strNextButtonBar = cSortedButtonBarNames(i + 1)
                        Else
                            strNextButtonBar = cSortedButtonBarNames(0)
                        End If
                        Exit For
                    Else
                        If i = 0 Then
                            strNextButtonBar = cSortedButtonBarNames(g_cButtonBars.Count - 1)
                        Else
                            strNextButtonBar = cSortedButtonBarNames(i - 1)
                        End If
                    End If
                End If
            Next
            
            ' It could be that this session doesn't have any button bar name set,
            ' in which case, we have to start somewhere... start with the Default
            ' button bar:
            If strNextButtonBar = "" Then strNextButtonBar = "Default"
                
            ' Now, actually change the button bar for this session
            crt.Session.Config.SetOption "User Button Bar Name", strNextButtonBar
            
            ' Make sure this session is set to actually use a button bar (or else
            ' the change above won't be realized in the UI:
            If not bButtonBarOn Then
                crt.Session.Config.SetOption "User Button Bar", True
            End If
            
            crt.Session.SetStatusText "BB: " & strNextButtonBar
            
            Exit Sub
            
        Else
            crt.Dialog.MessageBox _
                "Unable to locate ButtonBarV4.ini file in config path: " & _
                strConfigPath
            Exit Sub
        End If
            
    Else
        ' Unable to read existing color schemes from the Color Schemes.ini file
        crt.Dialog.MessageBox _
            "Error: Unable to determine location of current configuration " & _
            "path in order to load existing button bar definitions.\r\n\r\n" & _
            "You are probably running SecureCRT with a configuration folder " & _
            "that exists where SecureCRT.exe lives, or you are running with " & _
            "the /F <special_path_to_config_folder> option, and we can't " & _
            "cope with that in SecureCRT yet.\r\n\r\n" & _
            "Script is unable to proceed further."
        Exit Sub
    End If
End Sub
    
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function GetConfigPath()
    ' Try and get at where your configuration folder is located
    strOptionName = "Upload Directory V2"
    strOrigValue = crt.Session.Config.GetOption(strOptionName)
    
    crt.Session.Config.SetOption strOptionName, "${VDS_CONFIG_PATH}\"
    ' Make the change, so that the above templated name will get written
    ' to the config...
    crt.Session.Config.Save
    
    ' Now, load a fresh copy of the config, and pull the option... so
    ' that SecureCRT will convert from the template path value to the
    ' actual path value:
    Set objConfig = crt.OpenSessionConfiguration(crt.Session.Path)
    strConfigPath = objConfig.GetOption(strOptionName)
    
    ' Now, let's restore the setting to its original value
    crt.Session.Config.SetOption strOptionName, strOrigValue
    crt.Session.Config.Save
    
    ' Now return the config path
    GetConfigPath = strConfigPath
End Function

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function SortDictionary(objDict, nWhatToSort)
' Code provided by Microsoft as an example of how to sort items in a dictionary:
'   http://support.microsoft.com/kb/246067
    ' nWhatToSort should be passed in as:
    '    1 if you wish to sort keys.
    '    2 if you wish to sort values, instead of keys.
    intSort = nWhatToSort
    
    Const dictKey = 1
    Const dictItem = 2
    
    Dim strDict()
    Dim objKey
    Dim strKey, strItem
    Dim X, Y, Z

    ' get the dictionary count
    Z = objDict.Count

    ' We need more than one item to warrant sorting
    If Z > 1 Then
    ' Create an array to store dictionary information
    ReDim strDict(Z, 2)
    X = 0
    ' Populate the string array
    For Each objKey In objDict
        strDict(X, dictKey) = CStr(objKey)
        strDict(X, dictItem) = CStr(objDict(objKey))
        X = X + 1
    Next

    ' Perform a shell sort of the string array
    For X = 0 to (Z - 2)
        For Y = X to (Z - 1)
            If StrComp(strDict(X, intSort), _
                       strDict(Y, intSort), _
                       vbTextCompare) > 0 Then
                strKey = strDict(X,dictKey)
                strItem = strDict(X,dictItem)
                strDict(X, dictKey) = strDict(Y, dictKey)
                strDict(X, dictItem) = strDict(Y, dictItem)
                strDict(Y, dictKey) = strKey
                strDict(Y, dictItem) = strItem
            End If
        Next
    Next

    ' Erase the contents of the supplied dictionary object
    objDict.RemoveAll

    ' Re-populate the dictionary with the sorted information
    For X = 0 to (Z - 1)
      objDict.Add strDict(X, dictKey), strDict(X, dictItem)
    Next

    End If
End Function

Code files attached (see below or header links above).

Does this help?

--Jake
Attached Files
File Type: txt CycleThroughButtonBars.py.txt (7.3 KB, 34 views)
File Type: txt CycleThroughButtonBars.vbs.txt (9.6 KB, 39 views)
__________________
Jake Devenport
VanDyke Software
Technical Support
support@vandyke.com
http://www.vandyke.com/support
Reply With Quote
  #3  
Old 04-21-2017, 03:47 AM
HSA HSA is offline
Registered User
 
Join Date: Apr 2014
Posts: 21
Hi Jake,

Thanks for the quick reply and the suggestion! I tried a simpler approach, it just searches through the ButtonBarV4.ini file for all the names of the buttonbars, puts them in an array and lets you select one from an inputbox.

Code:
Sub Main
	Dim buttonArray(50)
	
	Set objShell = CreateObject( "WScript.Shell" )
	appDataLocation=objShell.ExpandEnvironmentStrings("%APPDATA%")	
	buttonBarFilePath = appDataLocation & "\VanDyke\Config\ButtonBarV4.ini"
	
	Set objShell = Nothing
	
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set Filecontent = objFSO.OpenTextFile(buttonBarFilePath, 1, 2)
	content = Filecontent.ReadAll
	lines = Split(content, vbcr)
	
	For i=0 to Ubound(lines)
		beforeButton = Instr(1, lines(i), chr(34))
		If beforeButton <> "0" Then
			afterButton = Instr(beforeButton + 1, lines(i), chr(34))
			buttonName = Mid(lines(i), beforeButton + 1, afterButton - beforeButton - 1)
			buttonArray(x) = buttonName
			x = x + 1
		End If
	Next
	
	Set objFSO = Nothing
	Set Filecontent = Nothing
	
	For buttonIndex = 0 to x - 1
		buttonBox = buttonBox & vbcrlf & "(" & buttonIndex + 1 & ") " & buttonArray(buttonIndex)
	Next
	
	selectedButton = Inputbox ("Please select the button bar you want to toggle?" & vbCrlf & buttonBox & vbCrlf, "Select button bar")
	
	If IsNumeric(selectedButton) Then
		If selectedButton => 1 and Abs(selectedButton) =< x Then
			crt.Session.Config.SetOption "User Button Bar Name", buttonArray(selectedButton - 1)
		Else
			crt.Dialog.MessageBox "You entered " & selectedButton & " which is an incorrect input, please enter a nr between 1 and " & x, "Incorrect input", ICON_STOP
		End If
	Else
		crt.Dialog.MessageBox "You entered " & selectedButton & " which is a non numeric input, please enter a nr between 1 and " & x, "Non numeric input", ICON_STOP
	End If
End Sub
Reply With Quote
Reply

Tags
button bar name


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -6. The time now is 04:09 AM.