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 09-25-2018, 02:10 PM
aitijneg aitijneg is offline
Registered User
 
Join Date: Sep 2018
Location: Toronto
Posts: 4
Python. Issue with capturing screen output to txt file

Dear colleagues. I'm totally new in scripting. I have a task to scan around 20 switches to see if certain vlans are configured or not, what interfaces are in that vlans and mac address table for every vlan. For each vlan I'd like to create txt file to save output from all switches.
At this point my script can run device session, create text file on PC, send necessary commands to device but not properly writing screen output to the file. It stores just one line from the screen and I can't figure out why. I'm using multiple script examples from VanDuke web site to compile mine.
At this point I'm stuck in getting to understand how crt.Screen.Get method is working and how system calculates crt.Screen.CurrentRow value to capture right portion of the screen. Is there any good newbies-friendly documentation for this?

Any help will be highly appreciated.

Best regards,
Dmitriy
Reply With Quote
  #2  
Old 09-25-2018, 02:29 PM
ekoranyi ekoranyi is offline
VanDyke Technical Support
 
Join Date: Jan 2017
Posts: 547
Hi aitijneg,

I'm sorry to hear you're having trouble. To get a better idea of what may be happening I will likely need to review the script you've written. Can you provide your code for review?

What version of SecureCRT are you running?

What Operating System are you running SecureCRT on?

In the meantime we do have an example script that may fit your needs. The script demonstrates how to connect to hosts read in from a "hosts" file and for each host, send a list of commands read in from a "commands" file. Results of each command run are (by default) logged to separate, uniquely-named files based on the host address and the command that is run. However, the script code is architected to allow you to change this behavior so that it's all logged to one file per host, or even just to a single file.

This would allow you to create a list of your 20 switches, a list of the commands needed to verify the information and the script would handle the rest. It would connect to each switch run the set of commands and create a log file that contained all the output of those commands.

Does this script seem like it would fit your needs?
__________________
Thanks,
--Eric

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #3  
Old 09-26-2018, 01:37 AM
aitijneg aitijneg is offline
Registered User
 
Join Date: Sep 2018
Location: Toronto
Posts: 4
Eric hello. Thanks for your reply.
The script example is not really what I want to achieve. My goal is to scan all my devices and store all outputs related to certain vlan in one file. Next vlan output to store in next file and so forth. Below is my script code.

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

# MultiSessionSend.py
#
# Description:
#	 Reads in sessions from a file (one session per line) and
#	 connects to each one (one at a time) and sends a series of
#	 commands to the remote, then disconnects from the session
#	 and moves on to the next session.
#	 
#	 By default, the file containing the sessions is expected to be named
#	 "SessionList.txt", and should be located in the current user's home
#	 directory.  Each line of the file is expected to contain the
#	 path to the session as it appears within the Connect dialog (excluding
#	 the leading "Sessions/" component.  Here is an example file contents:
#		 
#		 redhat
#		 redhat8
#		 192.168.0.123
#		 192.168.0.131
#		 Redhat Sessions\RedHat - XTerm
#
#	 For the sake of simplicity, this example assumes that all
#	 sessions we're connecting to are using the SSH1 and SSH2
#	 protocols, with usernames and passwords saved encrypted
#	 as part of the session configuration so that we don't need
#	 to worry about authentication within this script.

import os

# Check if target directory exists and create one if doesn't
directory = "c:\\VLAN_DB"
if not os.path.exists(directory):
    os.makedirs(directory)

def Main(vlan_start,vlan_end):
	errorMessages = ""
	
	sessionsFileName = os.path.expanduser("~") + "/SessionList.txt"
	if not os.path.exists(sessionsFileName):
		crt.Dialog.MessageBox(
			"Session list file not found:\n\n" +
			sessionsFileName + "\n\n" +
			"Create a session list file as described in the description of " +
			"this script code and then run the script again.")
		return

	sessionFile = open(sessionsFileName, "r")
	sessionsArray = []

	for line in sessionFile:
		session = line.strip()
		if session:	# Don't add empty lines/sessions
			sessionsArray.append(session)

	sessionFile.close()

	# Connect to each session and issue a few commands, then disconnect.
	for session in sessionsArray:
		#crt.Dialog.MessageBox("Connecting to Session: " + session)

		try:
			crt.Session.Connect("/S \"" + session + "\"")
		except ScriptError:
			error = crt.GetLastErrorMessage()

		# If we successfully connected, we'll do the work we intend to do...
		# otherwise, we'll skip the work and move on to the next session in 
		# the list.
		if crt.Session.Connected:
			crt.Screen.Synchronous = True
			for x in range (vlan_start, vlan_end):
				vl=str(x)
				# When we first connect, there will likely be data arriving from the
				# remote system.  This is one way of detecting when it's safe to
				# start sending data.
				while True:				
					if not crt.Screen.WaitForCursor(1):
						break
				# Once the cursor has stopped moving for about a second, we'll
				# assume it's safe to start interacting with the remote system.
				
				# Checking if file to store screen ontput exists
				vl_filename = "vlan " + vl + ".txt"
				vl_filepath = os.path.join(directory,vl_filename)
				if not os.path.exists(vl_filepath):
					fp = open(vl_filepath, "wb+")
				else:
					fp = open(vl_filepath, "ab+")
				# Get the shell prompt so that we can know what to look for when
				# determining if the command is completed. Won't work if the prompt
				# is dynamic (e.g. changes according to current working folder, etc)
				screenrow = crt.Screen.CurrentRow - 1
				screenrow_str = str(screenrow)
				row = crt.Screen.CurrentRow
				prompt = crt.Screen.Get(row, 0, row, crt.Screen.CurrentColumn - 1)
				prompt = prompt.strip()
				fp.write(prompt + os.linesep)
				
				crt.Screen.Send("show vlan id "+ vl +"\n")
				# Wait for the command to complete, by looking for the prompt to
				# appear once again.
				readline = crt.Screen.Get(screenrow, 1, screenrow, 127)
				fp.write(readline + os.linesep)
				crt.Screen.WaitForString(prompt)
	
				crt.Screen.Send("show mac address-table vlan " + vl +"\n")
				# Wait for the command to complete, by looking for the prompt to
				# appear once again.
				readline = crt.Screen.Get(screenrow, 1, screenrow, 127)
				fp.write(readline + os.linesep)
				crt.Screen.WaitForString(prompt)
	
				crt.Screen.Send("show spanning-tree vlan " + vl +"\n")
				# Wait for the command to complete, by looking for the prompt to
				# appear once again.
				readline = crt.Screen.Get(screenrow, 1, screenrow, 127)
				fp.write("currentrow="+ screenrow_str + os.linesep)
				fp.write(readline + os.linesep)
				crt.Screen.WaitForString(prompt)

			# Now disconnect from the remote machine...
			crt.Session.Disconnect()
			# Wait for the connection to close
			while crt.Session.Connected == True:
				crt.Sleep(100)

			crt.Sleep(1000)
		else:
			errorMessages = errorMessages + "\n" + "*** Error connecting to " + session + ": " + error

	if errorMessages == "":
		crt.Dialog.MessageBox("Tasks completed.  No Errors were detected.")
	else:
		crt.Dialog.MessageBox("Tasks completed.  The following errors occurred:\n" + errorMessages)

	#crt.Quit()

	
Main(1,20)
Reply With Quote
  #4  
Old 09-26-2018, 01:42 AM
aitijneg aitijneg is offline
Registered User
 
Join Date: Sep 2018
Location: Toronto
Posts: 4
My Secure CRT version is 8.5.0 (x64 build 1740)
OS version Windows 7 Ent, 64-bit
Reply With Quote
  #5  
Old 09-26-2018, 04:52 PM
ekoranyi ekoranyi is offline
VanDyke Technical Support
 
Join Date: Jan 2017
Posts: 547
Hi aitijneg,

I'm noticing a few things that may help explain the behavior you're seeing. The biggest thing I'm see is that crt.Screen.Get is not very compatible with crt.Screen.Synchronous = True. When Synchronous is set to True data is only written to the screen when a WaitFor or Read is done. This means that between you sending the commands and attempting to use Screen.Get no data is being written to the screen. With no data on screen Get doesn't return anything.

Another option, that may work better for you, would be the ReadString method. This would look something like:

Code:
crt.Screen.Send("show vlan id "+ vl +"\r")
crt.Screen.WaitForString("show vlan id "+ vl +"\r")                
strResults = crt.Screen.ReadString(prompt)
fp.write(strResults + os.linesep)
This sends the command, waits for the command to appear on screen, captures screen data until the prompt appears, then writes the data. Also notice that I've replaced \n with \r, this should work as a return sending the command.

Another benefit of using this method is you can simplify the code for getting your prompt.

Code:
nRow = crt.Screen.CurrentRow
nColumn = crt.Screen.CurrentColumn -1
prompt = crt.Screen.Get(nRow, 1, nRow, nColumn)
prompt = prompt.strip()
Does making these changes help get you the behavior you're looking for?
__________________
Thanks,
--Eric

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #6  
Old 09-27-2018, 05:29 AM
aitijneg aitijneg is offline
Registered User
 
Join Date: Sep 2018
Location: Toronto
Posts: 4
Eric, thanks a lot for your help. It works now. I had to tweak your code a bit (remove '/r' from crt.Screen.WaitForString:
Code:
crt.Screen.WaitForString("show vlan id "+ vl)
and play with ReadString method as some switches have space character after '#' in their prompt while others don't.
Code:
strResults = crt.Screen.ReadString([prompt, prompt + " "])
After that script started to work perfectly.

Best regards,
Dmitriy
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:26 PM.