Welcome to the VanDyke Software Forums

Join the discussion today!


Go Back   VanDyke Software Forums > Scripting

Notices

Reply
 
Thread Tools Rate Thread Display Modes
  #1  
Old 07-06-2017, 04:54 AM
Omoreno Omoreno is offline
Registered User
 
Join Date: Jul 2017
Posts: 3
Connect to multiple predefined sessions through Sessions Window or a Dialogbox

Hi, I recently made a script to connect to all sessions that are already created in SecureCRT. Ít works great:

Code:
import os
import sys
import datetime

my_session_dir = "~/AppData/Roaming/VanDyke/Config/Sessions/"
my_site_dir = ""

strHome = os.path.expanduser("~")
global g_strMyDocs
g_strMyDocs = strHome + "/Desktop/Script_SecureCRT/"
global commandsFile
commandsFile = g_strMyDocs + "Commands.txt"


g_strDateTimeTag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S.%f")[:19]

def ExpandPath(base_path):
    if base_path[0:2] == "~/":
        base_path = os.path.join(os.path.expanduser('~'), base_path[2:])
    elif base_path[0] != "/" or base_path[0] != "\\":
        base_path = os.path.join(os.path.expanduser('~'), base_path)
    return base_path

def GetSessions(Session_Dir, Site_Dir):
    '''
    This function will get all the session names in a starting directory and all
    subdirectories.
    '''
    # Files in Session directories to ignore
    blacklist = ["__FolderData__.ini", "Default.ini"]

    # Extention of all Session files in .ini so we'll only look for those
    extension = ".ini"

    # Get list of Sessions
    SessionList = []
    Root_Dir = ExpandPath(Session_Dir) + Site_Dir
    for root, dirs, files in os.walk(Root_Dir):
        for file in files:
            if file.endswith(extension):
                if not file in blacklist:
                    if dirs:
                        session_name = Site_Dir + str(dirs) + (os.path.splitext(file)[0])
                    else:
                        session_name = Site_Dir + (os.path.splitext(file)[0])
                    SessionList.append(session_name)

    return SessionList



def main():
	
    errorMessages = ""
    
    # Get Sessions
    sessionsArray = GetSessions(my_session_dir, my_site_dir)

    global commandsFile
    commandsFile = crt.Dialog.FileOpenDialog(
        "Please select the COMMANDS data file to be imported.",
        "Open",
        commandsFile,
        "Text Files (*.txt)|*.txt|CSV Files (*.csv)|*.csv||")        

    if commandsFile == "":
        return
    
    # Connect to each session and issue a few commands, then disconnect.
    for my_session in sessionsArray:
        try:    
            crt.Session.Connect("/S \"" + my_session + "\"")
            crt.Sleep(1000)
        except ScriptError:
            error = crt.GetLastErrorMessage()
        
        if crt.Session.Connected:
            
            crt.Screen.Synchronous = True
            
            strLogFolder = g_strMyDocs + "Output_Log/"
            strLogName = strLogFolder + "Log-" + my_session + "-{1}.txt".format(strLogFolder, g_strDateTimeTag)
            #crt.Screen.Send(strLogName)
            crt.Session.LogFileName = strLogName
            crt.Session.Log(True)
            
            # Note: A IOError exception will be generated if 'input.txt' doesn't exist.
            #
            for line in open(g_strMyDocs + "commands.txt", "r"):
                # Send the line with an appended CR
                #
                #crt.Screen.Send(line + '\r')
                crt.Screen.Send(line)
                # Wait for my prompt before sending the next line
                #
                crt.Screen.WaitForString("#")
            
            crt.Session.Log(False)
            
            crt.Screen.Synchronous = False
            
            # Now disconnect from the remote machine...
            crt.Session.Disconnect()
            # Wait for the connection to close
            while crt.Session.Connected == True:
                crt.Sleep(100)
            crt.Sleep(1000)
        
        else:
            errorMessages = errorMessages + "\n" + "*** Error connecting to " + my_session + ": " + error
    
    if errorMessages == "":
        crt.Dialog.MessageBox("No Errors were detected.")
    else:
        crt.Dialog.MessageBox("The following errors occurred:\n" + errorMessages)
    
    
    strLogFolder = g_strMyDocs + "/Connection_Error_Log"
    strFilename = "{0}/Log-ConnectionError-{1}.txt".format(strLogFolder, g_strDateTimeTag)
    objFile = open(strFilename, "w")
    objFile.write(errorMessages)
    objFile.close()

main()


This code works perfectly when I want to execute the same script on all sessions.

The problem now is that i want to create a new script just modifying a few things so the user can select what sessions to execute the script to.

I have seen a few scripts that allow you to connect to predefined sessions written in a text file, but that is static, I want to allow the user to select the particular sessions when this script is executed.


I have tried changing the GetSessions method for this new script, with FileOpenDialog, but even if it works like I want, it just lets you select ONE session... I want the possibility to select and connect to multiple sessions, and putting a "for" clause would not be the best solution...

Code:
Site_Dir = Site_Dir + '__FolderData__'
    Root_Dir = ExpandPath(Session_Dir) + Site_Dir
    
    selectedSessions = []
    selectedSessions = crt.Dialog.FileOpenDialog(
        "Please select the Sessions to be selected.",
        "Open",
        Root_Dir,
        "Session .ini files (*.ini)|*.ini||")        

    
    
    if selectedSessions == "":
        return
    
    
    return selectedSessions
Reply With Quote
  #2  
Old 07-06-2017, 10:50 AM
ekoranyi ekoranyi is offline
VanDyke Technical Support
 
Join Date: Jan 2017
Posts: 654
Hi Omoreno,

What Operating System are you running the script on?

If you are on Windows one option may be to use an Internet Explorer object to create a checklist. Another forum user posted an example of this functionality.
__________________
Thanks,
--Eric

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #3  
Old 07-07-2017, 01:28 AM
Omoreno Omoreno is offline
Registered User
 
Join Date: Jul 2017
Posts: 3
Hi ekoranyi,

Thanks for the reply!!

I'm using the script in SecureCRT for Windows.

Would you have a Python solution for my problem? Sadly, i'm a little rusty in Visual Basic...

Regards
Reply With Quote
  #4  
Old 07-07-2017, 09:05 AM
ekoranyi ekoranyi is offline
VanDyke Technical Support
 
Join Date: Jan 2017
Posts: 654
Hi Omoreno,

We don't currently have an example of a Python script implementing a GUI. The SecureCRT implementation of Python does not currently include any GUI elements.

I have added you to a feature request in our SecureCRT enhancement database to add custom menus. Should a future release of SecureCRT have this option, we will post to this forum thread.

Roughly how many sessions do you expect the user to be choosing from?
__________________
Thanks,
--Eric

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #5  
Old 07-10-2017, 01:46 AM
Omoreno Omoreno is offline
Registered User
 
Join Date: Jul 2017
Posts: 3
Hi ekoranyi,

I'm not sure about how many sessions would the user select each time. It would vary from 1 to a few. If it's a global change that needs to be implemented in most devices, then the user will probably apply the other script

Knowing that we cannot implement this functionality with GUI elements, is there another method to do it? Anythink you can think of?

Regards
Reply With Quote
  #6  
Old 07-10-2017, 09:27 AM
ekoranyi ekoranyi is offline
VanDyke Technical Support
 
Join Date: Jan 2017
Posts: 654
Hi Omoreno,

One option may be to use SecureCRT's Prompt Dialog to display a list of sessions and capture the selected sessions. I've included a brief example of this method.

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


SessionList = ['Session1', 'Session2', 'Session3', 'Session4']
seperator = '\n'


password = crt.Dialog.Prompt(seperator.join(SessionList), "Enter Selection", "", True)
arrSelected = selected_sessions.split()

for x in arrSelected:
	crt.Dialog.MessageBox(x)
__________________
Thanks,
--Eric

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
Reply

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 08:17 PM.