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 10-11-2016, 08:17 AM
Zander Zander is offline
Registered User
 
Join Date: Oct 2016
Posts: 11
SecureCRT Vbs Script Help

Hello all,

I'm a complete newbie to script writing so please accept my apologies in advance for wrong terminology etc.

I'm currently trying to write a script for work that helps me automate log on to the Cisco kit that I access but I've having some trouble! It works mostly but there are some aspects that don't function like I want them to, plus I think it could probably be a lot shorter? I could be wrong though!

The overall aim is for me to be able to copy an IP address and then by running the script it will SSH to the device.
I have created a 'case' to help with some of the different aspects of devices (e.g. some only have Telnet rather than SSH) or if I make a mistake (e.g. copying something that isn't an IP)
Below is the script...

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

crt.Screen.Synchronous = True

crt.Screen.Synchronous = True
crt.Screen.IgnoreEscape = True

Sub Main()
    ' If there isn't anything in the Windows Clipboard, it doesn't make any
    ' sense to continue with the script.
    If Trim(crt.Clipboard.Text) = "" Then
        crt.Dialog.MessageBox "No text found in the Windows Clipboard."
        Exit Sub
    End If
    
                'Send the SSH command to USERNAME
                crt.Screen.Send "ssh USERNAME@"
                
    ' Multiple lines in the Windows Clipboard are typically stored with a CRLF
    ' separator, but this script example tries to accommodate other line endings
    ' that might be supported by some editors. Break up lines into an array
    ' (each line as an element within the array).
    If Instr(crt.Clipboard.Text, vbcrlf) > 0 Then
        vLines = Split(crt.Clipboard.Text, vbcrlf)
    ElseIf Instr(crt.Clipboard.Text, vblf) > 0 Then
        vLines = Split(crt.Clipboard.Text, vblf)
    Else
        vLines = Split(crt.Clipboard.Text, vbcr)
    End If
    
    nLineNumber = 0
    For Each strLine In vLines
        ' Send the next line to the remote
        crt.Screen.Send strLine & vbcr
        
        ' Wait for the remote to echo the line back to SecureCRT; bail if the
        ' remote fails to echo the line back to us within 3 seconds.
        If Not crt.Screen.WaitForString(strLine, 3) Then
            crt.Dialog.MessageBox _
                "Sent " & nLineNumber + 1 & " lines, but the last one was " & _
                "not echoed back to SecureCRT within 3 seconds." & vbcrlf & _
                vbcrlf & _
                "Abandoning paste operation."
            Exit Sub
        End If
        nLineNumber = nLineNumber + 1
    Next
    
                'Send the remaining text to log into the CPE
                crt.Screen.Send chr(13)
		Dim nIndex
		nIndex = crt.screen.WaitForStrings( _
		"assword: ", _
		"Are you sure you want to continue connecting (yes/no)?", _
		"onnection refused", _
		"no address associated with name", _
		"syntax error", _
		"^C", _
		5 )
		
		Select Case nIndex
		
			Case 1 'Password
                crt.Screen.Send "PASSWORD1" & chr(13)
                nResult = crt.Screen.WaitForString (">", 7)
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "enable" & chr(13)
                crt.Screen.WaitForString "Password: "
                crt.Screen.Send "PASSWORD2" & chr(13)
				End If
                nResult = crt.Screen.WaitForString ("#", 2)
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "sh ip int brief" & chr(13)
				End If
				
			Case 2 'SSH First Connect Prompt
				crt.Screen.Send "yes" & chr(13)
				crt.Screen.WaitForString "Password: "
                crt.Screen.Send "PASSWORD1" & chr(13)
                nResult = crt.Screen.WaitForString (">", 7)
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "enable" & chr(13)
                crt.Screen.WaitForString "Password: "
                crt.Screen.Send "PASSWORD2" & chr(13)
                nResult = crt.Screen.WaitForString ("#", 2)
				End If
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "sh ip int brief" & chr(13)
				End If
				
			Case 3 'Equipment needs Telnet not SSH
					crt.Screen.Send "telnet "
					crt.Screen.WaitForString "$"
					If Instr(crt.Clipboard.Text, vbcrlf) > 0 Then
						vLines = Split(crt.Clipboard.Text, vbcrlf)
					ElseIf Instr(crt.Clipboard.Text, vblf) > 0 Then
						vLines = Split(crt.Clipboard.Text, vblf)
					Else
						vLines = Split(crt.Clipboard.Text, vbcr)
					End If
    
					nLineNumber = 0
					For Each strLine In vLines
						' Send the next line to the remote
						crt.Screen.Send strLine & vbcr
        
						' Wait for the remote to echo the line back to SecureCRT; bail if the
						' remote fails to echo the line back to us within 3 seconds.
					If Not crt.Screen.WaitForString(strLine, 3) Then
						crt.Dialog.MessageBox _
						"Sent " & nLineNumber + 1 & " lines, but the last one was " & _
						"not echoed back to SecureCRT within 3 seconds." & vbcrlf & _
						vbcrlf & _
						"Abandoning paste operation."
					Exit Sub
				End If
					nLineNumber = nLineNumber + 1
				Next
				crt.Screen.WaitForString "Password: "
				crt.Screen.Send "PASSWORD1" & chr(13)
                nResult = crt.Screen.WaitForString (">", 7)
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "enable" & chr(13)
                crt.Screen.WaitForString "Password: "
                crt.Screen.Send "PASSWORD2" & chr(13)
                nResult = crt.Screen.WaitForString ("#", 2)
				End If
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "sh ip int brief" & chr(13)
				End If
			
			Case 4 'No SSH address associated with name
				crt.Screen.Send Chr(3) & chr(13)
				MsgBox "Incorrect IP address entered"
				
			Case 5 'Sytax Error
				crt.Screen.Send Chr(3) & chr(13)
				MsgBox "Syntax Error"
			
			Case 6 ' Manually Cancelled
				crt.Screen.Send Chr(3) & chr(13)
		
			Case Else 'Timeout
				crt.Screen.Send Chr(3) & chr(13)
				crt.Screen.WaitForString "$"
				crt.Screen.Send "telnet "
					If Instr(crt.Clipboard.Text, vbcrlf) > 0 Then
						vLines = Split(crt.Clipboard.Text, vbcrlf)
					ElseIf Instr(crt.Clipboard.Text, vblf) > 0 Then
						vLines = Split(crt.Clipboard.Text, vblf)
					Else
						vLines = Split(crt.Clipboard.Text, vbcr)
					End If
    
					nLineNumber = 0
					For Each strLine In vLines
						' Send the next line to the remote
						crt.Screen.Send strLine & vbcr
        
						' Wait for the remote to echo the line back to SecureCRT; bail if the
						' remote fails to echo the line back to us within 3 seconds.
					If Not crt.Screen.WaitForString(strLine, 3) Then
						crt.Dialog.MessageBox _
						"Sent " & nLineNumber + 1 & " lines, but the last one was " & _
						"not echoed back to SecureCRT within 3 seconds." & vbcrlf & _
						vbcrlf & _
						"Abandoning paste operation."
					Exit Sub
				End If
					nLineNumber = nLineNumber + 1
				Next
		
				nResult = crt.Screen.WaitForString ("assword: ", 4)
				If nResult = 0 Then
				MsgBox "Timeout reached, equipment unreachable or an error has occured"
				crt.Screen.Send Chr(3) & chr(13)
				Else
				crt.Screen.WaitForString "Password: "
				crt.Screen.Send "PASSWORD1" & chr(13)
				End If
                nResult = crt.Screen.WaitForString (">", 7)
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "enable" & chr(13)
                crt.Screen.WaitForString "Password: "
                crt.Screen.Send "PASSWORD2" & chr(13)
                nResult = crt.Screen.WaitForString ("#", 2)
				End If
				If nResult = 0 Then
				MsgBox "Password Incorrect"				
				Else
                crt.Screen.Send "sh ip int brief" & chr(13)
				End If

	End Select
End Sub
As mentioned above it mostly works, the main issue is my 'Case Else' statement. I'd like the 'Case Else' to end if line 188
Code:
MsgBox "Timeout reached, equipment unreachable or an error has occured"
is used as I do not need the rest of the script after this but I cannot find anything online that says how to make this happen

Thank you in advance for any help, it's very much appreciated!

Cheers,

Zander
Reply With Quote
  #2  
Old 10-11-2016, 10:07 AM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 1,099
If you're trying to simply exit the script when you reach that part of your code, you're inside of a Sub Main(), so just use the Exit Sub statement all on its own. For example:
Code:
                If nResult = 0 Then
                    MsgBox "Timeout reached, equipment unreachable or an error has occured"
                    crt.Screen.Send Chr(3) & chr(13)
                    Exit Sub
                Else
                    crt.Screen.WaitForString "Password: "
                    ' ...
For making your script-authoring life easier in the long run, consider that currently you're using a Select Case that is triggering on the result of WaitForStrings, which is a number representing the index of the string that it found.

Rather than triggering on this index, you can trigger on the string itself (so that if you have to change/rearrange any of the strings in the call, you won't have to edit more than just that one).

Also, if you make use of appropriately-named variables, you can have an easier-to-read-and-maintain script, since magic numbers like "1", "2", "3", etc. won't leave you wondering, "Now, what does '5' mean again?..." Here's an example:
Code:
Sub Main()
    ' ...
    ' ... read in your value from the clipboard *before* you
    ' Send() the ssh command. That way you can simplify the
    ' remainder of the cleanup in your script, and you won't
    ' have to do this again when you try telnet later on.
    '   Hint: Check the Scripting Guide for a tip on how to
    '   validate what's in the clipbard as being an IP address,
    '   specifically, the diatribe dealing with 'Regular Expressions'
    '   beginning on page 73 and extending through page 76...
    '   Scripting guide is here:
    '      https://www.vandyke.com/support/tips/scripting/index.html
    ' ...
    
    ' Define variables for strings we'll be waiting for, then put
    ' them into an array. This way, we'll only have to define/declare
    ' them once and if we ever have to edit them later on, we'll only
    ' need to edit the string in one place instead of two (or more).
    strPasswordPrompt = "assword: "
    strNewHostKeyPrompt = "Are you sure you want to continue connecting (yes/no)?"
    strConnectionRefused = "onnection refused"
    strUnknownAddress = "no address associated with name"
    strSyntaxError = "syntax error"
    strControlC = "^C"
    
    ' Now, let's put all these strings into an array that we'll use
    ' when calling crt.Screen.WaitForStrings()...
    vWaitFors = Array(_
        strPasswordPrompt, _
        strNewHostKeyPrompt, _
        strConnectionRefused, _
        strUnknownAddress, _
        strSyntaxError, _
        strControlC)

    ' Wait for any of the above to be found. Note that we're wrapping
    ' the "crt.Screen.WaitForStrings() call in an __If__ statement -- this
    ' can be done if you're using a timeout because Screen.WaitForStrings()
    ' will always return 0/False if it times out before finding any of the
    ' elements of the array you pass in.
    If crt.screen.WaitForStrings(vWaitFors, 5) Then
        strWhatWasFound = vWaitFors(crt.Screen.MatchIndex - 1)
        ' Let's determine what we found, and do stuff about it...
        Select Case strWhatWasFound
            Case strPasswordPrompt
                ' Handle the [pP]assword: prompt
                ' ...
            
            Case strNewHostKeyPrompt
                ' Handle the new host key ssh prompt
                ' ...
                
            Case strConnectionRefused
                ' Handle the case where the connection is refused.
                ' ...
                
            Case strUnknownAddress
                ' Handle this case.
                ' ...
                
            Case strSyntaxError
                ' Handle this case.
                ' ...
                
            Case strControlC
                ' Handle this case.
                ' ...
            
            Case Else
                crt.Dialog.MessageBox(_
                    "Whoa!" & vbcrlf & vbcrlf & _
                    "You've something in your WaitFors array doesn't have " & _
                    "'Case handler' code to deal with: " & vbcrlf & vbcrlf & _
                    vbtab & strWhatWasFound & vbcrlf & vbcrlf & _
                    "Time to work on your script code some more and handle " & _
                    "this new thing you added to your vWaitFors array...")
        End Select
    Else
        ' This is where you handle your timeout case, because
        ' WaitForStrings returns False (zero) if it times out.
        crt.Screen.Send Chr(3) & chr(13)
        crt.Screen.WaitForString "$"
        crt.Screen.Send "telnet "
        ' ...
    End If

    ' ...
End Sub
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
  #3  
Old 10-12-2016, 03:50 AM
Zander Zander is offline
Registered User
 
Join Date: Oct 2016
Posts: 11
Hi Jake,

Thank you so much for your response, it's really helped me! I wasn't aware of regular expressions so I've added that in now which has also allowed me to get rid of the 'Syntax Error' and 'Unknown Address' variables

I've tried to tidy it up now but there are still a few bits that I'm a bit stuck on...

Code:
Sub Main()
	'Defining variables
	strPasswordPrompt = "assword: "
    strNewHostKeyPrompt = "Are you sure you want to continue connecting (yes/no)?"
    strConnectionRefused = "onnection refused"
    strControlC = "^C"
	
	vWaitFors = Array(_
        strPasswordPrompt, _
        strNewHostKeyPrompt, _
        strConnectionRefused, _
        strControlC)
		
	Set re = New RegExp
	' Set up a pattern that starts at the beginning ("^"), and looks for a
	' digit that's between 1 and 3 characters long ("\d{1,3}"), followed by
	' a dot character ("\.") (repeated again 3 times, but the last one
	' doesn't have a trailing dot character), followed immediately by the
	' end of the input ("$"):
	re.Pattern = "^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$"
	' This loop allows us to continue prompting for valid input until either
	' the user cancels, or provides a valid IP address.
	
    ' If there isn't anything in the Windows Clipboard, it doesn't make any
    ' sense to continue with the script.
	
    If Trim(crt.Clipboard.Text) = "" Then
        crt.Dialog.MessageBox "No text found in the Windows Clipboard"
        Exit Sub
	Else
		If Trim(crt.Clipboard.Text) = re.Pattern Then
    End If
	
	Set matches = re.Execute(crt.Clipboard.Text)

	If matches.Count < 1 Then
	MsgBox "Invalid IPv4 address entered!"
	Exit Sub
	Else
	' Now check to see if each octet is within a valid range
	bValid = True
	For Each nOctet In matches(0).Submatches
	If nOctet < 0 Or nOctet > 255 Then
	crt.Dialog.MessageBox _
	"Clipboard Contains an Invalid IPv4 address"
	Exit Sub
	bValid = False
	End If
	Next
    
    'Send the SSH command to USERNAME
		crt.Screen.Send "ssh USERNAME@"
		
	' Multiple lines in the Windows Clipboard are typically stored with a CRLF
    ' separator, but this script example tries to accommodate other line endings
    ' that might be supported by some editors. Break up lines into an array
    ' (each line as an element within the array)
    If Instr(crt.Clipboard.Text, vbcrlf) > 0 Then
        vLines = Split(crt.Clipboard.Text, vbcrlf)
    ElseIf Instr(crt.Clipboard.Text, vblf) > 0 Then
        vLines = Split(crt.Clipboard.Text, vblf)
    Else
        vLines = Split(crt.Clipboard.Text, vbcr)
    End If
    
    nLineNumber = 0
    For Each strLine In vLines
        ' Send the next line to the remote
        crt.Screen.Send strLine & vbcr
        
        ' Wait for the remote to echo the line back to SecureCRT; bail if the
        ' remote fails to echo the line back to us within 3 seconds.
        If Not crt.Screen.WaitForString(strLine, 3) Then
            crt.Dialog.MessageBox _
                "Sent " & nLineNumber + 1 & " lines, but the last one was " & _
                "not echoed back to SecureCRT within 3 seconds." & vbcrlf & _
                vbcrlf & _
                "Abandoning paste operation."
            Exit Sub
        End If
        nLineNumber = nLineNumber + 1
    Next
    
		'Send the remaining text to log into the CPE (Return Key)
		crt.Screen.Send chr(13)
		
	Dim nIndex
		If crt.screen.WaitForStrings(vWaitFors, 5) Then
		strWhatWasFound = vWaitFors(crt.Screen.MatchIndex - 1)
		
		Select Case strWhatWasFound
		
			Case strPasswordPrompt 'Password prompt is seen
				'Nothing needs to happen so continue script
				
			Case strNewHostKeyPrompt 'SSH First Connection Prompt
				crt.Screen.Send "yes" & chr(13)
				crt.Screen.WaitForString "Password: "
				
			Case strConnectionRefused 'Equipment needs Telnet not SSH
					crt.Screen.WaitForString "$"
					crt.Screen.Send "telnet "
					crt.Screen.WaitForString "$"
					nLineNumber = 0
					For Each strLine In vLines
						' Send the next line to the remote
						crt.Screen.Send strLine & vbcr
						' Wait for the remote to echo the line back to SecureCRT; bail if the
						' remote fails to echo the line back to us within 3 seconds.
					If Not crt.Screen.WaitForString(strLine, 3) Then
						crt.Dialog.MessageBox _
						"Sent " & nLineNumber + 1 & " lines, but the last one was " & _
						"not echoed back to SecureCRT within 3 seconds." & vbcrlf & _
						vbcrlf & _
						"Abandoning paste operation."
					Exit Sub
				End If
					nLineNumber = nLineNumber + 1
				Next
				crt.Screen.WaitForString "Password: "
			
			Case strControlC 'User cancelled the script
				crt.Screen.Send Chr(3) & chr(13)
				Exit Sub
		
			Case Else 'Connection attempt has timed out with SSH - Attempt Telnet, if this times out then exit script
				
				crt.Screen.Send Chr(3) & chr(13)
				crt.Screen.WaitForString "$"
				crt.Screen.Send "telnet "
					nLineNumber = 0
					For Each strLine In vLines
						' Send the next line to the remote
						crt.Screen.Send strLine & vbcr
						' Wait for the remote to echo the line back to SecureCRT; bail if the
						' remote fails to echo the line back to us within 3 seconds.
					If Not crt.Screen.WaitForString(strLine, 3) Then
						crt.Dialog.MessageBox _
						"Sent " & nLineNumber + 1 & " lines, but the last one was " & _
						"not echoed back to SecureCRT within 3 seconds." & vbcrlf & _
						vbcrlf & _
						"Abandoning paste operation."
					Exit Sub
				End If
					nLineNumber = nLineNumber + 1
				Next
			
				Dim nResult
				nResult = crt.Screen.WaitForString ("assword: ", 4)
				If nResult = 0 Then
					MsgBox "Timeout reached, equipment unreachable or an error has occured"
				crt.Screen.Send Chr(3) & chr(13)
				Exit Sub
				Else
				crt.Screen.WaitForString "Password: "
				End If
		End Select

	'Send rest of login information to device	
	crt.Screen.Send "PASSWORD1" & chr(13)
	nResult = crt.Screen.WaitForString (">", 7)
	If nResult = 0 Then
			MsgBox "Password Incorrect"
			Exit Sub
		Else
			crt.Screen.Send "enable" & chr(13)
            crt.Screen.WaitForString "Password: "
            crt.Screen.Send "PASSWORD2" & chr(13)
            nResult = crt.Screen.WaitForString ("#", 2)
	End If
		If nResult = 0 Then
			MsgBox "Password Incorrect"
			Exit Sub
		Else
            crt.Screen.Send "sh ip int brief" & chr(13)
	End If
	End If
	End If
	End If
End Sub
I've had to throw in a lot of 'End If' statements at the end to stop to script erroring but I can't understand why as everywhere I have an 'If' statement there is a corresponding 'End If' - Unless of course I'm missing something?

I've tried to tidy up the telnet attempts later on but they're still quite long, I've tried taking bits out/ changing bits to shorten in but I'm having no luck - Is there perhaps a way of making the first 'paste clipboard contents bit so that I can reuse it later to cut down on the length? (this bit...)
Code:
	' Multiple lines in the Windows Clipboard are typically stored with a CRLF
    ' separator, but this script example tries to accommodate other line endings
    ' that might be supported by some editors. Break up lines into an array
    ' (each line as an element within the array)
    If Instr(crt.Clipboard.Text, vbcrlf) > 0 Then
        vLines = Split(crt.Clipboard.Text, vbcrlf)
    ElseIf Instr(crt.Clipboard.Text, vblf) > 0 Then
        vLines = Split(crt.Clipboard.Text, vblf)
    Else
        vLines = Split(crt.Clipboard.Text, vbcr)
    End If
    
    nLineNumber = 0
    For Each strLine In vLines
        ' Send the next line to the remote
        crt.Screen.Send strLine & vbcr
        
        ' Wait for the remote to echo the line back to SecureCRT; bail if the
        ' remote fails to echo the line back to us within 3 seconds.
        If Not crt.Screen.WaitForString(strLine, 3) Then
            crt.Dialog.MessageBox _
                "Sent " & nLineNumber + 1 & " lines, but the last one was " & _
                "not echoed back to SecureCRT within 3 seconds." & vbcrlf & _
                vbcrlf & _
                "Abandoning paste operation."
            Exit Sub
        End If
        nLineNumber = nLineNumber + 1
    Next
    
		'Send the remaining text to log into the CPE (Return Key)
		crt.Screen.Send chr(13)
Thank you again for your help, it's very very much appreciated

Last edited by Zander; 10-12-2016 at 08:19 AM. Reason: Trying to get code to display colourfully!
Reply With Quote
  #4  
Old 10-12-2016, 09:36 AM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 1,099
Post

Quote:
I've had to throw in a lot of 'End If' statements at the end to stop to script erroring but I can't understand why as everywhere I have an 'If' statement there is a corresponding 'End If' - Unless of course I'm missing something?
I won't be able to allocate resources to analyze and fix all the places in your code where you're making VBScript syntax mistakes. However, I'll provide you with a few tips that you can use to learn and move forward with your project.

Part of the problem is that you're using an editor that is combining tabs with spaces for indentation. It's easier to read if you stick with either one or the other. Some editors can be configured to always use 4 spaces instead of inserting a tab character when performing indentation.

Proper indentation will help you see where you've missed End If statements.

Here's just one example:

Quote:
I've tried to tidy up the telnet attempts later on but they're still quite long, I've tried taking bits out/ changing bits to shorten in but I'm having no luck - Is there perhaps a way of making the first 'paste clipboard contents bit so that I can reuse it later to cut down on the length?
Not clear what you're trying to accomplish with all that code. If you want access to what's in the clipboard, and you simply want to parse out the IP that's there and check it to see if it's valid, you'd do something like this:

Code:
strAddress = crt.Clipboard.Text
' Remove all spaces, CRs, LFs, and TAB characters that might be in the clipboard
strAddress = Replace(strAddress, " ", "")
strAddress = Replace(strAddress, vbcr, "")
strAddress = Replace(strAddress, vblf, "")
strAddress = Replace(strAddress, vbtab, "")

' Now check it against our regexp pattern.
Set re = New RegExp
' Set the pattern to match only an IPv4 address
re.Pattern = _
     "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}" & _
     "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$"

' This loop allows us to continue prompting for valid
' input until either the user cancels, or provides a
' valid IP address.
Do
    If re.Test(strAddress) Then
        Exit Do
    Else
        strAddress = crt.Dialog.Prompt(_
            "Please specify a valid IPv4 address", _
            "Enter IP Address", _
            strAddress)
        If strAddress = "" Then
            Exit Sub
        End If
    End If
Loop
Put that block first thing inside of your Sub Main. Then you'll always have the strAddress variable to use when referencing what was originally in the clipboard.

Additionally, you're sending 'ssh user@' before you even test the input... you should consider instead building up your entire command *before* sending anything to the remote. For example.
Code:
strCmd = "ssh user@" & strAddress
crt.Screen.Send strCmd & vbcr
This should help simplify things as you won't have to Ctrl+C to clear your command line... perhaps.

--Jake
Attached Images
File Type: png If..Then_missingEndIf_t=12505.r4.png (32.1 KB, 4993 views)
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
  #5  
Old 10-13-2016, 05:04 AM
Zander Zander is offline
Registered User
 
Join Date: Oct 2016
Posts: 11
Hi Jake,

Again, thank you so much for your help - As I said at the start I'm a complete novice so thank you for bearing with me

I followed your advice about the indentation and have found the issues with my 'End If' statements I didn't realise something so simple would help so much!
Thank you also for the help in defining strings for the username & password aspects! I've now got the script to a place I'd like it to be So thank you so much for that!

I do have one last question - With the IP address validation that's now in place I'm encountering an issue where if I copy a cell from Excel with an IP address inside and then run this script in SecureCRT it doesn't recognise it as an IP address whereas if I copy the IP address from within the cell the validation is happy with this - Do you have any ideas as to why this is? It's not a huge issue, just a bugbear This used to work fine before the validation was in place so it seems that when the Excel cell itself is copied something else is in the clipboard along with the IP address to cause the validation to believe it's not following the IP address conventions

Cheers,

Zander

Code:
Sub Main()
	'Defining IP address as string and removing all spaces, CRs, LFs, and TAB characters
		strAddress = crt.Clipboard.Text
		strAddress = Replace(strAddress, " ", "")
		strAddress = Replace(strAddress, vbcr, "")
		strAddress = Replace(strAddress, vblf, "")
		strAddress = Replace(strAddress, vbtab, "")

	'Defining SSH & Telent commands
		strSSHCmd = "ssh USERNAME@" & strAddress
		strTelCmd = "telnet " & strAddress
	
	'Defining variables
		strPasswordPrompt = "assword: "
		strNewHostKeyPrompt = "Are you sure you want to continue connecting (yes/no)?"
		strConnectionRefused = "onnection refused"
		strControlC = "^C"
	
	'Defining strings for cases
	vWaitFors = Array(_
        strPasswordPrompt, _
        strNewHostKeyPrompt, _
        strConnectionRefused, _
        strControlC)
		
	Set re = New RegExp
		' Set up a pattern that starts at the beginning ("^"), and looks for a
		' digit that's between 1 and 3 characters long ("\d{1,3}"), followed by
		' a dot character ("\.") (repeated again 3 times, but the last one
		' doesn't have a trailing dot character), followed immediately by the
		' end of the input ("$"):
		re.Pattern = "^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$"

    If Trim(crt.Clipboard.Text) = "" Then
		' If there isn't anything in the Windows Clipboard, it doesn't make any
		' sense to continue with the script
        crt.Dialog.MessageBox "No text found in the Windows Clipboard"
        Exit Sub
	End If
	
	Set matches = re.Execute(crt.Clipboard.Text)

	If matches.Count < 1 Then
		MsgBox "Invalid IPv4 address copied!"
		Exit Sub
	Else
		'Now check to see if each octet is within a valid range
		bValid = True
		For Each nOctet In matches(0).Submatches
		If nOctet < 0 Or nOctet > 255 Then
			crt.Dialog.MessageBox _
			"Clipboard Contains an Invalid IPv4 address"
			Exit Sub
		Else
			bValid = False
		End If
		Next
	End If
	
	'Send the SSH command to USERNAME
	crt.Screen.Send strSSHCmd & vbcr
	nResult = crt.Screen.WaitForString (strSSHCmd, 3)
	If nResult = 0 Then
		MsgBox "Error Occurred"
		Exit Sub
	Else
		'Send the remaining text to log into the CPE (Return Key)
		crt.Screen.Send chr(13)
	End If
	
	If crt.screen.WaitForStrings(vWaitFors, 5) Then
		strWhatWasFound = vWaitFors(crt.Screen.MatchIndex - 1)
		
		Select Case strWhatWasFound
		
			Case strPasswordPrompt 'Password prompt is seen
				'Nothing needs to happen so continue script
				
			Case strNewHostKeyPrompt 'SSH First Connection Prompt
				crt.Screen.Send "yes" & chr(13)
				crt.Screen.WaitForString "Password: "
				
			Case strConnectionRefused 'Equipment needs Telnet not SSH
				crt.Screen.WaitForString "$"
				crt.Screen.Send strTelCmd & vbcr
				Dim nResult
					nResult = crt.Screen.WaitForString (strTelCmd, 3)
				If nResult = 0 Then
					crt.Dialog.MessageBox("Error Occurred")
					crt.Screen.Send Chr(3) & chr(13)
					Exit Sub
				End If
				crt.Screen.WaitForString "Password: "
					
			
			Case strControlC 'User cancelled the script
				crt.Screen.Send Chr(3) & chr(13)
				Exit Sub
		
			Case Else 'Need to add another variable!
				crt.Dialog.MessageBox(_
                    "Whoa!" & vbcrlf & vbcrlf & _
                    "You've something in your WaitFors array doesn't have " & _
                    "'Case handler' code to deal with: " & vbcrlf & vbcrlf & _
                    vbtab & strWhatWasFound & vbcrlf & vbcrlf & _
                    "Time to work on your script code some more and handle " & _
                    "this new thing you added to your vWaitFors array...")
		End Select
		
	Else 'Connection attempt has timed out with SSH - Attempt Telnet, if this times out then exit script
		crt.Screen.Send Chr(3) & chr(13)
		crt.Screen.WaitForString "$"
		crt.Screen.Send strTelCmd & vbcr
		nResult = crt.Screen.WaitForString ("$", 4)
		If nResult = 0 Then
			MsgBox "Timeout reached, equipment unreachable or an error has occured"
			crt.Screen.Send Chr(3) & chr(13)
			Exit Sub
		End If
		nResult = crt.Screen.WaitForString (strTelCmd, 3)
		If nResult = 0 Then
			MsgBox "Error Occurred"
			Exit Sub
		Else
			nResult = crt.Screen.WaitForString ("assword: ", 4)
			If nResult = 0 Then
				MsgBox "Timeout reached, equipment unreachable or an error has occured"
				crt.Screen.Send Chr(3) & chr(13)
				Exit Sub
			End If
		End If
	End If
				
	'Send rest of login information to device	
	crt.Screen.Send "PASSWORD1" & chr(13)
	nResult = crt.Screen.WaitForString (">", 7)
	If nResult = 0 Then
		MsgBox "Password Incorrect"
		Exit Sub
	Else
		crt.Screen.Send "enable" & chr(13)
        crt.Screen.WaitForString "Password: "
        crt.Screen.Send "PASSWORD2" & chr(13)
        nResult = crt.Screen.WaitForString ("#", 2)
	End If
	If nResult = 0 Then
		MsgBox "Password Incorrect"
		Exit Sub
	Else
		crt.Screen.Send "sh ip int brief" & chr(13)
	End If
End Sub

Last edited by Zander; 10-13-2016 at 05:06 AM. Reason: Added clarification on the Excel question
Reply With Quote
  #6  
Old 10-13-2016, 09:47 AM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 1,099
Quote:
Originally Posted by Zander View Post
...if I copy a cell from Excel with an IP address inside and then run this script in SecureCRT it doesn't recognise it as an IP address whereas if I copy the IP address from within the cell the validation is happy with this - ...when the Excel cell itself is copied something else is in the clipboard along with the IP address to cause the validation to believe it's not following the IP address conventions
There could be something wrong with the regular expression -- I'm not perfect at that (yet )... but I'm betting that there is something being copied by Excel into the clipboard when what's copied is the the cell rather than the text within it.

One way to "see" what's in would be to convert all non-printing characters in the clipboard to something that is visible (like [CR] for a carriage return, for example) and then throw that into a messagebox so you can see what special characters there are.

See the Reveal Non-Printing Characters example script found on our Script Examples "sticky" for specifics on how you can troubleshoot further.

Once you "see" the extra stuff that's being put into the clipboard by Excel when you copy a cell, you can add more Replace() calls to remove those special characters from the string the pattern will operate over.

--Jake
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
Reply

Tags
script , secure crt , vbs

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:41 PM.