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 04-20-2012, 08:19 AM
rainman rainman is offline
Registered User
 
Join Date: Apr 2012
Posts: 16
Connecting to multiple IP addresses sequentially

Hello,
Can you please advise how to connect to one IP address , run script commands, disconnect and then move onto the next IP address ? I have all the IP addresses in a text file. Also how do I log each output into a file ? Thanks
Reply With Quote
  #2  
Old 04-20-2012, 09:11 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi rainman,

There is an example script in another post in our script examples sticky that you are welcome to customize to meet your particular needs.

In this script you will notice that there is a For...Next loop that allows you to iterate over all of your hosts.

Does this help you accomplish your goal?
__________________
--Todd

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

Last edited by bgagnon; 04-25-2018 at 09:44 AM.
Reply With Quote
  #3  
Old 04-20-2012, 09:31 AM
rainman rainman is offline
Registered User
 
Join Date: Apr 2012
Posts: 16
Thanks Todd, the script example looks pretty awesome. As I am just learning
would there be a more simplified version of how to telnet to one IP address, login and run some commands logout and then disconnect and then pick the next IP address from the text file and repeat ? Again your help us much appreciated Todd
Reply With Quote
  #4  
Old 04-20-2012, 11:14 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi rainman,

Since you are just beginning, do you have a preferred language, or are you learning both scripting and the language?

We do have a script in Python that may be easier to follow.

With regards to the complexity, we read the hostnames into an array to reduce disk I/O. This function does make the script more complex. Python has easier ways to accomplish the same goal.

Would you like to take a look at the Python script example?

What specifically do you want to log when you are running the script?

Based on your initial requirements, it sounded like you wanted individual log files. Can you clarify this requirement?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #5  
Old 04-23-2012, 05:28 AM
rainman rainman is offline
Registered User
 
Join Date: Apr 2012
Posts: 16
Hi Todd, basically , I want to telnet into a switch run a show inventory command capture that information in a file, logout then telnet to the next switch and repeat as above. All the information can be captured in a single file or multiple files. I just need to know how to script the telnet piece for a list of given IP addresses. Thanks.
Reply With Quote
  #6  
Old 04-23-2012, 04:01 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi rainman,

Simple scripts usually don't have the ability to handle errors very well. This is why we have complicated scripts as examples. Here is a Python example that is simpler than the VBScript. The script assumes that authentication will work every time. If for some reason you find authentication failing, you will need to add more robust code to replace lines 52-55.

PHP 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 osdatetimeSecureCRT

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def Main():
    
# Get home folder path
    
strFilePath os.path.expanduser("~") + '\\My Documents\\'
    
strCommand 'pwd'
    
strPrompt '#'
    
MsgBox crt.Dialog.MessageBox
    
    
# Open Hosts file
    
try:
        
objHostsFile open(strFilePath 'ScriptData\\hosts.txt','r')
    
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...
    
for strHost in objHostsFile:
        
# Replace newline character appended to hostname.
        
strHost strHost.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\\' strHost '--'
        
strLogFile += strCommand '--' strDateTime '.txt'
        
# String to use to connect to remote host.
        
strConnectString '/telnet ' strHost
        
# Only operate on non-blank values.
        
if strHost != "":
            
# Try to open log file.
            
try:
                
objLogFile open(strLogFile,'w')
                
# Try to connect to host and run command.
                
crt.Session.Connect(strConnectStringFalse)
                
# 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')
                
# If you want to suppress escape sequences from being captured,
                # set the Screen.IgnoreEscape property = True.
                
strResult crt.Screen.ReadString(strPrompt5)
                if 
strResult != "":
                    
# If you want the command logged along with the results,
                    # uncomment the next two lines
                    #objLogFile.write('Results of command ' + strCommand +
                    #    ' sent to host ' + strHost + ': \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:  ' strCommand)
                
# 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.')
                return
            
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.
    
objHostsFile.close()

Main() 
Does this help you get started writing your own script?
__________________
--Todd

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

Last edited by rtb; 04-23-2012 at 04:05 PM.
Reply With Quote
  #7  
Old 05-24-2012, 04:21 PM
jkatchmar jkatchmar is offline
Registered User
 
Join Date: May 2012
Posts: 5
Greetings

I tried running the sample script above and it appears to be failing on line 22:

except Exception as objInst:
MsgBox('Could not open hostname file with error: \n\n' + str(objInst) +
'\n\nExiting script.')
return

I'm very much a python n00b, so any hints as to how to get this working would be greatly appreciated.

Thanks!!
Reply With Quote
  #8  
Old 05-24-2012, 05:21 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi jkatchmar,

Thanks for the question. The script is not able to open the file on line 21. Do you have a file in the correct location that contains hostnames?

To see what path the script is attempting to open you can insert a message box command just prior to opening the file. For example:
PHP Code:
    try: 
        
MsgBox(strFilePath 'ScriptData\\hosts.txt'
        
objHostsFile open(strFilePath 'ScriptData\\hosts.txt','r'
    
except Exception as objInst
        
MsgBox('Could not open hostname file with error: \n\n' str(objInst) +  
            
'\n\nExiting script.'
        return 
Does this help resolve the issue?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #9  
Old 05-24-2012, 08:34 PM
jkatchmar jkatchmar is offline
Registered User
 
Join Date: May 2012
Posts: 5
Thanks Todd

The file does exist, just need to confirm if my path statements in the script are correct. In the script I have the following:

#---------------------------------------------------
def Main():
# Get home folder path
strFilePath = os.path.expanduser("~") + '/scripts/'
strCommand = 'pwd'
strPrompt = '#'
MsgBox = crt.Dialog.MessageBox

# Open Hosts file
try:
objHostsFile = open(strFilePath + 'hosts/hosts.txt','r')
except Exception as objInst:
MsgBox('Could not open hostname file with error: \n\n' + str(objInst) +
'\n\nExiting script.')
return

#---------------------------------------------------

Here is the output of the file location on the system that is attempting to run the script:

MBP-JKATCHMAR:hosts jkatchmar$ pwd
/Users/jkatchmar/scripts/hosts
MBP-JKATCHMAR:hosts jkatchmar$ ls -al
total 16
drwxr-xr-x 4 jkatchmar staff 136 May 24 08:56 .
drwxr-xr-x 14 jkatchmar staff 476 May 24 17:18 ..
-rw-r--r-- 1 jkatchmar staff 14 May 24 08:56 hosts.txt
-rw-r--r-- 1 jkatchmar staff 41 May 23 15:44 test_hosts.txt


When the script is launched, here is the error that I am receiving:
#---------------------------------------------------
SyntaxError

Error: invalid syntax
File: /Users/jkatchmar/scripts/blahhh.py
Line: 22

except Exception as objInst:

#---------------------------------------------------

See anything that would be causing this?

Thanks for the assistance
Reply With Quote
  #10  
Old 05-25-2012, 07:13 AM
jkatchmar jkatchmar is offline
Registered User
 
Join Date: May 2012
Posts: 5
The script is currently pointing to the following location:

#--------------------------------------------------------------
def Main():
# Get home folder path
strFilePath = os.path.expanduser("~") + '/scripts/'
strCommand = 'pwd'
strPrompt = '#'
MsgBox = crt.Dialog.MessageBox

# Open Hosts file
try:
objHostsFile = open(strFilePath + 'hosts/hosts.txt','r')
except Exception as objInst:
MsgBox('Could not open hostname file with error: \n\n' + str(objInst) +
'\n\nExiting script.')
return

#---------------------------------------------------------

The file "hosts.txt" exists on the system in the following location:
MBP-JKATCHMAR:hosts jkatchmar$ pwd
/Users/jkatchmar/scripts/hosts

MBP-JKATCHMAR:hosts jkatchmar$ ls -al
total 16
drwxr-xr-x 4 jkatchmar staff 136 May 24 08:56 .
drwxr-xr-x 14 jkatchmar staff 476 May 24 17:18 ..
-rw-r--r-- 1 jkatchmar staff 14 May 24 08:56 hosts.txt
-rw-r--r-- 1 jkatchmar staff 41 May 23 15:44 test_hosts.txt


The assumption made is that the variable defined:
strFilePath = os.path.expanduser("~") + '/scripts/'

is pointing to /Users/jkatchmar/scripts/

Please let me know if that is incorrect.

The error message that I am receiving is not the error that is defined in the script, it is:

SyntaxError

Error: invalid syntax
File: /Users/jkatchmar/scripts/blahhh.py
Line: 22

except Exception as objInst:


Thanks again for the assistance
Reply With Quote
  #11  
Old 05-25-2012, 08:35 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi jkatchmar,

Thanks for the information. The error will make it easier to troubleshoot.

I am able to run the script on a Windows machine using SecureCRT 6.7.5.

What version of SecureCRT are you using?

What operating system are you using?

Do you have Python installed?

If so, what version of Python is installed?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #12  
Old 05-25-2012, 09:18 AM
jkatchmar jkatchmar is offline
Registered User
 
Join Date: May 2012
Posts: 5
Thanks, here is the information that was requested:

SecureCRT Version 6.7.4 (build 354) for OSX

Mac OSX version 10.7.4

Python version on localhost is Python 2.7.1

Regards
//jon
Reply With Quote
  #13  
Old 05-25-2012, 04:44 PM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi Jon,

Thanks for the information. It turns out that Python 2.7 or Python 2.7 on Mac doesn't honor a new feature added to 2.6 and forced in 3.0.

The problem line in the script is:
PHP Code:
    except Exception as objInst
In my testing, Python 2.7 on Mac requires the old syntax which is:
PHP Code:
    except ExceptionobjInst
Notice that the old syntax has a comma rather than the keyword as.

If you change the three Except: calls to use a comma, the script should run on Mac OS X Lion.

Does this help to resolve the issue?
__________________
--Todd

VanDyke Software
Technical Support
support@vandyke.com
505-332-5730
Reply With Quote
  #14  
Old 05-29-2012, 09:54 AM
jkatchmar jkatchmar is offline
Registered User
 
Join Date: May 2012
Posts: 5
That was it!!

Thanks for the help!!!
Reply With Quote
  #15  
Old 05-29-2012, 10:54 AM
rtb rtb is offline
VanDyke Technical Support
 
Join Date: Aug 2008
Posts: 4,306
Hi Jon,

Thanks for the update. I am glad to hear that this is working.

I was researching this issue with a colleague and he is the one that suggested that we try and revert to the old syntax. I just didn't think that the old syntax would be required by a newer version of Python.

I will pass your thanks on to him.
__________________
--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 11:59 AM.