#$language = "Python" #$interface = "1.0" # SFTPTabAutomation.py # Last Modified: # 23 Jan, 2023 # - Demonstrate how to retrieve local and remote working directories # - Demonstrate how to determine local "Documents" folder # - Demonstrate one approach of how to detect 'cd' failures # - Demonstrate how to display text to SecureCRT's terminal screen # without sending any data to the connected host/device # - With success, display a countdown leading up to closing the SFTP # tab. # - With failure, display error message in red and leave SFTP tab open # # 26 Mar, 2020 # - Bug Fix: Close is a method; use Close() # - Added Disconnect() call prior to Close() # - No longer use a Dialog to display success/fail. Instead # we send text to the screen. # # 04 Apr, 2012 # - Initial version # # DESCRIPTION: # Demonstrates opening an SFTP tab & automating a file download. # Prior to running this script, the currently active tab must already be # connected with the SSH2 protocol to a remote server that is capable of # providing SFTP functionality; otherwise an error will occur and script # execution will be halted. # --------------------------------------------------------------------- def Main(): # Open up an SFTP tab based on the current (script tab) connection objSFTPTab = crt.GetScriptTab().ConnectSftp() # When using Get2, Screen.Synchronous should be False, or else nothing # will appear on the screen (since we're not using any WaitForString() # or ReadString() methods). objSFTPTab.Screen.Synchronous = False # Wait for the 'sftp> ' prompt to appear on the screen as an indication that # interaction with the SFTP tab can begin. while True: strScreenText = objSFTPTab.Screen.Get2( 1, 1, crt.Screen.Rows, crt.Screen.Columns) # If we spot the "sftp> " prompt on the screen, then we're pretty sure # it's safe to start interacting with the SFTP tab. Exit the loop: if "sftp> " in strScreenText: break # Otherwise, the absence of the "sftp> " prompt on the screen indicates # that the tab isn't quite ready to go... sleep for a few milliseconds # and then check again... crt.Sleep(10) # Now we can work with the SFTP connection. # NOTE: We turn on Synch = True now so that we don't miss any data. # This means that for EVERY Screen.Send(), we must do an accompanying # Screen.WaitForString() so that we don't get out of sync. objSFTPTab.Screen.Synchronous = True # Determine our current directory objSFTPTab.Screen.Send("pwd\r") WaitForSequence(["pwd", "\r\n"], objSFTPTab) strCurPWD = objSFTPTab.Screen.ReadString("\r\nsftp> ") objSFTPTab.Session.SetStatusText("Cur: {}".format(strCurPWD)) # Get a long file listing with the "ls -l" command objSFTPTab.Screen.Send("ls -l\r") WaitForSequence(["ls -l", "\r\n"], objSFTPTab) # Use ReadString to wait for the "sftp> " prompt to arrive, capturing all # the data we receive in the meantime. strFileListing = objSFTPTab.Screen.ReadString("sftp> ") if len(strFileListing) > 1024: strDataToDisplay = strFileListing[:1024] + "\r\n[truncated]" else: strDataToDisplay = strFileListing #crt.Dialog.MessageBox("File Listing\r\n{}".format(strDataToDisplay)) # Change local directory (local to the SecureCRT Windows machine) to the # folder in which the downloaded file should be saved: import os strLocDocuments = os.path.join(os.path.expanduser("~"), "Documents") objSFTPTab.Screen.Send("lcd {}\r".format(strLocDocuments)) objSFTPTab.Screen.WaitForString("sftp> ") objSFTPTab.Screen.Send("lpwd\r") WaitForSequence(["lpwd", "\r\n"], objSFTPTab) strCurLocDir = objSFTPTab.Screen.ReadString("\r\nsftp> ") #crt.Dialog.MessageBox("Current local dir: {}".format(strCurLocDir)) # Change remote directory to the path where the file to be downloaded # is expected to exist: objSFTPTab.Screen.Send("cd tmp\r") WaitForSequence(["cd tmp", "\r\n"], objSFTPTab) strCDResults = objSFTPTab.Screen.ReadString("sftp> ") # If there is a failure changing to a directory, the results string # will not be empty (instead, it will contain text of the failure). if len(strCDResults) > 0: DisplayToScreen("\r\n\r\n" + "\033[31mFailed to cd to directory!\r\n\r\n\t" + "\033[7m{}\033[0m".format(strCDResults), objSFTPTab ) DisplayToScreen("\r\n\r\nError detected; leaving tab open.", objSFTPTab) return # Get (download) a file named MyFile.txt objSFTPTab.Screen.Send("get MyFile.txt\r") WaitForSequence(["get MyFile.txt", "\r\n"], objSFTPTab) strResults = objSFTPTab.Screen.ReadString("sftp> ") # Check for success/failure if not "100%" in strResults: DisplayToScreen( "\r\n\r\n" + "\033[31mFailed to get file!\r\n\r\n\t" + "\033[7m{}\033[0m".format(strResults), objSFTPTab) DisplayToScreen("\r\n\r\nError detected; leaving tab open.", objSFTPTab) return # Put the information we received from the screen into an array where # each line of the output gathered is in a unique element of the array vDataLines = strResults.split("\r\n") # Display success along with the 2nd-to-last line of the information; # that's the line that contains stats about the successful transfer. DisplayToScreen("\r\n\r\n" + "\033[7;32mFile transfer successful\033[0m\r\n" + "{}\r\n\r\n".format(vDataLines[-2]), objSFTPTab) # Display a countdown of 5 seconds until the tab will get closed. nCountdownSeconds = 5 while nCountdownSeconds > 0: if nCountdownSeconds > 1: strSeconds = "seconds" else: strSeconds = "second " DisplayToScreen("\rClosing SFTP tab in {} {}...".format( nCountdownSeconds, strSeconds), objSFTPTab) crt.Sleep(1000) nCountdownSeconds -= 1 # Close the SFTP tab once we're done. In case the Global Option "Confirm # on disconnect" is enabled, we'll first disconnect this SFTP tab prior # to attempting to close it. objSFTPTab.Session.Disconnect() objSFTPTab.Close() # --------------------------------------------------------------------- def WaitForSequence(vSequenceOfStrings, objTab): for strEntry in vSequenceOfStrings: objTab.Screen.WaitForString(strEntry) # --------------------------------------------------------------------- def DisplayToScreen(strData, objTab): bOrigSync = objTab.Screen.Synchronous if bOrigSync: objTab.Screen.Synchronous = False objTab.Screen.Send(strData, True) crt.Sleep(1) if bOrigSync: objTab.Screen.Synchronous = True Main()