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 06-19-2018, 05:03 AM
winniec winniec is offline
Registered User
 
Join Date: Jun 2018
Posts: 5
Question Python Disconnect will make the command unfinished

I have a script that auto connect to ip address which is in a file "SessionList.txt". One system for one tab. Then, we have a list of commands that will sent to each tab and enable logging.
However, if I disable the logging or disconnect in the end, I will miss output of some of my commands. Would you please help to solve this?

It will take about one seconds with running the command except "show log". The "show log" command will flushing the screen. And I could not determine how long it will take to complete. Anyway, it may take more than 3 seconds.

Even I change the tab.Screen.WaitForString("#",2) to "20" but no help. I still get my commands unfinished with the disconnect code.

It is also weird that the MessageBox will pop up even my commands have not finished. It normally pop up when the "show log" is printing. Why would it happen?

Thank you very much.

Here is my script:

import os
LOG_DIRECTORY = os.path.join(
os.getcwd(), 'Xunjian') ##This needs to change the location?
COMMANDS = [
"show version",
"show system",
"show cpuinfo",
"show meminfo",
"show ip route",
"show envm",
"show log",
#"show tech",
"show ha log",
"show cable modem summary total"
]


def main():

if not os.path.exists(LOG_DIRECTORY):
os.mkdir(LOG_DIRECTORY)

if not os.path.isdir(LOG_DIRECTORY):
crt.Dialog.MessageBox(
"Log output directory %r is not a directory" % LOG_DIRECTORY)
return

##You can delete the bellowing def and disable the definition of the above if you already have tabs connected.
AutoConnectTab("SessionList.txt")
######If you don't want to manual enter the user/pwd name. Then you can enable the AutoConnect def.
#AutoConnect("SessionList.txt")

###Confirm if it is safe to input commands
while True:
if not SCRIPT_TAB.Screen.WaitForCursor(1):
break

#####Get the tab, and send commands to the tabs
skippedTabs=""
Count=crt.GetTabCount()

for i in range(1, Count+1):
tab = crt.GetTab(i)
tab.Activate()
##Get the hostname
strCmd = "show run | in ^hostname\r"
tab.Screen.Send(strCmd)
tab.Screen.WaitForStrings([strCmd + "\r", strCmd + "\n"])
host = tab.Screen.ReadString(["\r", "\n"])
if "" in host:
Host = host.split()[1]
hostname=Host[1:-1]
else:
Host = "unknown-hostname"
hostname=Host

##Identify the filename and enable the logging
tab.Session.LogFileName = os.path.join(LOG_DIRECTORY, hostname + '.txt')

if tab.Session.Connected==True:
tab.Session.Log(True) ##Save the session log
tab.Screen.Send("page-off\r")

###Send the commands to the tab
for command in COMMANDS:
try:
tab.Screen.Send(command+"\n")
tab.Screen.WaitForString("#",2)
except:
return

else: ##Check if there is any skippedTabs
if skippedTabs=="":
skippedTabs=str(i)
else:
skippedTabs=skippedTabs+","+str(i)

tab.Session.Log(False) ##I will miss my last two commands here.
tab.Session.Disconnect() ##If I add "#" with the two commands. All the commands could be finished.

##Go back to the original one
#SCRIPT_TAB.Activate()


if skippedTabs!="":
skippedTabs="\n\nThe following tabs did not receive the command:"+skippedTabs
crt.Dialog.Message("We have skippedTabs:" + str(skippedTabs))
crt.Dialog.MessageBox("The following command was sent to all connected tabs:" + str(Count))


LaunchViewer(LOG_DIRECTORY)

def LaunchViewer(filename):
try:
os.startfile(filename)
except AttributeError:
subprocess.call(['open', filename])


def CreateObjTab(user, password,session):
objNewTab = crt.Session.ConnectInTab("/TELNET %s 23" % session)
objNewTab.Screen.WaitForString("login:")
objNewTab.Screen.Send(user + "\r")
objNewTab.Screen.WaitForString("Password:")
objNewTab.Screen.Send(password + "\r")
objNewTab.Screen.WaitForString(">")
objNewTab.Screen.Send("enable\r")
objNewTab.Screen.WaitForString("Password")
objNewTab.Screen.Send("casa\r")

def AutoConnectTab(file): ###Auto connect sessions from a txt
####This is to Open the "SessionList.txt" and get a list of the ip address
if not os.path.exists(file):
return
sessionFile = open(file, "r")
sessionArray = []
for line in sessionFile:
session = line.strip()
if session:
sessionArray.append(session)
sessionFile.close()
# Receive variable
user = crt.Dialog.Prompt("Enter user name:", "Login", "", False)
password = crt.Dialog.Prompt("Enter password:", "Login", "", True)
for session in sessionArray[0:]:
try:
CreateObjTab(user, password,session)
except ScriptError:
pass
if not SCRIPT_TAB.Session.Connected:
return


main()
Reply With Quote
  #2  
Old 06-19-2018, 08:13 AM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,636
Hi winniec,

One thing that jumps out at me immediately is that I don't see where you have ever set Synchronous to True:
tab.Screen.Synchronous = True
Even though it's a VBScript manual, Scripting Essentials explains in chapter 4 why this is so vital to be sure you don't miss data (section with Avoid "Missing" Data with Screen.Synchronous = True as the title).

Also, a minor thing, in one spot you are using \n with the Send() instead of \r:
Code:
        ###Send the commands to the tab
            for command in COMMANDS:
                try:
                    tab.Screen.Send(command+"\n")
What your script does is very close to one of our example scripts in the forums here so you might look it over for further tips/clues.
__________________
Thanks,
--Brenda

VanDyke Software
Technical Support
support@vandyke.com
(505) 332-5730
Reply With Quote
  #3  
Old 06-21-2018, 06:18 AM
winniec winniec is offline
Registered User
 
Join Date: Jun 2018
Posts: 5
Quote:
Originally Posted by bgagnon View Post
Hi winniec,

One thing that jumps out at me immediately is that I don't see where you have ever set Synchronous to True:
tab.Screen.Synchronous = True
Even though it's a VBScript manual, Scripting Essentials explains in chapter 4 why this is so vital to be sure you don't miss data (section with Avoid "Missing" Data with Screen.Synchronous = True as the title).

Also, a minor thing, in one spot you are using \n with the Send() instead of \r:
Code:
        ###Send the commands to the tab
            for command in COMMANDS:
                try:
                    tab.Screen.Send(command+"\n")
What your script does is very close to one of our example scripts in the forums here so you might look it over for further tips/clues.
Thanks for the response.
I have a synchronized code at the very beginning. Sorry I did not paste entirely.
SCRIPT_TAB=crt.GetScriptTab()
SCRIPT_TAB.Screen.Synchronous=True
SCRIPT_TAB.Screen.IgnoreEscape = True

I solved this issue with adding one command in the command list. Then filter the key word in the last word to decide whether we stop the tab.

Add one more "show version" in the COMMAND list. Then add these at the end:

if tab.Screen.WaitForStrings("Running Image"):
tab.Session.Log(False)
tab.Session.Disconnect()

Though it works....but seems not so perfectly...
Reply With Quote
  #4  
Old 07-21-2019, 06:10 AM
phonethihakyaw phonethihakyaw is offline
Registered User
 
Join Date: Jul 2019
Posts: 1
Unhappy Python Script Error In Linux

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

# LogCommandOutput.py
#
# Description:
# Sends commands one by one as listed in the COMMANDS array to the
# remote machine. The results of each command are captured into a
# variable, and then written to an individual log file (one log file
# for each command). Once all the commands have been run, a file
# browser is launched, with the first command output file selected
# within the file browser window.
#
# Demonstrates:
# This example script demonstrates how to log the output of specific
# commands to separate files (one file for each command) without
# having to manually turn logging on before and off after running each
# command.
#
# This specific example doesn't use the logging script API to write
# data to a file. Instead, we use the ReadString() method to capture
# the result of each command and write it manually to a file of our
# choosing (LOG_FILE_TEMPLATE serves as a template for the file name
# which changes with each command that is issued to the remote. For
# example, the results of the first command will be written to a file
# named Command_01_Results.txt, the results of the 2nd command to
# Command_02_Results.txt, etc...).
#
# Specifically, this example automates the logging process by:
# - Using an array of commands that are to be sent to the remote
# system (COMMANDS)
# - Using SCRIPT_TAB.Screen.Send() to issue each command.
# - Using the SCRIPT_TAB.Screen.ReadString() method to not only wait
# for an indication that the command sent has been completed, but
# also capture all of the text received while the command was
# running.
#
# Note: This script assumes that SecureCRT is currently connected to the
# remote device prior to running this script. Otherwise, the script
# will exit with an error message.
#
# If you want this script to perform the connection sequence as
# well, simply replace the "if not SCRIPT_TAB.Session.Connected:"
# block within the main() function below with a line similar to
# the following:
#
# SCRIPT_TAB.Session.Connect("/S MySessionName")

import os
import subprocess

LOG_DIRECTORY = os.path.join(
os.path.expanduser('~'), 'LogOutputOfSpecificCommand')

LOG_FILE_TEMPLATE = os.path.join(
LOG_DIRECTORY, "Command_%(NUM)s_Results.txt")

SCRIPT_TAB = crt.GetScriptTab()

COMMANDS = [
"pwd",
"ls -lR --color /tmp",
"ps -eaf | grep vshelld",
"tail -100 /var/log/messages",
# "sh run",
# "",
# "",
]

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():

if not os.path.exists(LOG_DIRECTORY):
os.mkdir(LOG_DIRECTORY)

if not os.path.isdir(LOG_DIRECTORY):
crt.Dialog.MessageBox(
"Log output directory %r is not a directory" % LOG_DIRECTORY)
return

if not SCRIPT_TAB.Session.Connected:
crt.Dialog.MessageBox(
"Not Connected. Please connect before running this script.")
return

# Instruct WaitForString and ReadString to ignore escape sequences when
# detecting and capturing data received from the remote (this doesn't
# affect the way the data is displayed to the screen, only how it is handled
# by the WaitForString, WaitForStrings, and ReadString methods associated
# with the Screen object.
SCRIPT_TAB.Screen.IgnoreEscape = True
SCRIPT_TAB.Screen.Synchronous = True

# If this script is run as a login script, there will likely be data
# arriving from the remote system. This is one way of detecting when it's
# safe to start sending data. If this script isn't being run as a login
# script, then the worst it will do is seemingly pause for one second
# before determining what the prompt is.
# If you plan on supplying login information by waiting for username and
# password prompts within this script, do so right before this while loop.
while True:
if not SCRIPT_TAB.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.

# 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)
rowIndex = SCRIPT_TAB.Screen.CurrentRow
colIndex = SCRIPT_TAB.Screen.CurrentColumn - 1

prompt = SCRIPT_TAB.Screen.Get(rowIndex, 0, rowIndex, colIndex)
prompt = prompt.strip()

for (index, command) in enumerate(COMMANDS):
command = command.strip()

# Set up the log file for this specific command
logFileName = LOG_FILE_TEMPLATE % {"NUM" : NN(index + 1, 2)}

# Send the command text to the remote
SCRIPT_TAB.Screen.Send(command + '\r')

# Wait for the command to be echo'd back to us.
SCRIPT_TAB.Screen.WaitForString('\r', 1)
SCRIPT_TAB.Screen.WaitForString('\n', 1)

# Use the ReadString() method to get the text displayed while
# the command was runnning. Note also that the ReadString()
# method captures escape sequences sent from the remote machine
# as well as displayed text. As mentioned earlier in comments
# above, if you want to suppress escape sequences from being
# captured, set the Screen.IgnoreEscape property = True.
result = SCRIPT_TAB.Screen.ReadString(prompt)
result = result.strip()

filep = open(logFileName, 'wb+')

# If you don't want the command logged along with the results, comment
# out the very next line
filep.write("Results of command: " + command + os.linesep)

# Write out the results of the command to our log file
filep.write(result + os.linesep)

# Close the log file
filep.close()

# Once we're complete, let's bring up the directory containing the
# log files.
LaunchViewer(LOG_DIRECTORY)


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def LaunchViewer(filename):
try:
os.startfile(filename)
except AttributeError:
subprocess.call(['open', filename])


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def NN(number, digitCount):
# Normalizes a single digit number to have digitCount 0s in front of it
format = "%0" + str(digitCount) + "d"
return format % number


main()

Dear Securecrt Developers,

Please help me to resolve this issue in my Linux because i can't run this script and it display OSError in Message box and can't save output file.it works fine on Windows.
Reply With Quote
  #5  
Old 07-22-2019, 07:09 AM
bgagnon bgagnon is offline
VanDyke Technical Support
 
Join Date: Oct 2008
Posts: 4,636
Hi phonethihakyaw,

Quote:
Please help me to resolve this issue in my Linux because i can't run this script and it display OSError in Message box and can't save output file.it works fine on Windows.
What error do you get?
__________________
Thanks,
--Brenda

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

Tags
command , diconnect , loggging , tab

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 07:33 PM.