在Xshell可以像这样一个文件批量导入主机:

https://blog.netsarang.com/91/importing-csv-formatted-host-information-to-xshell/

在CRT上也可以,格式和Xshell的一样,但前提是需要运行一个自定义脚本:

脚本:https://forums.vandyke.com/showthread.php?p=37089#post37089

操作:https://www.vandyke.com/support/tips/importsessions.html

视频操作:https://youtu.be/f7nMFYhGoiI

简单操作步骤:

脚本文件内容:

ImportArbitraryDataFromFileToSecureCRTSessions.vbs

# $language = "VBScript"
# $interface = "1.0"' ImportArbitraryDataFromFileToSecureCRTSessions.txt
'   (Designed for use with SecureCRT 7.2 and later)
'
'   Last Modified: 23 Feb, 2018
'      - Warn user if the configuration folder appears to be read-only.
'      - Fall back to secondary locations in which to attempt to write
'        the results log file in case the user's Documents, Desktop, or
'        configuration folder are all read-only or otherwise un-write-able
'        for the user.
'
'   Last Modified: 21 Dec, 2017
'      - Allow multiple 'description' fields on the same line. All will be
'        compounded together with each one ending up on a separate line in
'        the Session's Description session option.
'      - Allow 'username' field to be defaulted in the header line
'      - Allow 'folder' field to be defaulted in the header line
'      - Duplicate sessions are now imported with unique time-stamped
'        names (for each additional duplicate). Earlier versions of this
'        script would overwrite the first duplicate with any subsequent
'        duplicates that were found in the data file.
'      - When displaying the browse dialog, filter now includes both
'        CSV and TXT file types, to make it easier to find the data file
'        (less clicking).
'      - Allow for protocol field to be defaulted, if not present in the
'        header line.
'      - Fix error messages relating to invalid header lines so they no
'        longer indicate Protocol is a required field. If it's not present
'        the Default Session's protocol value will be used.
'      - Allow header fields to be case-insensitive so that "Description"
'        and "UserName" work just the same as "description" and "username"
'
'   Last Modified: 09 Aug, 2017
'      - Changed from using CInt to CLng in order to support port
'        specifications larger than 32768 (max integer supported in VBScript)
'
'   Last Modified: 20 Feb, 2017
'      - Added progress info to status bar
'      - When a line from the source file has bogus/incomplete data on it,
'        the script no longer halts operation, but instead, continues the
'        import process for all remaining legitimate lines, skipping any
'        lines that don't have sufficient/accurate format.
'      - Changed format of summary message shown at end to include header
'        line so entries that were skipped can be easily copied into a new
'        document to be imported.
'      - Toggle the Session Manager automatically so that imported sessions
'        are more immediately visible in the Session Manager.
'
'   Last Modified: 20 Jan, 2015
'      - Combined TAPI protocol handling (which is no longer
'        supported for mass import) with Serial protocol
'        import errors.
'      - Enhanced example .csv file data to show subfolder specification.
'
'   Last Modified: 21 Mar, 2012
'      - Initial version for public forums
'
' DESCRIPTION
' This sample script is designed to create sessions from a text file (.csv
' format by default, but this can be edited to fit the format you have).
'
' To launch this script, map a button on the button bar to run this script:
'    http://www.vandyke.com/support/tips/buttonbar.html
'
' The first line of your data file should contain a comma-separated (or whatever
' you define as the g_strDelimiter below) list of supported "fields" designated
' by the following keywords:
' -----------------------------------------------------------------------------
' session_name: The name that should be used for the session. If this field
'               does not exist, the hostname field is used as the session_name.
'       folder: Relative path for session as displayed in the Connect dialog.
'     hostname: The hostname or IP for the remote server.
'     protocol: The protocol (SSH2, SSH1, telnet, rlogin)
'         port: The port on which remote server is listening
'     username: The username for the account on the remote server
'    emulation: The emulation (vt100, xterm, etc.)
'  description: The comment/description. Multiple lines are separated with '\r'
' =============================================================================
'
'
' As mentioned above, the first line of the data file instructs this script as
' to the format of the fields in your data file and their meaning.  It is not a
' requirement that all the options be used. For example, notice the first line
' of the following file only uses the "hostname", "username", and "protocol"
' fields.  Note also that the "protocol" field can be defaulted so that if a
' protocol field is empty it will use the default value.
' -----------------------------------------------------------------------------
'   hostname,username,folder,protocol=SSH2
'   192.168.0.1,root,_imported,SSH1
'   192.168.0.2,admin,_imported,SSH2
'   192.168.0.3,root,_imported\folderA,
'   192.168.0.4,root,,
'   192.168.0.5,admin,_imported\folderB,telnet
'   ... and so on
' =============================================================================
'
'
' The g_strDefaultProtocol variable will only be defined within the
' ValidateFieldDesignations function if the protocol field has a default value
' (e.g., protocol=SSH2), as read in from the first line of the data file.
Dim g_strDefaultProtocol' The g_strDefaultFolder variable will only be defined within the
' ValidateFieldDesignations function if the folder field has a default value
' (e.g., folder=Site34), as read in from the first line of the data file.
Dim g_strDefaultFolder' The g_strDefaultUsername variable will only be defined within the
' ValidateFieldDesignations function if the username field has a default value
' (e.g., username=bensolo), as read in from the first line of the data file.
Dim g_strDefaultUsername' If your data file uses spaces or a character other than comma as the
' delimiter, you would also need to edit the g_strDelimiter value a few lines
' below to indicate that fields are separated by spaces, rather than by commas.
' For example:
'   g_strDelimiter = " "' Using a ";" might be a good alternative for a file that includes the comma
' character as part of any legitimate session name or folder name, etc.
Dim g_strDelimiter
g_strDelimiter = ","      ' comma
' g_strDelimiter = " "    ' space
' g_strDelimiter = ";"    ' semi-colon
' g_strDelimiter = chr(9) ' tab
' g_strDelimiter = "|||"  ' a more unique example of a delimiter.' The g_strSupportedFields indicates which of all the possible fields, are
' supported in this example script.  If a field designation is found in a data
' file that is not listed in this variable, it will not be imported into the
' session configuration.
Dim g_strSupportedFields
g_strSupportedFields = _"description,emulation,folder,hostname,port,protocol,session_name,username"' If you wish to overwrite existing sessions, set the
' g_bOverwriteExistingSessions to True; for this example script, we're playing
' it safe and leaving any existing sessions in place :).
Dim g_bOverwriteExistingSessions
g_bOverwriteExistingSessions = FalseDim g_fso, g_shell
Set g_fso = CreateObject("Scripting.FileSystemObject")
Set g_shell = CreateObject("WScript.Shell")Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8Dim g_strHostsFile, g_strExampleHostsFile, g_strMyDocs, g_strMyDesktop
g_strMyDocs = g_shell.SpecialFolders("MyDocuments")
g_strMyDesktop = g_shell.SpecialFolders("Desktop")
g_strHostsFile = g_strMyDocs & "\MyDataFile.csv"
g_strExampleHostsFile = _vbtab & "hostname,protocol,username,folder,emulation" & vbcrlf & _vbtab & "192.168.0.1,SSH2,root,Linux Machines,XTerm" & vbcrlf & _vbtab & "192.168.0.2,SSH2,root,Linux Machines,XTerm" & vbcrlf & _vbtab & "..." & vbcrlf & _vbtab & "10.0.100.1,SSH1,admin,CISCO Routers,VT100" & vbcrlf & _vbtab & "10.0.101.1,SSH1,admin,CISCO Routers,VT100" & vbcrlf & _vbtab & "..." & vbcrlf & _vbtab & "myhost.domain.com,SSH2,administrator,Windows Servers,VShell" & _vbtab & "..." & vbcrlf
g_strExampleHostsFile = Replace(g_strExampleHostsFile, ",", g_strDelimiter)Dim g_strConfigFolder, strFieldDesignations, vFieldsArray, vSessionInfog_strConfigFolder = GetConfigPath()Dim strSessionName, strHostName, strPort
Dim strUserName, strProtocol, strEmulation
Dim strPathForSessions, strLine, nFieldIndex
Dim strSessionFileName, strFolder, nDescriptionLineCount, strDescriptionDim g_strLastError, g_strErrors, g_strSessionsCreated
Dim g_nSessionsCreated, g_nDataLinesg_strDateTimeTag = GetDateTimeTag()g_strBogusLinesNotImported = ""Import'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sub Import()g_strHostsFile = crt.Dialog.FileOpenDialog( _"Please select the host data file to be imported.", _"Open", _g_strHostsFile, _"CSV/Text Files (*.txt;*.csv)|*.txt;*.csv|All files (*.*)|*.*")If g_strHostsFile = "" ThenExit SubEnd If' Open our data file for reading
    Dim objDataFileSet objDataFile = g_fso.OpenTextFile(g_strHostsFile, ForReading, False)' Now read the first line of the data file to determine the field' designations
    On Error Resume NextstrFieldDesignations = objDataFile.ReadLine()nError = Err.NumberstrErr = Err.DescriptionOn Error Goto 0If nError <> 0 ThenIf nError = 62 Thencrt.Dialog.MessageBox("Your data file is empty." & vbcrlf & _"Fill it with import data and try again." & vbcrlf & vbcrlf & _"ReadLine() Error code: " & nError & vbcrlf & _"ReadLine() Error text: " & strErr)Elsecrt.Dialog.MessageBox("Unable to read the first line from your data file!" & _vbcrlf & vbcrlf & _"ReadLine() Error code: " & nError & vbcrlf & vbcrlf & _"ReadLine() Error text: " & strErr)End IfExit SubEnd If' Validate the data file
    If Not ValidateFieldDesignations(strFieldDesignations) ThenobjDataFile.CloseExit SubEnd If' Get a timer reading so that we can calculate how long it takes to import.nStartTime = Timer' Here we create an array of the items that will be used to create the new' session, based on the fields separated by the delimiter specified in' g_strDelimitervFieldsArray = Split(strFieldDesignations, g_strDelimiter)' Loop through reading each line in the data file and creating a session' based on the information contained on each line.
    Do While Not objDataFile.AtEndOfStreamstrLine = ""strLine = objDataFile.ReadLinecrt.Session.SetStatusText "Processing line #: " & _NN(objDataFile.Line - 1, 4)' This sets v_File Data array elements to each section of strLine,' separated by the delimitervSessionInfo = Split(strLine, g_strDelimiter)If UBound(vSessionInfo) < UBound(vFieldsArray) ThenIf Trim(strLine) <> "" Theng_strErrors = g_strErrors & vbcrlf & _"Insufficient data on line #" & _NN(objDataFile.Line - 1, 4) & ": " & strLineElseg_strErrors = g_strErrors & vbcrlf & _"Insufficient data on line #" & _NN(objDataFile.Line - 1, 4) & ": [Empty Line]"End IfElseIf UBound(vSessionInfo) > UBound(vFieldsArray) Theng_strErrors = g_strErrors & vbcrlf & _"==> Number of data fields on line #" & _NN(objDataFile.Line - 1, 4) & _"(" & UBound(vSessionInfo) & ") " & _"does not match the number of fields in the header " & _"(" & UBound(vFieldsArray) & ")." & vbcrlf & _"    This line will not be imported (Does the session name have a character that " & _"matches the delimiter you're using? Also check for characters that Windows does not " & _"allow to be used in filenames: /\:*?""<>|): " & vbcrlf & vbtab & strLineg_strBogusLinesNotImported = g_strBogusLinesNotImported & _vbcrlf & strLineElse' Variable used to determine if a session file should actually be' created, or if there was an unrecoverable error (and the session' should be skipped).
            Dim bSaveSessionbSaveSession = True' Now we will match the items from the new file array to the correct' variable for the session's ini fileFor nFieldIndex = 0 To UBound(vSessionInfo)Select Case LCase(vFieldsArray(nFieldIndex))Case "session_name"strSessionName = vSessionInfo(nFieldIndex)' Check folder name for any invalid characters
                        Dim reSet re = New RegExpre.Pattern = "[\\\|\/\:\*\?\""\<\>]"
                        If re.Test(strSessionName) ThenbSaveSession = FalseIf g_strErrors <> "" Then g_strErrors = _vbcrlf & g_strErrorsg_strErrors = _"Error: " & _"Invalid characters found in SessionName """ & _strSessionName & """ specified on line #" & _NN(objDataFile.Line - 1, 4) & _": " & strLine & g_strErrorsg_strBogusLinesNotImported = g_strBogusLinesNotImported & _vbcrlf & strLineEnd IfCase "port"strPort = Trim(vSessionInfo(nFieldIndex))If Not IsNumeric(strPort) ThenbSaveSession = FalseIf g_strErrors <> "" Then g_strErrors = _vbcrlf & g_strErrorsg_strErrors = _"Error: Invalid port """ & strPort & _""" specified on line #" & _NN(objDataFile.Line - 1, 4) & _": " & strLine & g_strErrorsg_strBogusLinesNotImported = g_strBogusLinesNotImported & _vbcrlf & strLineEnd IfCase "protocol"strProtocol = Trim(lcase(vSessionInfo(nFieldIndex)))Select Case strProtocolCase "ssh2"strProtocol = "SSH2"Case "ssh1"strProtocol = "SSH1"Case "telnet"strProtocol = "Telnet"Case "serial", "tapi"bSaveSession = Falseg_strErrors = g_strErrors & vbcrlf & _"Error: Unsupported protocol """ & _vSessionInfo(nFieldIndex) & _""" specified on line #" & _NN(objDataFile.Line - 1, 4) & _": " & strLineCase "rlogin"strProtocol = "RLogin"Case ElseIf g_strDefaultProtocol <> "" ThenstrProtocol = g_strDefaultProtocolElsebSaveSession = FalseIf g_strErrors <> "" Then g_strErrors = _vbcrlf & g_strErrorsg_strErrors = _"Error: Invalid protocol """ & _vSessionInfo(nFieldIndex) & _""" specified on line #" & _NN(objDataFile.Line - 1, 4) & _": " & strLine & g_strErrorsg_strBogusLinesNotImported = g_strBogusLinesNotImported & _vbcrlf & strLineEnd IfEnd Select ' for protocols
Case "hostname"strHostName = Trim(vSessionInfo(nFieldIndex))If strHostName = "" ThenbSaveSession = Falseg_strErrors = g_strErrors & vbcrlf & _"Warning: 'hostname' field on line #" & _NN(objDataFile.Line - 1, 4) & _" is empty: " & strLineg_strBogusLinesNotImported = g_strBogusLinesNotImported & _vbcrlf & strLineEnd IfCase "username"strUserName = Trim(vSessionInfo(nFieldIndex))Case "emulation"strEmulation = LCase(Trim(vSessionInfo(nFieldIndex)))Select Case strEmulationCase "xterm"strEmulation = "Xterm"Case "vt100"strEmulation = "VT100"Case "vt102"strEmulation = "VT102"Case "vt220"strEmulation = "VT220"Case "ansi"strEmulation = "ANSI"Case "linux"strEmulation = "Linux"Case "scoansi"strEmulation = "SCOANSI"Case "vshell"strEmulation = "VShell"Case "wyse50"strEmulation = "WYSE50"Case "wyse60"strEmulation = "WYSE60"Case ElsebSaveSession = Falseg_strErrors = g_strErrors & vbcrlf & _"Warning: Invalid emulation """ & _strEmulation & """ specified on line #" & _NN(objDataFile.Line - 1, 4) & _": " & strLineg_strBogusLinesNotImported = g_strBogusLinesNotImported & _vbcrlf & strLineEnd SelectCase "folder"strFolder = Trim(vSessionInfo(nFieldIndex))' Check folder name for any invalid characters' Note that a folder can have subfolder designations,' so '/' is a valid character for the folder (path).Set re = New RegExpre.Pattern = "[\|\:\*\?\""\<\>]"
                        If re.Test(strFolder) ThenbSaveSession = FalseIf g_strErrors <> "" Then g_strErrors = _vbcrlf & g_strErrorsg_strErrors = _"Error: Invalid characters in folder """ & _strFolder & """ specified on line #" & _NN(objDataFile.Line - 1, 4) & _": " & strLine & g_strErrorsg_strBogusLinesNotImported = g_strBogusLinesNotImported & _vbcrlf & strLineEnd IfCase "description"strCurDescription = Trim(vSessionInfo(nFieldIndex))If strDescription = "" ThenstrDescription = strCurDescriptionElsestrDescription = strDescription & "\r" & strCurDescriptionEnd IfCase Else' If there is an entry that the script is not set to use' in strFieldDesignations, stop the script and display a' message
                        Dim strMsg1strMsg1 = "Error: Unknown field designation: " & _vFieldsArray(nFieldIndex) & vbcrlf & vbcrlf & _"       Supported fields are as follows: " & _vbcrlf & vbcrlf & vbtab & g_strSupportedFields & _vbcrlf & _vbcrlf & "       For a description of " & _"supported fields, please see the comments in " & _"the sample script file."If Trim(g_strErrors) <> "" ThenstrMsg1 = strMsg1 & vbcrlf & vbcrlf & _"Other errors found so far include: " & _g_strErrorsEnd IfMsgBox strMsg1, _vbOkOnly, _"Import Data To SecureCRT Sessions: Data File Error"Exit SubEnd SelectNextIf bSaveSession Then' Use hostname if a session_name field wasn't presentIf strSessionName = "" ThenstrSessionName = strHostNameEnd IfIf strFolder = "" ThenstrFolder = g_strDefaultFolderEnd If' Canonicalize the path to the session, as neededstrSessionPath = strSessionNameIf strFolder <> "" ThenstrSessionPath = strFolder & "/" & strSessionNameEnd If' Strip any leading '/' characters from the session pathIf Left(strSessionPath, 1) = "/" ThenstrSessionPath = Mid(strSessionPath, 2)End IfIf SessionExists(strSessionPath) ThenIf Not g_bOverwriteExistingSessions Then' Append a unique tag to the session name, if it already existsstrSessionPath = strSessionPath & _"(import_" & GetDateTimeTag & ")"End IfEnd If' Now: Create the session.' Copy the default session settings into new session name and set the' protocol.  Setting protocol protocol is essential since some variables' within a config are only available with certain protocols.  For example,' a telnet configuration will not be allowed to set any port forwarding' settings since port forwarding settings are specific to SSH.Set objConfig = crt.OpenSessionConfiguration("Default")If strProtocol = "" ThenstrProtocol = g_strDefaultProtocolEnd IfobjConfig.SetOption "Protocol Name", strProtocol' We opened a default session & changed the protocol, now we' save the config to the new session path:
                objConfig.Save strSessionPath' Now, let's open the new session configuration we've' saved, and set up the various parameters that were specified' in the file.
                If Not SessionExists(strSessionPath) Thencrt.Dialog.MessageBox("Failed to create a new session '" & _strSessionPath & "'." & vbcrlf & _vbcrlf & _"Does your configuration folder have " & _"sufficient permissions to allow writing/creating " & _"files?" & vbcrlf & vbcrlf & _vbtab & _"Options > Global Options > Configuration Paths" & _vbcrlf & vbcrlf & _"Fix permissions on your configuration folder and " & _"then try running this script again.")Exit SubEnd IfSet objConfig = crt.OpenSessionConfiguration(strSessionPath)objConfig.SetOption "Emulation", strEmulationIf LCase(strProtocol) <> "serial" ThenIf strHostName <> "" ThenobjConfig.SetOption "Hostname", strHostNameEnd IfIf strUsername = "" ThenstrUsername = g_strDefaultUsernameEnd IfIf strUserName <> "" ThenobjConfig.SetOption "Username", strUserNameEnd IfEnd IfIf strDescription <> "" ThenobjConfig.SetOption "Description", Split(strDescription, "\r")End IfIf UCase(strProtocol) = "SSH2" ThenIf strPort = "" Then strPort = 22objConfig.SetOption "[SSH2] Port", CLng(strPort)End IfIf UCase(strProtocol) = "SSH1" ThenIf strPort = "" Then strPort = 22objConfig.SetOption "[SSH1] Port", CLng(strPort)End IfIf UCase(strProtocol) = "TELNET" ThenIf strPort = "" Then strPort = 23objConfig.SetOption "Port", CLng(strPort)End If' If you would like ANSI Color enabled for all imported sessions (regardless' of value in Default session, remove comment from following line)' objConfig.SetOption "ANSI Color", True' Add other "SetOption" calls desired here...' objConfig.SetOption "Auto Reconnect", True' objConfig.SetOption "Color Scheme", "Traditional"' objConfig.SetOption "Color Scheme Overrides Ansi Color", True' objConfig.SetOption "Copy to clipboard as RTF and plain text", True' objConfig.SetOption "Description", Array("This session was imported from a script on " & Now)' objConfig.SetOption "Firewall Name", "YOUR CUSTOM FIREWALL NAME HERE"' objConfig.SetOption "Line Send Delay", 15' objConfig.SetOption "Log Filename V2", "${VDS_USER_DATA_PATH}\_ScrtLog(%S)_%Y%M%D_%h%m%s.%t.txt"' objConfig.SetOption "Rows", 60' objConfig.SetOption "Cols", 140' objConfig.SetOption "Start Tftp Server", True' objConfig.SetOption "Use Word Delimiter Chars", True' objConfig.SetOption "Word Delimiter Chars", " <>()+=$%!#*"' objConfig.SetOption "X Position", 100' objConfig.SetOption "Y Position", 50
objConfig.SaveIf g_strSessionsCreated <> "" Theng_strSessionsCreated = g_strSessionsCreated & vbcrlfEnd Ifg_strSessionsCreated = g_strSessionsCreated & "    " & strSessionPathg_nSessionsCreated = g_nSessionsCreated + 1End If' Reset all variables in preparation for reading in the next line of' the hosts info file.strEmulation = ""strPort = ""strHostName = ""strFolder = ""strUserName = ""strSessionName = ""strDescription = ""nDescriptionLineCount = 0End IfLoopg_nDataLines = objDataFile.LineobjDataFile.Closecrt.Session.SetStatusText ""Dim strResultsstrResults = "Import operation completed in " & _GetMinutesAndSeconds(Timer - nStartTime)If g_nSessionsCreated > 0 ThenstrResults = strResults & _vbcrlf & _String(70, "-") & vbcrlf & _"Number of Sessions created: " & g_nSessionsCreated & vbcrlf & _vbcrlf & _g_strSessionsCreatedElsestrResults = strResults & vbcrlf & _String(70, "-") & vbcrlf & _"No sessions were created from " & g_nDataLines & " lines of data."End IfIf g_strErrors = "" ThenstrResults = "No errors/warnings encountered from the import operation." & vbcrlf & vbcrlf & strResultsElsestrResults = "Errors/warnings from this operation include: " & g_strErrors & vbcrlf & _String(70, "-") & vbcrlf & _strResultsEnd IfIf g_strBogusLinesNotImported <> "" ThenstrResults = _"The following lines from the data file were *not* imported for " & _"various reasons detailed below:" & vbcrlf & _String(70, "=") & vbcrlf & _strFieldDesignations & _g_strBogusLinesNotImported & vbcrlf & _String(70, "-") & vbcrlf & _"Fix the above lines to resolve the issue and save the fixed lines " & _"to a new file. You can then run this script again to import these " & _"skipped sessions." & vbcrlf & vbcrlf & strResultsEnd IfSet cFilenames = CreateObject("Scripting.Dictionary")cFilenames.Add Replace(g_strMyDocs & "/__SecureCRT-Session-ImportLog-" & g_strDateTimeTag & ".txt", "\", "/"), ""
    cFilenames.Add Replace(g_strMyDesktop & "/__SecureCRT-Session-ImportLog-" & g_strDateTimeTag & ".txt", "\", "/"), ""
    cFilenames.Add Replace(g_strConfigFolder & "/__SecureCRT-Session-ImportLog-" & g_strDateTimeTag & ".txt", "\", "/"), ""
bSuccess = FalsestrResults = strResults & vbcrlf & vbcrlf & _String(80, "-") & vbcrlfFor Each strFilename In cFilenames.Keys():On Error Resume NextSet objFile = g_fso.OpenTextFile(strFilename, ForWriting, True)strErr = Err.DescriptionnError = Err.NumberOn Error Goto 0If nError = 0 ThenbSuccess = TrueExit ForElsecrt.Session.SetStatusText("Unable to open results file.")strResults = strResults & vbcrlf & _"Failed to write summary results to: " & strFilenameEnd IfIf Not g_fso.FileExists(strFilename) ThenbSuccess = FalseElseExit ForEnd IfNextIf Not bSuccess Thencrt.Clipboard.Text = strResultscrt.Dialog.MessageBox( _"Attempted to write summary results to the file locations below, " & _"but access was denied." & vbcrlf & vbtab & vbcrlf & vbtab & _Join(cFilenames.Keys(), vbcrlf & vbtab) & vbcrlf & vbcrlf & _"Results are in the clipboard. " & _"Paste this data into your favorite app now to see what occurred.")Exit SubEnd IfobjFile.WriteLine strResultsobjFile.Close' Display the log file as an indication that the information has been' imported.g_shell.Run chr(34) & strFilename & chr(34), 5, False
End Sub'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'      Helper Methods and Functions
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function ValidateFieldDesignations(ByRef strFields)If Instr(strFieldDesignations, g_strDelimiter) = 0 ThenDim strErrorMsg, strDelimiterDisplaystrErrorMsg = "Invalid header line in data file. " & _"Delimiter character not found: "If Len(g_strDelimiter) > 1 ThenstrDelimiterDisplay = g_strDelimiterElseIf Asc(g_strDelimiter) < 33 or Asc(g_strDelimiter) > 126 ThenstrDelimiterDisplay = "ASCII[" & Asc(g_strDelimiter) & "]"ElsestrDelimiterDisplay = g_strDelimiterEnd IfEnd IfstrErrorMsg = strErrorMsg & strDelimiterDisplay & vbcrlf & vbcrlf & _"The first line of the data file is a header line " & _"that must include" & vbcrlf & _"a '" & strDelimiterDisplay & _"' separated list of field keywords." & vbcrlf & _vbcrlf & "'hostname' is a required key word." & _vbcrlf & vbcrlf & _"The remainder of the lines in the file should follow the " & _vbcrlf & _"pattern established by the header line " & _"(first line in the file)." & vbcrlf & "For example:" & vbcrlf & _g_strExampleHostsFileMsgBox strErrorMsg, _vbOkOnly, _"Import Data To SecureCRT Sessions"Exit FunctionEnd IfIf Instr(LCase(strFieldDesignations), "hostname") = 0 ThenstrErrorMsg = "Invalid header line in data file. " & _"'hostname' field is required."If Len(g_strDelimiter) > 1 ThenstrDelimiterDisplay = g_strDelimiterElseIf Asc(g_strDelimiter) < 33 Or Asc(g_strDelimiter) > 126 ThenstrDelimiterDisplay = "ASCII[" & Asc(g_strDelimiter) & "]"ElsestrDelimiterDisplay = g_strDelimiterEnd IfEnd IfMsgBox strErrorMsg & vbcrlf & _"The first line of the data file is a header line " & _"that must include" & vbcrlf & _"a '" & strDelimiterDisplay & _"' separated list of field keywords." & vbcrlf & _vbcrlf & "'hostname' is a required keyword." & _vbcrlf & vbcrlf & _"The remainder of the lines in the file should follow the " & _vbcrlf & _"pattern established by the header line " & _"(first line in the file)." & vbcrlf & "For example:" & vbcrlf & _g_strExampleHostsFile, _vbOkOnly, _"Import Data To SecureCRT Sessions"Exit FunctionEnd IfIf Instr(LCase(strFieldDesignations), "protocol") = 0 ThenSet objConfig = crt.OpenSessionConfiguration("Default")g_strDefaultProtocol = objConfig.GetOption("Protocol Name")Else' We found "protocol", now look for a default protocol designationvFields = Split(strFields,g_strDelimiter)For each strField In vFieldsIf (InStr(LCase(strField), "protocol") > 0) And _(Instr(LCase(strField), "=") >0) Theng_strDefaultProtocol = UCase(Split(strField, "=")(1))' Fix the protocol field since we know the default protocol' valuestrFields = Replace(strFields, strField, "protocol")End IfNextEnd IfvFields = Split(strFields, g_strDelimiter)For Each strField In vFieldsIf (Instr(LCase(strField), "folder") > 0) And _(Instr(LCase(strField), "=") > 0) Theng_strDefaultFolder = Split(strField, "=")(1)' Fix the folder field since we know the default folderstrFields = Replace(strFields, strField, "folder")End IfIf (Instr(LCase(strField), "username") > 0) And _(Instr(LCase(strField), "=") > 0) Theng_strDefaultUsername = Split(strField, "=")(1)' Fix the username field since we know the default usernamestrFields = Replace(strFields, strField, "username")End IfNextValidateFieldDesignations = True
End Function'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function ReadRegKey(strKeyPath)On Error Resume NextErr.ClearReadRegKey = g_shell.RegRead(strKeyPath)If Err.Number <> 0 Then' Registry key must not have existed.' ReadRegKey will already be empty, but for the sake of clarity, we'll' set it to an empty string explicitly.ReadRegKey = ""End IfOn Error Goto 0
End Function'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function CreateFolderPath(strPath)
' Recursive function
    If g_fso.FolderExists(strPath) ThenCreateFolderPath = TrueExit FunctionEnd If' Check to see if we've reached the drive rootIf Right(strPath, 2) = ":\" ThenCreateFolderPath = TrueExit FunctionEnd If' None of the other two cases were successful, so attempt to create the' folder
    On Error Resume Nextg_fso.CreateFolder strPathnError = Err.NumberstrErr = Err.DescriptionOn Error Goto 0If nError <> 0 Then' Error 76 = Path not found, meaning that the full path doesn't exist.' Call ourselves recursively until all the parent folders have been' created:If nError = 76 Then _CreateFolderPath(g_fso.GetParentFolderName(strPath))On Error Resume Nextg_fso.CreateFolder strPathnError = Err.NumberstrErr = Err.DescriptionOn Error Goto 0' If the Error is not = 76, then we have to bail since we no longer have' any hope of successfully creating each folder in the treeIf nError <> 0 Theng_strLastError = strErrExit FunctionEnd IfEnd IfCreateFolderPath = True
End Function'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function NN(nNumber, nDesiredDigits)
' Normalizes a number to have a number of zeros in front of it so that the
' total length of the number (displayed as a string) is nDesiredDigits.
    Dim nIndex, nOffbyDigits, strResultnOffbyDigits = nDesiredDigits - Len(nNumber)NN = nNumberIf nOffByDigits = 0 Then Exit FunctionIf nOffByDigits > 0 Then' The number provided doesn't have enough digitsstrResult = String(nOffbyDigits, "0") & nNumberElse' The number provided has too many digits.
nOffByDigits = Abs(nOffByDigits)' Only remove leading digits if they're all insignificant (0).If Left(nNumber, nOffByDigits) = String(nOffByDigits, "0") ThenstrResult = Mid(nNumber, nOffByDigits + 1)Else' If leading digits beyond desired number length aren't 0, we'll' return the number as originally passed in.strResult = nNumberEnd IfEnd IfNN = strResult
End Function'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function GetMinutesAndSeconds(nTotalSecondsElapsed)Dim nMinutesElapsed, nSecondsValue, nSecondsElapsedIf nTotalSecondsElapsed = 0 ThenGetMinutesAndSeconds = "less than a second."Exit FunctionEnd If' Convert seconds into a fractional minutes value.nMinutesElapsed = nTotalSecondsElapsed / 60' Convert the decimal portion into the number of remaining seconds.nSecondsValue = nMinutesElapsed - Fix(nMinutesElapsed)nSecondsElapsed = Fix(nSecondsValue * 60)' Remove the fraction portion of minutes value, keeping only the digits to' the left of the decimal point.nMinutesElapsed = Fix(nMinutesElapsed)' Calculate the number of milliseconds using the four most significant' digits of only the decimal fraction portion of the number of seconds' elapsed.nMSeconds = Fix(1000 * (nTotalSecondsElapsed - Fix(nTotalSecondsElapsed)))' Form the final string to be returned and set it as the value of our' function.GetMinutesAndSeconds = nMinutesElapsed & " minutes, " & _nSecondsElapsed & " seconds, and " & _nMSeconds & " ms"
End Function'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function SessionExists(strSessionPath)
' Returns True if a session specified as value for strSessionPath already
' exists within the SecureCRT configuration.
' Returns False otherwise.
    On Error Resume NextSet objTosserConfig = crt.OpenSessionConfiguration(strSessionPath)nError = Err.NumberstrErr = Err.DescriptionOn Error Goto 0' We only used this to detect an error indicating non-existance of session.' Let's get rid of the reference now since we won't be using it:Set objTosserConfig = Nothing' If there wasn't any error opening the session, then it's a 100% indication' that the session named in strSessionPath already existsIf nError = 0 ThenSessionExists = TrueElseSessionExists = FalseEnd If
End Function'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function GetDateTimeTag()' Use WMI to get at the current time values.  This info will be used' to avoid overwriting existing sessions by naming new sessions with' the current (unique) timestamp.Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")For Each objItem In colItemsstrLocalDateTime = objItem.LocalDateTimeExit ForNext' strLocalDateTime has the following pattern:' 20111013093717.418000-360   [ That is,  YYYYMMDDHHMMSS.MILLIS(zone) ]GetDateTimeTag = Left(strLocalDateTime, 18)
End Function'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Function GetConfigPath():Set objConfig = crt.OpenSessionConfiguration("Default")' Try and get at where the configuration folder is located. To achieve' this goal, we'll use one of SecureCRT's cross-platform path' directives that means "THE path this instance of SecureCRT' is using to load/save its configuration": ${VDS_CONFIG_PATH}.' First, let's use a session setting that we know will do the' translation between the cross-platform moniker ${VDS_CONFIG_PATH}' and the actual value... say, "Upload Directory V2"strOptionName = "Upload Directory V2"' Stash the original value, so we can restore it later...strOrigValue = objConfig.GetOption(strOptionName)' Now set the value to our moniker...objConfig.SetOption strOptionName, "${VDS_CONFIG_PATH}"' Make the change, so that the above templated name will get written' to the config...
    objConfig.Save' Now, load a fresh copy of the config, and pull the option... so' that SecureCRT will convert from the template path value to the' actual path value:Set objConfig = crt.OpenSessionConfiguration("Default")strConfigPath = objConfig.GetOption(strOptionName)' Now, let's restore the setting to its original valueobjConfig.SetOption strOptionName, strOrigValueobjConfig.Save' Now return the config pathGetConfigPath = strConfigPath
End Function

View Code

SecureCRT也能和Xshell一样批量导入主机相关推荐

  1. zabbix4.2批量导入主机

    批量导入主机 导出两台已有主机,默认导出文件为xml 根据XML文件进行分割,有用的标签是hosts 配置标签hosts脚本 配置hosts文件 生成导入文件 批量导入主机 多次执行需要删除之前生成的 ...

  2. Xshell批量导入IP地址

    我的xshell被覆盖了~~~结果原来的host没了,很郁闷要一个一个添加,网上找了很长时间在Xshell中批量添加IP的文章,结果都不行. 最后找到了https://blog.netsarang.c ...

  3. 怎么接收layui上传的文件_layui 上传文件_批量导入数据UI的方法

    使用layui的文件上传组件,可以方便的弹出文件上传界面. 效果如下: 点击[批量导入]按钮调用js脚本importData(config)就可以实现数据上传到服务器. 脚本: /*** * 批量导入 ...

  4. AD下批量导入域用户

    如果您的域环境比较大,那么设置用户可能会不方便,就"新建用户"都可能重复做上几十遍....是不是很.....呵呵... 下面介绍一个工具"csvde.exe", ...

  5. 大数据批量导入,解决办法,实践从定时从 sqlserver 批量同步数据到 mySql

    c#代码,批量导入数据代码 public class MySql_Target : ZFCommon.DataAccesser.Base.DABase{public MySql_Target(){th ...

  6. word录入表单数据 java 导入系统,java导入excel | 怎么把excel中的数据批量导入到word中的表格中...

    用javascript怎么实现把excel中的数据批量导入到数据库表中 这个js不能直接实现吧 我们程序用到 先读取excel内容转换成数组 然后放到页面上 再提交表单 储存 MySql如何批量添加数 ...

  7. txt 乱码_STATA数据导入——将TXT、EXCEL、SAS、SPSS数据/批量导入STATA

    作者:Misszhou早早早 邮箱:zlr1220@126.com 使用Stata进行数据分析时面临的第一个问题是如何将各种类型的数据转换为dta.格式,导入的途径主要有以下几种: Stat/Tran ...

  8. HBase结合MapReduce批量导入

    Hbase是Hadoop生态体系配置的数据库,我们可以通过HTable api中的put方法向Hbase数据库中插入数据,但是由于put效率太低,不能批量插入大量的数据,文本将详细介绍如何通过MapR ...

  9. 在leangoo项目里怎么批量导入成员,更改项目成员权限,移除项目成员?

    批量导入成员: 1 点击看板清单页面上的成员按钮 2. 点击添加成员按钮 更改项目成员权限 移除项目成员 浏览器访问官网:leangoo.com

最新文章

  1. GitHub开源城市结构公交路线数据可视化
  2. 如何写一份让面试官眼前一亮的简历?
  3. 密度聚类OPTICS算法
  4. Lexer的设计--中(4)
  5. mock平台架构及实现
  6. 转载:简单介绍Python中的try和finally和with方法
  7. 153. 寻找旋转排序数组中的最小值 golang
  8. 伦敦帝国学院M+T实验室,全奖博士招生
  9. 机器学习笔记(十):梯度下降 | 凌云时刻
  10. Mac Python下载安装教程
  11. Oracle P6培训系列:16为作业分配资源的预算数量
  12. 二阶系统的时间响应及动态性能(时域分析)
  13. 10、【易混淆概念集】-第六章1 三点估算 类比估算和参数估算的区别 储备分析 历时估算 项目进度网络图
  14. 银行电话精准营销的探索性分析并基于XGboost进行潜在客户预测建模
  15. arcgis批量裁剪影像tif流程_ArcGIS超级工具SPTOOLS-影像的批量裁剪和批量合并
  16. java实现接口签名
  17. win10下VMware15安装centos7详细步骤及遇到的问题
  18. 设计模式---单例模式Singleton
  19. 关于计算机这一块儿的认识
  20. JS小数点保留后2位

热门文章

  1. Linux系统运行级与启动机制剖析
  2. Python函数中的变量和函数返回值
  3. (转) 淘淘商城系列——Redis五种数据类型介绍
  4. PHP函数操作数组(集合贴)
  5. 数据库时间字段排序问题
  6. 怎样用Java自制优秀的图片验证码?这样!
  7. zookeeper注册中心
  8. Curator实现分布式锁的基本原理-LockInternals.attemptLock
  9. 为什么需要ORM 框架
  10. 前置通知(Before Advice)