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 06-24-2014, 01:47 AM
chiwee chiwee is offline
Registered User
 
Join Date: Mar 2014
Posts: 5
Script Close my SecureCRT

Hi all,

I am newbie to script. I downloaded a script from tnygren called "ConnectToMultipleHostsAndSendCommands.vbs".

I need to connect to my SSH server before I can make any connection to my routers and capture the commands output.

Each time I run the script, it will automatically closed my session having an error "Unable to connect to host: 192.168.1.1
Error (-518193145): Connection failed".

I believe this script do not allow to run on any existing connection and connect to the host specific under g_vHosts. How can I modify this script have a prompt for username and password (one time) and connects to all the g_vHosts specific under the list?

Below are output of the script: (Courtesy to tnygren)

Code:
#$language = "VBScript"
#$interface = "1.0"
' ConnectToMultipleHostsAndSendCommands.vbs

Option Explicit

Dim g_shell, g_fso
Set g_shell = CreateObject("WScript.Shell")
Set g_fso   = CreateObject("Scripting.FileSystemObject")

' Array of target hosts to which we will be connecting
dim g_vHosts(100)
g_vHosts(0) = "192.168.1.1"
' g_vHosts(1) = "192.168.0.2"
' g_vHosts(2) = "192.168.0.3"
' g_vHosts(3) = "192.168.0.123"
' g_vHosts(4) = "192.168.0.131"
' g_vHosts(5) = ""
' g_vHosts(6) = ""
' g_vHosts(7) = ""
' g_vHosts(8) = ""
' ...

' List of commands that we will issue on each host after
' we are connected
dim g_vCommands(2)
g_vCommands(0) = "show run | i line vty"
g_vCommands(1) = "show run | i username"

' What we'll be waiting for each time we run a command so that
' we know the command has finished (since our shell prompt will
' appear once again after each command)...
Dim g_szPrompt
g_szPrompt = "#"

' We'll log to a separate file for each connection/host, and
' we'll place the log files in the current user's "My Documents"
' folder...
Dim g_szLogNameTemplate
g_szLogNameTemplate = g_shell.SpecialFolders("MyDocuments") & _
	"\MM-DD-YYYY - HOST.log"

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sub Main()
    Dim nIndex, szHost
    
    ' Iterate over each of the hosts stored in the g_vHosts array (defined
    ' above)...
    For nIndex = 0 to uBound(g_vHosts) - 1
        szHost = Trim(g_vHosts(nIndex))
  
        ' If the szHost is empty, it means we've gone through all
        ' populated elements of our g_vHosts array, and we should
        ' quit now.
        if szHost = "" then exit For

        ' Reset logging to 'off'
        crt.session.Log False

        ' Disconnect from any previous connection we have made that for any
        ' reason might not have been disconnected yet.
        If crt.Session.Connected = True then
            crt.session.Disconnect
        end if

        ' Set a log file name for this next connection and enable logging.
        Dim szLogFilename
        szLogFilename = g_szLogNameTemplate
        szLogFilename = Replace(szLogFilename, "HOST", szHost)
        szLogFilename = Replace(szLogFilename, "MM", NN(Month(Now)))
        szLogFilename = Replace(szLogFilename, "DD", NN(Day(Now)))
        szLogFilename = Replace(szLogFilename, "YYYY", Year(Now))

        ' Turn off normal error handling so that we can detect Connection
        ' errors rather than popping up a messagebox, interrupting the script.
        On Error Resume Next

        ' Choose your connect method
        '
        ' The use of the /Telnet connection method will require additional logic
        ' for detecting the username and password prompts (using
        ' crt.screen.WaitForString) and entering these values in order to
        ' authenticate successfully before running any commands.
        '      crt.session.connect "/Telnet " & szHost
        '
        ' For this example, we'll be using the SSH2 connection protocol, in
        ' which we can supply the username and password used for authentication.
        crt.session.connect "/SSH2 /L user /PASSWORD password" & szHost

        ' You might instead want to use a defined session to connect rather than
        ' providing all the connection information literally.  The following
        ' connection method requires that the values in g_vHosts (defined above,
        ' outside of Main()) are session names, rather than hostnames or IP
        ' addresses
        '      crt.session.connect "/S " & szHost

        If Err.Number = 0 then
            ' We've connected successfully.  Restore Error handling before
            ' proceeding.
            On Error Goto 0
            
            crt.screen.synchronous = true
            
            ' Now that we have connected, turn on logging
            ' for this connection
            crt.session.logfilename = szLogFilename
            crt.session.log True

            ' Let's issue commands
            Dim nCommandIndex
            For nCommandIndex = 0 to UBound(g_vCommands) - 1
                crt.Screen.Send g_vCommands(nCommandIndex) & vbcr
                
                ' Wait for the command to complete. If you want this to time out
                ' after a number of seconds, provide a timeout value to the
                ' WaitForString command as in:
                '     nResult = crt.Screen.WaitForString(g_szPrompt, 100)
                ' A command like the one above will wait for the value of
                ' g_szPrompt for 100 seconds and return false if the timeout
                ' occurs before the prompt string is detected.
                '
                ' For this example, we'll just wait forever.
                crt.Screen.WaitForString g_szPrompt
            Next
        Else
            ' We didn't connect successfully.  We should record this information
            ' in the debug log file for this connection.  Capture the 'Err'
            ' object's properties before restoring normal handling so we don't
            ' lose this information should another error occur.
            Dim szErrorDescription, nErrorCode
            nErrorCode = Err.Number
            szErrorDescription = Err.Description
            
            ' Now restore normal error handling
            On Error Goto 0
            
            Dim objFile
            Set objFile = g_fso.OpenTextFile(szLogFileName, 2, True)
            objFile.Write "Unable to connect to host: " & szHost & vbcrlf & _
                          "  Error (" & nErrorCode & "): " & szErrorDescription
            objFile.Close
        End if

        ' Disconnect from the current connection and turn off logging
        If crt.Session.Connected = True then
            crt.session.Log False
            crt.session.Disconnect
        end if

    ' Now that we've disconnected and turned off logging, let's move
    ' on to the next host...
    Next

    ' Once we've completed the commands and disconnected from the last host,
    ' we can close SecureCRT.
    crt.Quit
    
End Sub

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function NN(nNumber)
' Normalizes a single digit number to have a 0 in front of it
    NN = nNumber
    If nNumber < 10 Then NN = "0" & nNumber
End Function

Last edited by rtb; 06-24-2014 at 07:07 AM.
Reply With Quote
  #2  
Old 06-24-2014, 07:10 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,305
Hi chiwee,

Thanks for the post. What is the version of SecureCRT that you are using?

It sounds like you are connecting through a jump server or terminal server.

How do you use SecureCRT to manually connect to devices that are behind the server?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #3  
Old 06-24-2014, 08:45 PM
chiwee chiwee is offline
Registered User
 
Join Date: Mar 2014
Posts: 5
I am using version 7.2.

Yup all my equipment required me to login to the Jump Server before I can access the devices.

Public Internet --> Jump Server --> Routers

Fyi we only allow SSH.
Reply With Quote
  #4  
Old 06-24-2014, 11:41 PM
chiwee chiwee is offline
Registered User
 
Join Date: Mar 2014
Posts: 5
I happen to come across the script created by bgagnon "JumpHost-HandleSecondaryHostConnectionAttempts.vbs" which match my first requirement.

Now I need to combine "ConnectToMultipleHostsAndSendCommands.vbs" with "JumpHost-HandleSecondaryHostConnectionAttempts.vbs" and it should meet my requirement.

Trying to figure it out on how to do it. Here is the code for JumpHost:

Code:
' JumpHost-HandleSecondaryHostConnectionAttempts.vbs
'
'   - NOTE: SecureCRT must currently be connected to a gateway machine or  
'     jump host on which commands can be issued to connect to secondary hosts 
'     (eg: 'ssh hostb', 'telnet hostc', etc.)


crt.Screen.Synchronous = True
vHosts = Array(_
    "192.168.0.1",_
    "192.168.1.1",_
    "192.168.0.2")
' The order of elements in this array should be in the order of: 
'  - Expected login prompts (eg: "-->", "#", etc.)
'  - Special cases (accept host key, enter pwd, enter username, etc.)
'  - Fail/Bail cases (wrong pwd/login, hostname not found, time out, etc.)
vPossibleResponses = Array(_
    "-->",_
    "$",_
    "ogin:", _
    "ame:", _
    "(yes/no)?",_
    "sword:",_
    "Permission denied",_
    "incorrect", _
    "not known", _
    "timed out")
    
nIndex = 0
strJumpHostPrompt = "-->"
Do
    strCommand = "ssh user@" & vHosts(nIndex)
    crt.Screen.Send strCommand & vbcr
    
    ' Wait for our command to be echoed back to us so we know that it has been
    ' received before we attempt to wait for all possible responses.
    crt.Screen.WaitForString strCommand & vbcr
    
    ' Start an inner Do..Loop that looks for all defined possible responses to
    ' the Telnet... or SSH... command we just sent.
    Do
        crt.Screen.WaitForStrings vPossibleResponses
        If crt.Screen.MatchIndex > 0 Then
            strStringFound = vPossibleResponses(crt.Screen.MatchIndex - 1)
        End If
        Select Case crt.Screen.MatchIndex
            Case 1,2
                ' Found "-->" or "$" which in our example indicate successful
                ' authentications.
                
                ' Do work we need to complete on host including sending the exit
                ' command which will disconnect us from the secondary host
                ' allowing us to loop up to the top and connect to the next
                ' host. Note that the strStringFound variable currently contains  
                ' the "Secondary Host Prompt" if needed.
                ' .
                ' .
                ' .
                
                ' Now that we have done the necessary work (including waiting
                ' for an indication that the last command we sent above has
                ' completed, send "exit" to disconnect from secondary host.
                crt.Screen.Send "exit" & vbcr
                
                ' Wait for an indication that the exit command was successful
                ' before attempting to connect to next host.
                crt.Screen.WaitForString strJumpHostPrompt
                
                ' Exit inner Do..Loop since we are done with the success case.
                Exit Do
                
            Case 3,4
                ' Found "ogin" or "ame" which means waiting for user account.
                crt.Screen.Send strUsername & vbcr

                ' Fall through to the top of the inner Do..Loop to continue
                ' waiting for strings until all possibilities are exhausted.

            Case 5
                ' Found new hostkey prompt.  This indicates that this is the
                ' first time we have connected to the remote machine, and we
                ' need to accept the hostkey.    
                crt.Screen.Send "yes" & vbcr
                
                ' Fall through to the top of the inner Do..Loop to continue
                ' waiting for strings until all possibilities are exhausted.
            
            Case 6
                ' We are being prompted for a password.  Send it.
                crt.Screen.Send strPassword & vbcr
                
                ' Fall through to the top of the inner Do..Loop to continue
                ' waiting for strings until all possibilities are exhausted.
                
            Case 7
                ' SSH Password was denied or login was incorrect.  Exit this   
                ' inner Do..Loop and move on to the next host.
                
                ' First cancel the current authentication attempt to the
                ' secondary host.
                crt.Screen.SendKeys "^c"
                
                ' Wait for an indication that the Ctrl+C was successful before
                ' attempting to connect to next host.
                crt.Screen.WaitForString strJumpHostPrompt

                ' Exit inner Do..Loop and move to next host.
                Exit Do
                
            Case 8
                ' Telnet login or password was incorrect.  Exit this inner  
                ' Do..Loop and move on to the next host.
                
                ' First cancel the current authentication attempt to the
                ' secondary host.
                crt.Screen.SendKeys "^]"
                crt.Screen.WaitForString "telnet>"
                crt.Screen.Send "quit" & vbcr
                
                ' Wait for an indication that the Ctrl+C was successful before
                ' attempting to connect to next host.
                crt.Screen.WaitForString strJumpHostPrompt
                
                ' Exit inner Do..Loop and move to next host.
                Exit Do
                
            Case 9,10
                ' Not able to reach secondary host.  Connection timed out.  
                ' Wait for primary host prompt before exiting inner Do..Loop.
                crt.Screen.WaitForString strJumpHostPrompt
                
                ' Exit inner Do..Loop and move to next host.
                Exit Do
                
            Case Else
                ' Let user know that there is an unhandled case
                crt.Session.SetStatusText _
                    "Unhandled """ & strStringFound & """"
                ' Yikes... Never expect to be here, but if we got here, it's
                ' probably a programming error you've introduced with the
                ' 'vPossibleResponses' variable that you'll need to fix
                crt.Dialog.MessageBox "Yikes!" & vbcrlf & vbcrlf & _
                    "We never expect to get here. if you see this, you" & _
                    vbcrlf & _
                    "have probably introduced a programming error into" & _
                    vbcrlf & _
                    "your script code which will you will need to fix." & _
                    vbcrlf & vbcrlf & _
                    "Chances are you added a string to vPossibleResponses " & _
                    vbcrlf & _
                    "but you haven't added the code to handle " & _
                    vbcrlf & _
                    "what to do when that special string was found:" & _
                    vbcrlf & vbcrlf & vbtab & """" & strStringFound & """"
                crt.Screen.SendSpecial "MENU_SCRIPT_CANCEL"
                
            End Select
    Loop ' Inner loop waiting for all possible responses.

    nIndex = nIndex + 1
    
    ' Exit outer Do..Loop if we have attempted to connect to all hosts.
    If nIndex > Ubound(vHosts) Then Exit Do
    
Loop ' Outer loop connecting to all hosts in array.
Reply With Quote
  #5  
Old 06-25-2014, 07:49 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,305
Hi chiwee,

Thanks for the update. I don't think that you need to reinvent the wheel as it were.

We have an example script in both VBScript and Python that should be fairly close to what you want to do at the following location:
https://forums.vandyke.com/showthrea...7294#post37294
Does this help you accomplish your goal?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #6  
Old 06-25-2014, 08:00 PM
chiwee chiwee is offline
Registered User
 
Join Date: Mar 2014
Posts: 5
Hi rtb (Todd),

Almost got it. Just that the authentication that my cisco and juniper routers handle within the terminal window. It doesn't prompt for username and password.

I will spend more time study on vb scripting today and will revert if I managed to sort it out.

Reply With Quote
  #7  
Old 06-26-2014, 07:43 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,305
Hi chiwee,

Thanks for the update.

Can you tell me more about the issue?

Are you not seeing prompts in the terminal window and that is causing the problem?

Are you not able to handle the enable prompt?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #8  
Old 06-30-2014, 10:22 AM
chiwee chiwee is offline
Registered User
 
Join Date: Mar 2014
Posts: 5
Hi Todd,

Sorry on the late reply. Let me explain my issue so that you can have a clearer picture.

I would need to login several routers to capture some commands output such as version, ntp and interface etc.

With such requirement, your script "ReadDataFromHostFile-SendCommandsFromCommandsFile-LogResultsToIndividualFiles" would really serve the purpose.

However I am facing some login issue on the script. My environment required me to login to a jump host before I could login to our routers.

After authenticate with my jump host, I am required to enter command "ssh user@192.168.1.1".

I would received such prompt:

user@192.168.1.1's password:

Which I would enter my password and I am successful authenticate into the router.

This is where I would start to run those commands and captured the output.

Once done, i would issue a command call exit and loop to next host in the list and resume the same process until all hosts is completed.

Sorry on the lengthy text, hope this would provide you a clearer picture.
Reply With Quote
  #9  
Old 06-30-2014, 12:17 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,305
Hi chiwee,

Thanks for the update. I understand the situation. Anything you do will take more effort than just changing a couple of lines of code.

If you want "ReadDataFromHostFile-SendCommandsFromCommandsFile-LogResultsToIndividualFiles" to handle the jumphost connection, then you could use the scripts Connect() function outside of the For...Loop (lines 159 to 171, but they can't be moved without modification).

You would also need to create an additional function that doesn't connect using the Session object methods. The function would connect by sending a command using the Screen object, and handle authentication. You could use some of the Jumphost example script code as the foundation of the function. You don't actually need another function, but using a function may make the code easier to maintain. Once you have a new function, lines 159 to 164 would not be needed, and line 168 would call the new function, but pass in the hostname (g_strHost) rather than the connection string. Here is some pseudo code:
Code:
If Not JumpConnect(g_strHost) Then
    ...
Else
    ...
End If

Function JumpConnect(strHost)

    g_objTab.Screen.Send "ssh user@" & strHost & vbcr
    ....
    If you get connected Then
        JumpConnect = True
    Else
        JumpConnect = False
    End If

End Function
Does this help you add the functionality that you are seeking?
__________________
--Todd

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 07:31 PM.