Welcome to the VanDyke Software Forums

Join the discussion today!


Go Back   VanDyke Software Forums > Scripting

Reply
 
Thread Tools Rate Thread Display Modes
  #16  
Old 06-19-2012, 12:47 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi All,

After some additional investigation, it turns out that SecureCRT 6.7.5 and older uses Python 2.5.6 rather than the newest version (2.7.x) installed on Mac OS X Lion. This is why the older syntax is required for the error handling code.
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #17  
Old 08-28-2012, 11:07 AM
Levittown Levittown is offline
Registered User
 
Join Date: Aug 2012
Posts: 7
Help!

Todd:

I used the attached script (ReadDataFromHostFile-SendCommandsFromCommandsFile-LogResultsToIndividualFiles)
However, I'm getting the following:

Error: Path not found
File:
C:\Users\rgonza11\Documents\ReadDataFromHostfile-SendCommandsFromCommandsFile-LogResultsToIndividualFiles.txt
Line: 144

Line 144 correspond to the following line of code:
Set objFile = g_fso.OpenTextFile(strLogFile, ForAppending, True)

The only changes I made to your code is adding the two lines below:
# $language = "VBScript"
# $interface = "1.0"

Thank you
Reply With Quote
  #18  
Old 08-28-2012, 12:48 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi Levittown,

To troubleshoot this issue, I would suggest using a message box. You could place the message box prior to line 144. For example:
Code:
                MsgBox strLogFile
                Set objFile = g_fso.OpenTextFile(strLogFile, ForAppending, True)
Does a file with the name in the message box exist on your computer?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #19  
Old 08-28-2012, 01:56 PM
Levittown Levittown is offline
Registered User
 
Join Date: Aug 2012
Posts: 7
Quote:
Originally Posted by rtb View Post
Hi Levittown,

To troubleshoot this issue, I would suggest using a message box. You could place the message box prior to line 144. For example:
Code:
                MsgBox strLogFile
                Set objFile = g_fso.OpenTextFile(strLogFile, ForAppending, True)
Does a file with the name in the message box exist on your computer?
Todd:

When I place the MsgBox I get the following:

C:\Users\rgonzalez11\Documents\##10.10.10.10--show run interface fa1/0/1--2012-08-28--14'46'57.txt


Without the MsgBox I was getting the following error massage:

Error: Path not found
File:
C:\Users\rgonza11\Documents\ReadDataFromHostfile-SendCommandsFromCommandsFile-LogResultsToIndividualFiles.txt
Line: 144

The directory where the script is located also contains the following files:

##commands
##hosts

Thank you for all your help
Reply With Quote
  #20  
Old 08-28-2012, 02:09 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi Levittown,

Thanks for the update. Does the following path exist on your computer?
C:\Users\rgonzalez11\Documents\##10.10.10.10--show run interface fa1/0/
Based on the error message, I suspect that it does not.

To fix this issue, you are going to have to use a filename for the log file that uses valid Windows filename characters. Since you have commands that contain invalid Windows filename characters, you are going to have to either modify the command before adding it to the filename, or you are going to have to not use the command in the filename.

Does this information help you fix your script?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #21  
Old 08-28-2012, 05:54 PM
Levittown Levittown is offline
Registered User
 
Join Date: Aug 2012
Posts: 7
Todd:

That fixed the "path" problem; thank you!!!

I did noticed that when I launch the script I need to enter my username and password to authenticate. I would like to make the username and password part of the script so I don't have to enter them. What changes I need to make to make this work?

Thank you so much!

Quote:
Originally Posted by rtb View Post
Hi Levittown,

Thanks for the update. Does the following path exist on your computer?
C:\Users\rgonzalez11\Documents\##10.10.10.10--show run interface fa1/0/
Based on the error message, I suspect that it does not.

To fix this issue, you are going to have to use a filename for the log file that uses valid Windows filename characters. Since you have commands that contain invalid Windows filename characters, you are going to have to either modify the command before adding it to the filename, or you are going to have to not use the command in the filename.

Does this information help you fix your script?
Reply With Quote
  #22  
Old 08-29-2012, 12:20 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi Levittown,

I am glad to hear that this issue is resolved.

We have an updated example that illustrates how to accomplish your goal, but it will only work in 7.0.1. After I have had some time to test it, I will post it.

If you can't use SecureCRT 7.0.1, then you should be able to get the code necessary to modify the old script to have a hard coded username and password.
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #23  
Old 08-30-2012, 05:14 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi Levittown,

I have posted the new example to the following location:
http://forums.vandyke.com/showthread.php?t=10365
The name of the example is:
Example: Read Data From Separate Hosts/Commands File And Log To Individual Files
This example should handle the user credentials and invalid characters in the command when building the log file name.
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #24  
Old 09-06-2012, 02:44 PM
Levittown Levittown is offline
Registered User
 
Join Date: Aug 2012
Posts: 7
help!

Todd:

Thank you; I will give it a try. Ultimately, I would like to capture the entire output in a single text file as oppose to multiple output documents. Is this possible?

Again, thank you for your support.
Reply With Quote
  #25  
Old 09-07-2012, 11:04 AM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,494
Hi Levittown,

Todd is not currently available.

It is possible to log to a single file. We don't currently have an example to post, but I have noted the changes to the prior example that would be needed:
  • Remove lines 247 to 282 (retain the "cut data", some lines will be edited/reused)

  • Replace lines 34-35:
    g_strLogFileTemplate = g_strMyDocs & "\##IPADDRESS--COMMAND--YYYY-MM-DD--hh'mm'ss.txt"

    with:

    g_strOutputFile = g_strMyDocs & "\##Output_Results--YYYY-MM-DD--hh'mm'ss.txt"
  • Lines 275-280 of previously "cut" data added after above line replacement

    - Change all references in this block from strLogFile to g_strOutputFile

  • Lines 247-246 of previously "cut" data becomes these lines below and will immediately **precede** the For loop that sends commands (around line 202 in new script)
    Code:
    ' Open output file so we can write results to it
    Dim objFile
    Set objFile = g_fso.OpenTextFile(g_strOutputFile, ForAppending, True)
  • The rest of the "cut" data can be discarded (strCleanCmd lines)

Lastly, this snippet of code shows how you can include a separator between every command and every host. I have given a few lines before the new information and a few lines after to help you locate where in the existing script to place it.

Code:
                    ' Write out the results of the command and a separator
                    objFile.WriteLine strResult
                    
                    ' Add a separator between commands 
                    objFile.WriteLine _
                        "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
		    
                Next   ' Command Loop
		
                ' Add a separator between hosts 
                objFile.WriteLine String(80, "=")
                
                ' Close the log file
                objFile.Close
                
                ' Now disconnect from the current machine before connecting to
                ' the next machine
                Do
                    crt.Session.Disconnect
                    crt.Sleep 100
                Loop While crt.Session.Connected
                
                strSuccesses = strSuccesses & vbcrlf & strHost
            End If ' WaitForScreenContentsToStopChanging()
        End If ' Connect()
        
    Next   ' Host Loop

You also might check back to the main script link page occasionally:
http://forums.vandyke.com/showthread.php?t=10365
Once we have had a chance to refine the new script a bit further, we will make it available.
__________________
Thanks,
--Brenda

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #26  
Old 05-03-2018, 03:27 PM
Brawls Brawls is offline
Registered User
 
Join Date: May 2018
Posts: 2
How would you enable this script to handle errors in command input?

For example, if you send an unsupported command to the host and it returns something like "% Invalid input detected at '^' marker."?
Reply With Quote
  #27  
Old 05-03-2018, 03:59 PM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 1,039
Quote:
Originally Posted by Brawls View Post
How would you enable this script to handle errors in command input?

For example, if you send an unsupported command to the host and it returns something like "% Invalid input detected at '^' marker."?
This thread references an example scripts thread in which there are a number of different example script files.

Can you tell me which exact script you're asking about?

Name of the script?

Where you downloaded it from?

Python/VBScript?

--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
  #28  
Old 05-09-2018, 01:24 PM
Brawls Brawls is offline
Registered User
 
Join Date: May 2018
Posts: 2
The below code won't iterate beyond the first host

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

# SimpleReadDataFromHostFile-SendCommand-LogResultsToIndividualFiles.py 
# 
# Script demonstrates how to connect to hosts and send commands, logging results 
# to a uniquely named file based on the host address and the command that is run. 

import os, datetime, SecureCRT, csv 

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
def Main(): 
    # Get home folder path 
    strFilePath = os.path.expanduser("~") + '\\My Documents\\' 
    strCommand2 = 'show run | incl ntp server 147.80.8.22'
    strPrompt = '#' 
    MsgBox = crt.Dialog.MessageBox 
    objHostsFile = strFilePath + 'ScriptData\\hosts.csv'
    
    # Open Hosts file 
    try: 
        with open(objHostsFile) as csvfile:
            reader = csv.DictReader(csvfile)
    except Exception as objInst: 
        MsgBox('Could not open hostname file with error: \n\n' + str(objInst) +  
            '\n\nExiting script.') 
        return 
         
    # We only get here if we were able to successfully open commands file. 
    # Iterate over each host in our host list... 
    with open(objHostsFile) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            Loopback = row['Loopback']
            Hostname = row['Hostname']
            # Replace newline character appended to hostname. 
            Hostname = Hostname.replace('\n', '') 
            # Get date and time for use in log file naming. 
            # strDateTime = str(datetime.datetime.today()) 
            # Replace illegal characters in date. 
            #strDateTime = strDateTime.replace(':', '_') 
            # Create log file name and path 
            strLogFile = strFilePath + 'ScriptOutput\\' + Hostname + '.txt' 
            # String to use to connect to remote host. 
            strConnectString = '/SSH2 /L brawls_insight /PASSWORD ****** /C 3DES /M SHA1 ' + Loopback 
            # Only operate on non-blank values. 
            if Hostname != "":
                objLogFile = open(strLogFile,'w')
                # Try to open log file. 
                try:
                    # Try t o connect to host and run command. 
                    crt.Session.Connect(strConnectString, False) 
                    # Enable the Synchronous property so we don't miss data. 
                    crt.Screen.Synchronous = True 
                    # If you want to suppress escape sequences from being captured, 
                    # set the Screen.IgnoreEscape property = True. 
                    # Handle authentication. 
                    #crt.Screen.WaitForString('ogin:') 
                    #crt.Screen.Send('user\r') 
                    #crt.Screen.WaitForString('word:') 
                    #crt.Screen.Send('password\r') 
                    # Wait for prompt to indicate that remote is read for cmd. 
                    crt.Screen.WaitForString(strPrompt) 
                    # Send the command to the remote. 
                    #crt.Screen.Send(strCommand + '\r') 
                    # Wait for the command to be echo'd back to us. 
                    #crt.Screen.WaitForString(strCommand + '\r\n')
                    # Send the command to the remote. 
                    crt.Screen.Send(strCommand2 + '\r') 
                    # Wait for the command to be echo'd back to us. 
                    crt.Screen.WaitForString(strCommand2 + '\r\n')
                    strResult = crt.Screen.ReadString(strPrompt)
                    if strResult != "":
                        # If you want the command logged along with the results, 
                        # uncomment the next two lines 
                        #objLogFile.write('Results of command ' + strCommand2 + 
                        #    ' sent to host ' + Hostname + ': \r\n') 
                         
                        # Write out the results of the command 
                        objLogFile.write(strResult)
                    else:
                        objLogFile.write('Timed out waiting for prompt.  ' + 
                            'There may have been a problem running:  ' + strCommand2)
                         #Close the log file 
                    objLogFile.close()
                        # Disconnect to move on to next host. 
                    crt.Session.Disconnect() 
            # Handle multiple exceptions. 
                except IOError as objInst: 
                    MsgBox('Log file open error: \n\n' + str(objInst) + 
                        '\n\nExiting script.') 
                except SecureCRT.ScriptError as objInst: 
                    objLogFile.write("Error Connecting: " + str(objInst)) 
                    objLogFile.close() 
                except Exception as objInst: 
                    objLogFile.write('Unhandled script error:  \n\n' + str(objInst)) 
                    objLogFile.close() 
    # Close hostname file. Not needed because of "with"
    #objHostsFile.close() 

Main()
So, the issue was that crt.Session.Disconnect() was hanging.

Last edited by Brawls; 05-09-2018 at 02:09 PM. Reason: Found Solution
Reply With Quote
  #29  
Old 05-09-2018, 02:34 PM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 1,039
Quote:
Originally Posted by Brawls View Post
So, the issue was that crt.Session.Disconnect() was hanging.
If Session.Disconnect is "hanging", SecureCRT is attempting to close the SSH connection cleanly, but the remote system isn't playing well (it doesn't respond to SecureCRT's request to close the connection "cleanly").

You can force SecureCRT to close the connection regardless by setting the "Force Close on Exit" session option to True within your code right before you call Session.Disconnect(). For example


Code:
...
crt.Session.Config.SetOption "Force Close on Exit", True
crt.Session.Disconnect()
...
__________________
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


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 01:51 PM.