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 11-10-2014, 10:23 AM
stantonh stantonh is offline
Registered User
 
Join Date: Sep 2012
Posts: 7
Building SCRT INI sessions from CSV

Has the vbs script ImportArbitraryDataFromFileToSecureCRTSessions been converted to Python? I have about 23000 sessions to build but need to be able to allow users to import/build on Linux and Mac - not just Windows.

Thank you!
Reply With Quote
  #2  
Old 11-10-2014, 10:36 AM
ogun ogun is offline
Registered User
 
Join Date: Sep 2013
Posts: 15
Here is an excerpt from a script I made to automate shared sessions from a database.

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

# Top level folder to put all sessions in.
TOPLEVEL = "Shared"

import SecureCRT
import csv
import os.path
import shutil
import sys


def main():
    # CSV file has layout "hostname, folder, comment"
    csvfile = open('devices.csv')
    csvreader = csv.reader(csvfile)

    # Remove existing folder, we rebuild every time.
    script_name = crt.ScriptFullName
    script_dir = os.path.dirname(script_name)

    # We expect to be in $CONFIG/Scripts with the sessions in $CONFIG/Sessions
    sessions_folder = os.path.join(script_dir, '../Sessions')

    # Did we get it right?
    if not os.path.isdir(sessions_folder):
        msg = "Could not find sessions folder. Got %s" % sessions_folder
        crt.Dialog.MessageBox(msg)
        return

    # Append top level
    shared_folder = os.path.join(sessions_folder, TOPLEVEL)

    # Delete old folder
    if os.path.exists(shared_folder):
        shutil.rmtree(shared_folder)

    # Open the default session to use as a template for created sessions
    session = crt.OpenSessionConfiguration('Default')

    for line in csvreader:
        sessionname = line[0].split('.')[0]
        hostname = line[0]
        folder = TOPLEVEL + "\\" + line[1]
        comment = line[2]

        session.SetOption('Protocol Name', 'SSH2')
        session.SetOption('[SSH2] Port', 22)
        session.SetOption('Hostname', hostname)
        session.SetOption('Description', [comment])

        session.Save(folder + "\\" + sessionname)

# Do the running
main()
It requires the script file itself to be located in a specific place as unfortunately there is no easy way to find the session folder. (At least what I can find)

It will create the sessions in a session folder named Shared which it will delete everytime it's run. Each session is created by copying the default session.

Should be easy to modify according to your needs.
Reply With Quote
  #3  
Old 11-10-2014, 10:36 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi stantonh,

The script has not yet been converted. The VBScript is available, and you are welcome to convert it to Python.

The conversion is on my "when I have spare time" list, but I have not yet finished it.

It will be posted to the following location when it is converted:
https://forums.vandyke.com/showthrea...7089#post37089
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #4  
Old 11-11-2014, 11:31 AM
stantonh stantonh is offline
Registered User
 
Join Date: Sep 2012
Posts: 7
@ogun Finding Directories

Couple snippets your way for locating directories:
Function find_dir will call choose_item in case mutiple "Config" dirs are found allowing user to select. Choices always start with 1 allowing "0 to exit"


Code:
main()
    CONFIG = find_dir('.', 'Config)
    if CONFIG is None:
        # return from main() causes script to exit gracefully
        return
# above main in code        
def find_dir(dirStart, dirEnd):
    """
    Find SecureCRT's Config directory.
    :param dirStart: Starting directory
    :param dirEnd:   Last word(s) in directory name
    :return: filepath
    """
    found = []
    for root, dirs, files in os.walk(dirStart):
        if root.endswith(dirEnd):
            found.append(os.path.abspath(root))
    if len(found) == 0:
        return None
    elif len(found) == 1:
        return found[0]
    else:
        # found more than one dir fitting description
        return choose_item(found)

def choose_item(initer, title="Select item..."):
    """
    SCRT: Select individual item from enumerated iterable
    :param initer:
    :type iterable:
    :return: choice of item in iterable; 0 to exit
    :rtype: string
    """
    # noinspection PyUnusedLocal
    choice = None
    dictchoices = dict(enumerate(initer, 1))
    validchoices = range(len(dictchoices) + 1)
    msg = "Choose number from list or 0 to exit\r\n"
    for key, val in dictchoices.iteritems():
        msg += "  {0:s}  {1:s}\r\n".format(str(key), val)
    while True:
        try:
            choice = crt.Dialog.Prompt(msg, title)
        except NameError:
            msg += "{0:s}? ".format(title)
            choice = raw_input(msg)
        try:
            ichoice = int(choice)
        except ValueError:
            continue
        if ichoice in validchoices:
            if ichoice == 0:
                return None
            else:
                return dictchoices[ichoice]

Last edited by stantonh; 11-11-2014 at 12:26 PM.
Reply With Quote
  #5  
Old 11-11-2014, 12:25 PM
stantonh stantonh is offline
Registered User
 
Join Date: Sep 2012
Posts: 7
@rtb (Todd)

I'm over half way done. Up to building (or updating) the actual files. I'd prefer to update to you personally if you can help me testing. I currentlly only have Linux (Ubuntu) and Win7 (x64) testing capabilities and I'm writing for Python 2.7. I am keeping variables and function name consistent with the VBS script to make troubleshooting easier. It will be a bit more modular similar to the ReadHosts-ReadCommands-LogResults.py script.
Reply With Quote
  #6  
Old 11-11-2014, 05:46 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi stantonh,

Thanks for the update. Feel free to send an email to support@vandyke.com with a subject of Attn: Todd - import script, and I will do what I can to help.
__________________
--Todd

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


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:19 AM.