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 03-20-2018, 05:57 AM
conip conip is offline
Registered User
 
Join Date: Mar 2018
Posts: 7
Question python - multiple commands executed only in the last tab

hi,

I have one issue with executing multiple commands for multiple tabs.

All tabs are being opened sequentional in the "for" loop

when ssh or telnet session is established with SUCCESS condition I'm trying to invoke internal function "f_command(self)" but it is behaving strange

I've got each tab opened and got the MessageBox that I'm in a configure terminal but then the second command (actually the third) "end" is not sent to Screen, it is but only to the last TAB in the for loop.

Why is that?

I've forgotten to mention that Screen.Synchronous is set to True
and one strange thing: when I leave all of the TABs opened to timeout - this command "end" is being sent

Code:
previously when object class DEVICE is invoked I'm setting this property
command = "sh run | i snmp-server location\r"

class DEVICE:
	def __init__(self,DEV_IP=None,PASS=None,USER=None,FILE=None,JUMPBOX_NAME=None,CURRENT_TAB=None,COMMAND=None):
		self.DEV_IP = DEV_IP
		self.PASS = PASS
		self.USER = USER
		self.JUMPBOX_NAME = JUMPBOX_NAME
		self.FILE = FILE
		self.objTAB = CURRENT_TAB
		self.command = COMMAND

...
	def f_connect_ssh(self):
		...
		self.objTAB.Screen.Synchronous = True
		...
		self.f_command()
		...
		return



	def f_command(self):
		szPrompt = "#"
		# Wait for the command and the trailing CR to be echoed back from the remote
		# before we start capturing data... Otherwise, we'll capture the command we
		# issued, as well as the results, and in this example, we only want to
		# capture the results.
		self.objTAB.Screen.Send(self.command)
		self.objTAB.Screen.WaitForString("#",3)
		self.objTAB.Screen.Send("configure terminal\r\n")
		if self.objTAB.Screen.WaitForString("(config)#") == True:
			crt.Dialog.MessageBox("you are in CONF T") //invoked for each TAB as expected
			#self.objTAB.Activate()			//doesn't help
			self.objTAB.Screen.Send("end\r\n")
		else:
			crt.Dialog.MessageBox("you are not in CONF T")
		#self.FILE.write("\n"+szResult)
		#crt.Dialog.MessageBox(szResult)
		return

Last edited by conip; 03-20-2018 at 06:53 AM.
Reply With Quote
  #2  
Old 03-20-2018, 08:39 AM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,636
Hi conip,

You have not posted enough code for me to know what is happening.

Where is the For loop?

If your script contains sensitive data you don't want to post in the public forum, feel free to send a copy to support@vandyke.com and reference "Attn Brenda - Forum Thread #13053" in the subject line.
__________________
Thanks,
--Brenda

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #3  
Old 03-20-2018, 11:27 AM
conip conip is offline
Registered User
 
Join Date: Mar 2018
Posts: 7
no worries

I didn't want to paste too much as I thought it was irrelevant

Code:
import re
import hashlib
import os.path
#=========================================================
class DEVICE:
	def __init__(self,DEV_IP=None,PASS=None,USER=None,FILE=None,JUMPBOX_NAME=None,CURRENT_TAB=None,COMMAND=None):
		self.DEV_IP = DEV_IP
		self.PASS = PASS
		self.USER = USER
		self.JUMPBOX_NAME = JUMPBOX_NAME
		self.FILE = FILE
		self.objTAB = CURRENT_TAB
		self.command = COMMAND
	#-----------------------	
	def f_connect_ssh(self):
		errcode = 0
		result = ""
		data = ""
		errorMessages = ""
		#try:
		self.FILE.write("\nTrying SSH to - %s -> RESULT =  " % (str.strip(self.DEV_IP)))
			#1st "true/false" arg - true - wait for the connection to fully auth before continuing (default TRUE)
			#2nd "true/false" arg - if true - when attempt fails, method returns an object, if false - return exception(default FALSE)
		self.objTAB = crt.Session.ConnectInTab("/Firewall=firewall /SSH2 /ACCEPTHOSTKEYS /PASSWORD %s %s@%s" % (self.PASS,self.USER,self.DEV_IP), False, True)
		errorMessages = crt.GetLastErrorMessage()
		self.objTAB.Screen.Synchronous = True
		
		if self.objTAB.Session.Connected == True:
			screenrow = self.objTAB.Screen.CurrentRow - 1
			data = self.objTAB.Screen.Get(screenrow,1,screenrow,40)
			if self.objTAB.Screen.WaitForString('assword:', 4) == True:
				self.FILE.write("FAILED: WRONG Password")
				return "SSH-FAILED"
			else:
				self.FILE.write("SUCCESS")
				self.f_command()
				return "SSH-SUCCESS"
		else:
			if (errorMessages != ""):
				self.FILE.write("FAILED: Could not establish SSH")
				return "SSH-FAILED"
					
	#-----------------------
	def f_connect_telnet(self):
		errcode = 0
		errorMessages = ""
		self.FILE.write("\nTrying TELNET to - %s -> RESULT = " % (str.strip(self.DEV_IP)))
		try:
			self.objTAB = crt.Session.ConnectInTab("/Firewall=firewall /telnet %s " % (self.DEV_IP))
			self.objTAB.Screen.Synchronous = True
			if self.objTAB.Screen.WaitForString("sername:",2) == True:
				self.objTAB.Screen.Send(self.USER + "\r")
				self.objTAB.Screen.Send(self.PASS + "\r")
				if self.objTAB.Screen.WaitForString("sername:",2) == False:
					self.FILE.write("SUCCESS")
					self.f_command()
					return "TELNET-SUCCESS"
				else:
					self.FILE.write("FAILED: Wrong Password")
					return "TELNET-FAILED"
					
		except:
			errorMessages = crt.GetLastErrorMessage()
			self.FILE.write("FAILED: %s " % (errorMessages))
			return "TELNET-FAILED"

	#-----------------------
	def f_command(self):
		szPrompt = "#"
		# Wait for the command and the trailing CR to be echoed back from the remote
		# before we start capturing data... Otherwise, we'll capture the command we
		# issued, as well as the results, and in this example, we only want to
		# capture the results.
		self.objTAB.Screen.Send(self.command)
		self.objTAB.Screen.WaitForString("#",3)
		self.objTAB.Screen.Send("configure terminal\r\n")
		if self.objTAB.Screen.WaitForString("(config)#") == True:
			crt.Dialog.MessageBox("you are in CONF T")
			#self.objTAB.Activate()			//doesn't help
			self.objTAB.Screen.Send("end\r\n")
			self.objTAB.Screen.WaitForString("#")
		else:
			crt.Dialog.MessageBox("you are not in CONF T")
		#self.FILE.write("\n"+szResult)
		#crt.Dialog.MessageBox(szResult)
		return
	#-----------------------
	def f_close(self):
		self.objTAB.Close()
		return

#=========================================================		
		
		
def main():
	#------var initiation --------------
	crt.Screen.Synchronous = True
	auth_error_count = 0
	result = "SSH-FAILED"
	file_output = "C:\\python\\output.txt"
	dev_counter = 1
	command = "sh run | i snmp-server location\r"
	USERNAME = "user1"
	#------end of var initiation--------
	with open(file_output,'w') as f:
		try:
			pass
		except:
			crt.Dialog.MessageBox("can't open file")
			quit()
		
	file = open(file_output,'w') 
	
	PASS = crt.Dialog.Prompt("Enter password: " , "Login", "", True)

	with open("c:\\python\\MYFILE.txt","r") as MYFILE:
		MYDATA = MYFILE.readlines()		
	
	#=== table declaration [ IP , SNMP to be sent ]
	TABLE = [["" for j in range(2)] for i in range(len(MYDATA))]	
	for x in range(len(MYDATA)):
		LINE_X = MYDATA[x]
		lista = re.split(r'\|',LINE_X)
		IP_X = lista[0]
		SNMP_X = lista[1]
		TABLE[x][0] = IP_X
		TABLE[x][1] = SNMP_X		
	
	# checking default setting for Authentication prompt in case of failure 
	# if TRUE - windows popup, we need cli in order to process the output further
	# saving this setting to a variable (CRT_DEFAULT_cli_prompt) to set it as it
	# was before this change
	CRT_DEFAULT_SESSION = crt.OpenSessionConfiguration("Default")
	CRT_DEFAULT_cli_prompt = CRT_DEFAULT_SESSION.GetOption("Auth Prompts in Window")
	#crt.Dialog.MessageBox(str(CRT_DEFAULT_cli_prompt))
	
	
	if CRT_DEFAULT_cli_prompt == False:
		CRT_DEFAULT_SESSION.SetOption("Auth Prompts in Window", True)
		CRT_DEFAULT_SESSION.Save()
	
	
	file.write("===============================================================\n")
	
	#for x in range(len(TABLE)):
	for x in range(3):
		file.write(str(dev_counter)+") ")
		dev_counter = dev_counter + 1

		DEV_TEST = DEVICE(TABLE[x][0],PASS,USERNAME,file,"test","none",command)
		result = DEV_TEST.f_connect_ssh()

		if result == "SSH-FAILED":
			result = DEV_TEST.f_connect_telnet()
			if result == "TELNET-FAILED":
				crt.Dialog.MessageBox("You have provided wrong password\nTo avoid locking the account\nscript will be terminated")
				file.close()
				quit()
				#DEV_TEST.f_close()
		
		file.write("\n===============================================================\n")
	
	
	file.close()
	
	# setting default option to value from before script execution
	CRT_DEFAULT_SESSION.SetOption("Auth Prompts in Window", CRT_DEFAULT_cli_prompt)
	CRT_DEFAULT_SESSION.Save()

	
main()
Reply With Quote
  #4  
Old 03-20-2018, 02:16 PM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,636
Hi conip,

We are not that familiar with using Python classes. I think we will have to leave this one up to the forum community for any assistance.

I noticed you had commented out this line:
Code:
			#self.objTAB.Activate()			//doesn't help
I would suggest you might leave that in and then add a message box in main() (line 153, after where you are calling the connect function) that lets you know the tab has been activated so you can check if tabs one and two are being activated within that loop.
__________________
Thanks,
--Brenda

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #5  
Old 03-20-2018, 11:58 PM
conip conip is offline
Registered User
 
Join Date: Mar 2018
Posts: 7
ok - Im not a developer, I'm a network guy but
I don't believe its a matter of class/objects, its just a function being invoked in the "for" loop.

first 2 commands are being sent correctly
for some reasons it hangs with the 3rd one for all the tabs but last

are you not able to verify it?
Reply With Quote
  #6  
Old 03-21-2018, 07:29 AM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,636
Hi conip,

Did you try the previous suggestion?

Quote:
are you not able to verify it?
No, I am not. I do not have the same type system to which these commands would be legitimate. By the time I edit the script to a point where it would work in my test environment, it's not likely to resemble the original.

There are two places where you are sending \r\n when it should just be \r:
Code:
		self.objTAB.Screen.Send("configure terminal\r")

		if self.objTAB.Screen.WaitForString("(config)#") == True:
			crt.Dialog.MessageBox("you are in CONF T")
			#self.objTAB.Activate()			//doesn't help
			self.objTAB.Screen.Send("end\r")
			self.objTAB.Screen.WaitForString("#")
However, thanks for this clarification:
Quote:
first 2 commands are being sent correctly
for some reasons it hangs with the 3rd one for all the tabs but last
As it seems a bit different a problem than previously stated:
Quote:
I've got each tab opened and got the MessageBox that I'm in a configure terminal but then the second command (actually the third) "end" is not sent to Screen, it is but only to the last TAB in the for loop.

I noticed you did add the additional WaitForString() after sending "end" since the first post. Is that what changed the results from what was stated before?

Please provide a "blow by blow" explanation of what happens to each of the three tabs when the For loop executes.
__________________
Thanks,
--Brenda

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #7  
Old 03-21-2018, 09:19 AM
conip conip is offline
Registered User
 
Join Date: Mar 2018
Posts: 7
AHHH - that was it - THX !!! I'll repeat myself - you are GREAT!!!



Quote:
There are two places where you are sending \r\n when it should just be \r:
- I've deleted \n and it works

previously I've had the following:


ok - so these are the steps the script takes during the execution

1) new tab to new device is opened (ssh works)
2) script sends "sh run | i snmp-server location"
3) I see the output of this
4) scripts sends "configure terminal"
5) see the output
"Enter configuration commands, one per line ..."
hostname(config)#
6) see the messageBox (you are in CONF T)
7) I click OK
8) new tab is opened (and again exactly the same steps as from 1-7)
...
16) new tab is opened (again exactly the same steps and outputs as previously)
17) clicking OK (see that end is send and executed)


its funny but when closing the active tabs I see (just a sec before the tab is actually closed) that the "end" is being send but
Reply With Quote
  #8  
Old 03-21-2018, 09:39 AM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,636
Hi conip,

We like your script style. Keep up the good work!

What was the info after the quoted text?

Were you reporting a different issue?
__________________
Thanks,
--Brenda

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

Last edited by bgagnon; 03-21-2018 at 09:46 AM.
Reply With Quote
  #9  
Old 03-24-2018, 03:13 AM
conip conip is offline
Registered User
 
Join Date: Mar 2018
Posts: 7
hi Brenda,

the info after the quoted text was the description you asked for "step by step" what happened to each one of the tab.

as you have already helped me fixing this script its irrelevant.

nevertheless - thx again for your help. Its nice to hear you liked my script
Reply With Quote
  #10  
Old 03-24-2018, 10:20 AM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,636
Hi conip,

Thanks for the clarification. I thought that was what it was (after all, you typed it all out, might as well post it ) but just wanted to make sure.

Have a great weekend!
__________________
Thanks,
--Brenda

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
Reply

Tags
command , multiple , python , send , tabs

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 02:30 AM.