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-30-2015, 08:14 PM
andymc andymc is offline
Registered User
 
Join Date: Sep 2015
Posts: 14
Password Authentication Failed

Code :: Python

Mission :: Log into X amount of devices. Run a custom command, log the results. End.

Below code WORKS It logs into the end devices gets what I am looking for, in this case I was checking to see if the serial numbers matched against a list of know serial number. It then writes to an XML file, and that's it all done.

The problem with this code is this :: If a node were to be down, then I get a script error that I can seem to catch ??? Which as I work around I just ping the hosts before I run the script and then remove the downed hosts.

The second problem is, if I get an Authentication failure, I get a dialog box stating so, and I need to manually click the box to go away. Once I do so, my back-up credentials kick in and work fine. I work in an environment where if password A does not work then password B will, and if that does not work, I have a bigger issue on hand.


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

# 
# Purpose :: python script that iterates around a list of ip addresses, a custom 
# command can then be entered into these hosts and the output saved to a txt file.
#
#



errcode = 0

user1 = "first_user_name"
passwd1 = "first_password"

user2 = "second_user_name"
passwd2 = "second_password"

def main():

	end_string = "\rshow flash:"
	worlds_end_string = "flash:"
	
	what_you_looking_for = "show ver | i rocessor boar"
	results_should_contain = "Processor"
	# counter :: a simple counter used for itteration within the while loop
	num = 0
	
	# Note sure what this does, but seems to help with data ???
	crt.Screen.Synchronous = True
	
	
	file = open('hosts.txt', 'r')
	hosts = file.readlines()
	file.close()
	
	file = open('serial_numbers.txt', 'r')
	serial_numbers = file.readlines()
	file.close()

	# Open the results.txt file and start writing the XML document 
	file = open('results.xml' , 'w')
	file.write("<?xml version=\"1.0\"?>\n")
	file.write("<results>\n")
	file.close()
	
	# the for loop
	# each_node is an element within the hosts list, however, we do not make reference to it anywhere inside the loop
	# its purpose is simply to look at each hostst element, which in our case will be an IP address and to try and establish 
	# a connectio to it.
	
	for each_node in hosts:
	
		# try :: try and connect using your TACACS credentials 
		try:

			# Check to see if we are connected, and if we are disconnect the current session 
			if crt.Session.Connected: 
				crt.Session.Disconnect()
		
			# Build up a string to send to crt.Session.Connect 
			cmd = "/SSH2 /L %s /ACCEPTHOSTKEYS /PASSWORD %s /C 3DES /M SHA1 %s" % (user1, passwd1, each_node.rstrip())
			crt.Session.Connect(cmd)

			# Add a custom command once logged on
			crt.Screen.Send(what_you_looking_for+end_string)
		
			# we are reading until we get to the # symbol
			strResult = crt.Screen.ReadString("flash:")

			# if the string finds something interesting then do
			# if the string does not contain what we are looking for then the results will be 
			# -1
			# thats why we say is not eqqual to 
			# crt.Dialog.MessageBox(serial_numbers[num])
			dummy = serial_numbers[num].rstrip()
			if strResult.find(dummy) != -1 :
			# if 1 == 1 :
				
				# Open the file foo.txt and append to the current data 
				with open("results.xml", "a") as myfile:
					#myfile.write(hosts[num])
					myfile.write("<host id=\"" + hosts[num].rstrip() + "\">")
					myfile.write("<output>" + strResult + "</output>\n")
					myfile.write("<matched> SERIAL NUM MATCHED </matched>\n")
					# myfile.write("<output> Serial Number Matched </output>\n")
					myfile.write("</host>")
					
					# Close open file
					myfile.close()

			else :
				with open("results.xml", "a") as myfile:
					#myfile.write(hosts[num])
					myfile.write("<host id=\"" + hosts[num].rstrip() + "\">")
					myfile.write("<output>" + strResult + "</output>\n")
					myfile.write("<matched> NO MATCH </matched>\n")
					# myfile.write("<output> Serial Number Matched </output>\n")
					myfile.write("</host>")
					
			# increment the counter by 1 
			num += 1
	
		# If the aboved failed, then try and login with the Other credentials
		except ScriptError:	
			
				# Check to see if we are connected, and if we are disconnect the current session 
				if crt.Session.Connected: 
					crt.Session.Disconnect()
			
				# Build up a string to send to crt.Session.Connect 
				cmd = "/SSH2 /L %s /ACCEPTHOSTKEYS /PASSWORD %s /C 3DES /M SHA1 %s" % (user2, passwd2, each_node.rstrip())
				crt.Session.Connect(cmd)

				# Add a custom command once logged on
				crt.Screen.Send(what_you_looking_for+end_string)
			
				# we are reading until we get to the # symbol
				strResult = crt.Screen.ReadString("flash:")

				#if strResult.find(serial_numbers[num]) != -1 :
				dummy = serial_numbers[num].rstrip()
				if strResult.find(dummy) != -1 :
				#if 1 == 1 :
					
					# Open the file foo.txt and append to the current data 
					with open("results.xml", "a") as myfile:
						#myfile.write(hosts[num])
						myfile.write("<host id=\"" + hosts[num] + "\">")
						myfile.write("<output>" + strResult + "</output>\n")
						myfile.write("<matched> SERIAL NUM MATCHED </matched>\n")
						# myfile.write("<output> Serial Number Matched </output>\n")
						myfile.write("</host>")
						
						# Close open file
						myfile.close()
				else :
					with open("results.xml", "a") as myfile:
						#myfile.write(hosts[num])
						myfile.write("<host id=\"" + hosts[num] + "\">")
						myfile.write("<output>" + strResult + "</output>\n")
						myfile.write("<matched> NO MATCH </matched>\n")
						# myfile.write("<output> Serial Number Matched </output>\n")
						myfile.write("</host>")
						
				# increment the counter by 1 
				num += 1
			
	if crt.Session.Connected: 
		crt.Session.Disconnect()
	
	file = open('results.xml' , 'a')
	file.write("</results>\n")
	file.close()
	
	crt.Dialog.MessageBox("Thats me all done.")

main()
So anyway I read the forums etc, I find that I need to enable

"Disable logon prompts in terminal window"

So I have another shot, brand new code...

This one seemed to work, but I get strange results, the commands, i.e.

show ver

get entered well before the device is loaded up, and I believe that is because, I no longer wait to confirm I am authenticated with the connect method. But if I do wait this causes more issues.


Code:
def main():

	# Note sure what this does, but seems to help with data ???
	crt.Screen.Synchronous = True


	num = 0
	for e in host:
		get_connected(host[num])
		num += 1

def disconnect_me():
	if crt.Session.Connected: 
		crt.Session.Disconnect()
	
def get_connected(each_node):

	try:
		# make sure i am disconnected 
		disconnect_me()
		cmd = "/SSH2 /L %s /ACCEPTHOSTKEYS /PASSWORD %s /C 3DES /M SHA1 %s" % (user1, passwd1, each_node.rstrip())
		crt.Session.Connect(cmd, False, True)
		crt.Screen.Send("show ver" + end_string)
		
		# we are reading until we get to the # symbol
		strResult = crt.Screen.ReadString("flash:")
		
		password_authentication_failure = crt.Screen.WaitForString("Password authentication failed", 50000)
		if password_authentication_failure:
			# make sure i am disconnected 
			disconnect_me()
			
			# Now we are going to try and log in as otherpass.
			cmd = "/SSH2 /L %s /ACCEPTHOSTKEYS /PASSWORD %s /C 3DES /M SHA1 %s" % (user2, passwd2, each_node.rstrip())
			crt.Session.Connect(cmd, False, True)
			crt.Screen.Send("show ver" + end_string)
			# we are reading until we get to the # symbol
			strResult = crt.Screen.ReadString("flash:")
			return
			
		else:
			# This should never ever be called
			# But if it is please display meaningfull message
			crt.Dialog.MessageBox("Total Melt Down !")

	#This should be called upon when the node is down
	except ScriptError:
		errcode = crt.GetLastError()

	# This should be called each and every time
	if errcode != 0:
		# make sure i am disconnected 
		disconnect_me()
		
	# This should never be called 
	else:
		crt.Dialog.MessageBox("Total Melt Down !")

main()
To those who are smarted than I, please have a look at this, your suggestion would be very greatful
Reply With Quote
  #2  
Old 10-01-2015, 10:56 AM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 1,096
If you want to handle errors connecting, you're on the right track -- mostly.

Yes. Enable the option to have auth prompts appear in terminal window. You can do this within a script, too, but would need to do so prior to calling any Connect*() functions. If you set the option in Global Options -> Default Session --> Edit Default Session, then it will apply to scripts that use Connect()
or ConnectInTab() with ad hoc connection args like "/SSH2", etc.

Regarding commands getting sent too soon, you'll need to make sure the remote is ready to receive commands before you send them. Typically you use crt.Screen.WaitForStrings() for some unique portion of the shell prompt to appear.

There's a script example already on our sticky that's written in python and does most of what it seems you desire to accomplish.

Check out the example "Read Data From Separate Hosts/Commands File And Log To Individual Files", and consider using it as a base for working towards the solution you need.

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


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 09:29 AM.