# $language = "VBScript" # $interface = "1.0" ' ImportMPuttyXMLConfigToSecureCRTSessions.vbs ' DESCRIPTION: ' Imports MPutty (MTPutty) session configurations into SecureCRT saved ' sessions. ' ' To ensure that any pre-existing sessions are not overwritten, imported ' sessions are stored in SecureCRT's Session Manager in a new folder named: ' ##_mPuttyImport(YYYYMMDD_HHMMSS.mmm) ' ' Only the following fields will be imported from the XML file: ' Session Path & Session Name (Name) ' Hostname (Host) ' Protocol (Protocol) -- only SSH2, Telnet, Raw, Rlogin, and Serial ' Port (Port) ' ' 03 May, 2016 ' - Initial revision ' --------------------------------------------------------------------- Set g_shell = CreateObject("WScript.Shell") Set g_fso = CreateObject("Scripting.FileSystemObject") Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 g_strDesktop = g_shell.SpecialFolders("Desktop") Dim g_nSessionsCreated, g_strWarnings g_nSessionsCreated = 0 Dim g_colDuplicatesOfExistingSessions, g_colSessionsCreated Set g_colDuplicatesOfExistingSessions = CreateObject("Scripting.Dictionary") Set g_colSessionsCreated = CreateObject("Scripting.Dictionary") g_nStartTime = Timer Dim g_vCommands(5) ' GetTimeDateWithMilliseconds is a function defined in this script which ' will return something like: ' 20150114093717.418 [ That is, YYYYMMDD_HHMMSS.mmm ] g_strImportDestinationFolder = "##_mPuttyImport(" & GetTimeDateWithMilliseconds & ")" Sub Main() strPathToDataFile = _ crt.Dialog.FileOpenDialog( _ "Specify Path to existing mPutty (MTPutty) exported XML export file", _ "Import", _ g_strDesktop & "\*.xml", _ "XML files (*.xml)|*.xml||") If strPathToDataFile = "" Then Exit Sub nImportStartTime = Timer ' Create an XML document object using Microsoft's building XMLDOM object: Set xmlDoc = CreateObject("Microsoft.XMLDOM") ' Instruct the XMLDOM object to be synchronous (wait for the XML file ' to be fully parsed prior to moving on with the script): xmlDoc.Async = False ' Now, actually load the contents of the XML file into the xmlDoc object xmlDoc.Load strPathToDataFile If xmlDoc.parseError.errorCode <> 0 Then crt.Dialog.MessageBox "A parsing error was detected while attempting to " & _ "read in the specified XML file: " & strPathToDataFile & _ vbcrlf & vbcrlf & _ "Error description: " & vbcrlf & xmlDoc.parseError.reason & vbcrlf & _ "This could mean that your XML file is saved with an encoding " & _ "that does not match the XML content-specified encoding. For " & _ "example, if your XML file were saved in ASCII format, but the " & _ "first line of the XML file said the following, then you would " & _ "need to either change the line in your XML file to reflect the " & _ "actual format of the file, or re-save the file in the format or " & _ "encoding specified on the line:" & vbcrlf & _ vbtab & "" Exit Sub End If ' Set up a dictionary of supported protocols ' The keys are the way the protocol is found in mPutty/MTPutty's XML file ' The items are the way they are found in SecureCRT session INI files Set cProt = CreateObject("Scripting.Dictionary") cProt.Add "0", "SSH2" ' Default protocol for SecureCRT, don't know what it means for mputty. cProt.Add "1", "Raw" cProt.Add "2", "Telnet" cProt.Add "3", "Rlogin" cProt.Add "4", "SSH2" cProt.Add "5", "Serial" ' XPath instruction to return all nodes containing SessionData strXPathQuery = "//Node[@Type=""1""]" nSessionsImported = 0 ' Get a list of all connections in the XML doc Set objNodeList = xmlDoc.SelectNodes(strXPathQuery) If objNodeList.Length > 0 Then ' Iterate over each connection node and pull out the associated data For Each objNode in objNodeList ' Get the necessary attributes: strSessionFolder = GetFullPathForNode(objNode.parentNode) nProtocol = objNode.SelectNodes("PuttyConType")(0).Text If Not cProt.Exists(nProtocol) Then If g_strWarnings <> "" Then g_strWarnings = g_strWarnings & vbcrlf g_strWarnings = g_strWarnings & _ "Unknown mputty connection protocol type: " & nProtocol & ". Session will not be imported" Else strProtocol = cProt(nProtocol) strSessionName = objNode.SelectNodes("DisplayName")(0).Text nPort = objNode.SelectNodes("Port")(0).Text strHostname = objNode.SelectNodes("ServerName")(0).Text strUsername = objNode.SelectNodes("UserName")(0).Text Select Case strProtocol Case "SSH2" If nPort = "0" Then nPort = "22" Case "Raw" If nPort = "0" Then nPort = "23" Case "Telnet" If nPort = "0" Then nPort = "23" Case "Rlogin" If nPort = "0" Then nPort = "513" Case "Serial" ' File names cannot be COM1, COM2, ' etc, so we'll have to adjust the ' session name accordingly. Set reCOM = new RegExp reCOM.Pattern = "^COM\d+$" If reCOM.Test(strSEssionName) Then strSessionName = "Serial - " & strSessionName End If End Select strSessionPath = strSessionFolder & "/" & strSessionName ' Remove any spaces in folder path that would prevent nested ' folders from being created dynamically Set re = New regexp re.global = True re.pattern = "\s*\\\s*" strSessionPath = re.Replace(strSessionPath, "\") ' Remove initial backslash strSessionPath = Right(strSessionPath, Len(strSessionPath) - 1) ' Copy the default session settings into new session name and set the ' protocol. Setting protocol is essential since some variables ' within a config are only available with certain protocols. Set objConfig = crt.OpenSessionConfiguration("Default") objConfig.SetOption "Protocol Name", strProtocol ' Before saving a session to the existing configuration, find out if there ' is already an existing session with that same name. If there is, we'll ' append a tag to the session name: " - Imported from mPutty/MTPutty" so as to avoid ' wiping out any existing sessions that might already exist. On Error Resume Next Set objTosserConfig = crt.OpenSessionConfiguration(strSessionPath) nError = Err.Number strErr = Err.Description On 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 we should modify the session name so we can avoid wiping out any ' existing session information. If nError = 0 Then If g_colDuplicatesOfExistingSessions.Exists(strSessionPath) Then g_colDuplicatesOfExistingSessions(strSessionPath) = _ CInt(g_colDuplicatesOfExistingSessions(strSessionPath)) + 1 Else g_colDuplicatesOfExistingSessions.Add strSessionPath, 1 End If strSessionPath = strSessionPath & " (duplicate from mPutty/MTPutty)" End If ' Save the config, then reload it, so the protocol, if changed, is accurate. ' Setting protocol is essential since some variables within a config ' are only available with certain protocols. objConfig.Save g_strImportDestinationFolder & "/" & strSessionPath ' Get a handle to new session config Set objConfig = crt.OpenSessionConfiguration(g_strImportDestinationFolder & "/" & strSessionPath) Select Case LCase(strProtocol) Case "ssh2" objConfig.SetOption "[SSH2] Port", cInt(nPort) objConfig.SetOption "Hostname", strHostname objConfig.SetOption "Username", strUsername objConfig.SetOption "Key Exchange Algorithms", "ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1" objConfig.SetOption "SSH2 Authentications V2", "keyboard-interactive,password,publickey" objConfig.SetOption "Idle NO-OP Check", True objConfig.SetOption "Idle NO-OP Timeout", 59 Case "telnet", "raw" objConfig.SetOption "Port", cInt(nPort) objConfig.SetOption "Hostname", strHostname objConfig.SetOption "Idle NO-OP Check", True objConfig.SetOption "Idle NO-OP Timeout", 59 objConfig.SetOption "Force Char Mode", True Case "raw" objConfig.SetOption "Port", cInt(nPort) objConfig.SetOption "Hostname", strHostname Case "serial" objConfig.SetOption "Com Port", strHostname Case Else If g_strWarnings = "" Then g_strWarnings = g_strWarnings & vbcrlf g_strWarnings = g_strWarnings & "Skipping session for unknown protocol: " & LCase(strProtocol) End Select ' Set default emulation configuration and settings here: objConfig.SetOption "Emulation", "Xterm" objConfig.SetOption "Use Word Delimiter Chars", True objConfig.SetOption "Word Delimiter Chars", ", []""';{}+=()`<>?" objConfig.SetOption "Log Filename V2", "C:\Users\%USERNAME%\Documents\SCRT_Logs\%S_%Y%M%D_%h%m%s_%t.txt" objConfig.SetOption "Custom Log Message Each Line", "[%h:%m:%s.%t] " objConfig.SetOption "Custom Log Message Connect", "######################## Connection Started: %Y/%M/%D, %h:%m:%s.%t ########################" objConfig.SetOption "Custom Log Message Disconnect", "------------------------ Connection closed: %Y/%M/%D, %h:%m:%s.%t ------------------------" objConfig.SetOption "Color Scheme", "Yellow / Black" objConfig.SetOption "ANSI Color", True objConfig.SetOption "Color Scheme Overrides Ansi Color", True objConfig.SetOption "Output Transformer Name", "UTF-8" objConfig.SetOption "User Button Bar", True objConfig.SetOption "User Button Bar Name", "Default" ' Save the config now objConfig.Save nSessionsImported = nSessionsImported + 1 crt.Session.SetStatusText "Imported " & nSessionsImported & " of " & objNodeList.Length On Error Resume Next g_colSessionsCreated.Add strSessionPath, 1 On Error Goto 0 '~ nResult = crt.Dialog.MessageBox(_ '~ "Session #" & g_nSessionsCreated & ":" & vbcrlf & _ '~ "---------------------------------------------------------------------" & vbcrlf & _ '~ "Path: " & strSessionPath & vbcrlf & _ '~ "Name: " & strSessionName & vbcrlf & _ '~ "Hostname: " & strHostname & vbcrlf & _ '~ "Protocol: " & strProtocol & vbcrlf & _ '~ "Port: " & nPort & vbcrlf & _ '~ "Username: " & strUsername & vbcrlf & _ '~ "Warnings: " & g_strWarnings, _ '~ "Importing session #" & g_nSessionsCreated & ", Continue?", _ '~ 4) '~ If nResult <> 6 Then Exit Sub g_nSessionsCreated = g_nSessionsCreated + 1 End If Next Else MsgBox "No connections found in XML file using path: " & vbcrlf & vbcrlf & _ strXPathQuery & _ vbcrlf & vbcrlf & _ "Are you sure the data file is an XML file from mPutty/MTPutty?" End If If g_colSessionsCreated.Count > 0 Then strSummaryMsg = _ "Successfully created " & g_colSessionsCreated.Count & _ " sessions in " & Round(Timer - nImportStartTime, 2) & " seconds" & vbcrlf & _ "You may need to close and re-open the Session Manager in order to see the imported sessions." If g_colDuplicatesOfExistingSessions.Count > 0 Then strSummaryMsg = strSummaryMsg & vbcrlf & vbcrlf & _ "Total of " & g_colDuplicatesOfExistingSessions.Count & _ " sessions already existed in SecureCRT prior to import." End If Else strSummaryMsg = _ "No mPutty/MTPutty session configurations were detected in the .xml file" & _ " you specified: " & strPathToDataFile End If crt.Dialog.MessageBox strSummaryMsg & vbcrlf & g_strWarnings ' Open up the Session Manager automatically. crt.Screen.SendSpecial "MENU_TOGGLE_SESSION_MANAGER" crt.Sleep(200) crt.Screen.SendSpecial "MENU_TOGGLE_SESSION_MANAGER" End Sub '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Function CreateXMLDocObject(byRef objXMLDoc, byRef strInterface) g_strLastError = "" Dim nIndex ' Get the 2nd (0-based) element of the interface number ' MsgBox strInterface nIndex = split(strInterface, ".")(2) On Error Resume Next Err.Clear Set objXMLDoc = CreateObject("Msxml2.DOMDocument." & nIndex & ".0") if Err.Number <> 0 then if nIndex < 2 then g_strLastError = "Error creating xml DOM object(" & strInterface & "): " & Err.Description On Error Goto 0 exit Function else strInterface = "Msxml2.DOMDocument." & nIndex - 1 & ".0" CreateXMLDocObject = CreateXMLDocObject(objXMLDoc, strInterface) On Error Goto 0 exit function end if end if On Error Goto 0 CreateXMLDocObject = True End Function '----------------------------------------------------------------------------- Function GetTimeDateWithMilliseconds() Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem") For Each objItem In colItems strLocalDateTime = objItem.LocalDateTime Exit For Next ' strLocalDateTime has the following pattern: ' 20111013093717.418000-360 [ That is, YYYYMMDDHHMMSS.MILLIS(zone) ] ' Take the left-most 18 digits... strTimeDate = Left(strLocalDateTime, 18) strTimeDate = Left(strTimeDate, 8) & "_" & Mid(strTimeDate, 9) ' ... return the time/date string as value of the function in the following ' format: 20111013_093717.418 GetTimeDateWithMilliseconds = strTimeDate End Function '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Function GetFullPathForNode(objNode) Set objNodeCopy = objNode x = 0 strNodePath = "" Do While Not objNodeCopy Is Nothing ' Get the node's name, but be cautious since ' a node might not have a "name" attribute (like ' the root 'configuration' node) 'stop On Error Resume Next strCurName = objNodeCopy.SelectNodes("DisplayName")(0).Text nError = Err.Number strErr = Err.Description On Error Goto 0 ' If there's an error, we probably just reached ' the node that doesn't have a name, and we're done If nError <> 0 Then Exit Do If strCurName <> "" Then ' Otherwise, start building upon the path strNodePath = "\" & strCurName & strNodePath End If ' Now, replace the node copy with its parent, and then ' loop up to the top again Set objNodeCopy = objNodeCopy.parentNode Loop GetFullPathForNode = Replace(strNodePath, "\", "/") End Function