コード例 #1
0
        public long ReadInt64(IRemoteProcess remoteProcess, MemoryMap memoryMap)
        {
            Contract.Requires <ArgumentNullException>(remoteProcess != null);
            Contract.Requires <ArgumentNullException>(memoryMap != null);

            throw new NotImplementedException();
        }
コード例 #2
0
        public byte[] Read(IRemoteProcess remoteProcess, MemoryMap memoryMap, int size)
        {
            Contract.Requires <ArgumentNullException>(remoteProcess != null);
            Contract.Requires <ArgumentNullException>(memoryMap != null);

            throw new NotImplementedException();
        }
コード例 #3
0
        public short ReadInt16(IRemoteProcess remoteProcess, MemoryMap memoryMap)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);
            Contract.Requires<ArgumentNullException>(memoryMap != null);

            throw new NotImplementedException();
        }
コード例 #4
0
        public byte[] Read(IRemoteProcess remoteProcess, MemoryMap memoryMap, int size)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);
            Contract.Requires<ArgumentNullException>(memoryMap != null);

            throw new NotImplementedException();
        }
コード例 #5
0
        public string ReadString(IRemoteProcess remoteProcess, MemoryMap memoryMap, int?length = null)
        {
            Contract.Requires <ArgumentNullException>(remoteProcess != null);
            Contract.Requires <ArgumentNullException>(memoryMap != null);
            Contract.Requires <ArgumentOutOfRangeException>(length == null || length >= 0);

            throw new NotImplementedException();
        }
コード例 #6
0
        public IProcessModules Create(IRemoteProcess remoteProcess)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);

            return new ProcessModulesViewModel(
                remoteProcess,
                this.processDetailsVMFactory.Create(),
                this.moduleFactories.Select(o => o.Create(remoteProcess)));
        }
コード例 #7
0
        public IProcessModules Create(IRemoteProcess remoteProcess)
        {
            Contract.Requires <ArgumentNullException>(remoteProcess != null);

            return(new ProcessModulesViewModel(
                       remoteProcess,
                       this.processDetailsVMFactory.Create(),
                       this.moduleFactories.Select(o => o.Create(remoteProcess))));
        }
コード例 #8
0
        /// <summary>
        /// Get Oracle Version
        /// </summary>
        /// <param name="OracleHome">Oracle Home</param>
        /// <param name="version">Version</param>
        /// <returns></returns>
        private ResultCodes GetOracleServerEdition(string OracleHome, out string edition)
        {
            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                  0,
                                  "Task Id {0}: Attempting to retrieve config file from OracleHome: {1}.",
                                  m_taskId,
                                  OracleHome);
            StringBuilder fileContent        = new StringBuilder();
            string        contentXMLFilePath = string.Empty;

            edition = @"";
            if (OracleHome.EndsWith(@"\"))
            {
                contentXMLFilePath = OracleHome + @"inventory\ContentsXML\comps.xml";
            }
            else
            {
                contentXMLFilePath = OracleHome + @"\inventory\ContentsXML\comps.xml";
            }

            if (Lib.ValidateFile(m_taskId, contentXMLFilePath, m_cimvScope))
            {
                using (IRemoteProcess rp =
                           RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, contentXMLFilePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) {
                    //
                    // Launch the remote process.
                    // This method will block until the entire remote process operation completes.
                    resultCode = rp.Launch();
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                          m_taskId,
                                          resultCode.ToString());
                    fileContent.Append(rp.Stdout);
                }
                // Parse config file content
                edition = parseContentXMLFile(fileContent.ToString());
            }
            else
            {
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Oracle Server Config file: {1} does not exist.",
                                      m_taskId,
                                      contentXMLFilePath);
                // Some Oracle Administrator might have corrupted config file or registry settings.
                // In order not to confuse scan result with actual error, return RC_SUCCESS instead.
                resultCode = ResultCodes.RC_SUCCESS;
            }
            return(resultCode);
        }
コード例 #9
0
 private static async Task <IRemoteProcessPipResult> GetCompletionAsync(IRemoteProcess remoteProcess)
 {
     try
     {
         IRemoteProcessResult anyBuildResult = await remoteProcess.Completion;
         return(AnyBuildRemoteProcessPipResult.FromAnyBuildResult(anyBuildResult));
     }
     catch (Exception e)
     {
         return(new ErrorRemoteProcessPipResult(e.ToString()));
     }
 }
コード例 #10
0
        public void AttachToProcess(IRemoteProcess remoteProcess)
        {
            Contract.Requires <ArgumentNullException>(remoteProcess != null);

            if (remoteProcess.IsAttached)
            {
                return;
            }

            this.remoteProcessCommandService.AttachClientToRemoteProcess(
                new AttachClientToRemoteProcessCommand(remoteProcess.Id));
            this.TryClose();
        }
コード例 #11
0
        private ResultCodes DeleteFile(ManagementScope cimvScope, string fileName)
        {
            ResultCodes resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;

            using (IRemoteProcess rp =
                       RemoteProcess.NewRemoteProcess(m_taskId, cimvScope,
                                                      @"cmd /Q /C del """ + fileName + '"', null,
                                                      StdioRedirection.STDOUT, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher))
            {
                resultCode = rp.Launch();
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Deletion of file {1} completed with result code {2}.",
                                      m_taskId,
                                      fileName,
                                      resultCode.ToString());
            }
            return(resultCode);
        }
コード例 #12
0
        private IntPtr GetAddress(IRemoteProcess remoteProcess, MemoryMap memoryMap)
        {
            Contract.Requires <ArgumentNullException>(remoteProcess != null);
            Contract.Requires <ArgumentNullException>(memoryMap != null);
            var module =
                remoteProcess.Modules.FirstOrDefault(
                    m => string.Equals(m.Name, memoryMap.DllName, StringComparison.OrdinalIgnoreCase));

            if (module == null)
            {
                return(IntPtr.Zero);
            }

            return(memoryMap.Offsets.Skip(1)
                   .Aggregate(
                       module.BaseAddress + memoryMap.Offsets.First(),
                       (current, offset) =>
                       (IntPtr)(this.readProcessMemory.ReadInt32(remoteProcess.Handle, current) + offset)));
        }
コード例 #13
0
        public ProcessModulesViewModel(IRemoteProcess remoteProcess, IItem processDetails, IEnumerable<IModule> modules)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);
            Contract.Requires<ArgumentNullException>(processDetails != null);
            Contract.Requires<ArgumentNullException>(modules != null);

            this.remoteProcess = remoteProcess;
            this.processDetails = processDetails;
            this.iconSource = null;
            this.modules = new BindableCollection<IModule>(modules);

            var inpc = remoteProcess as INotifyPropertyChanged;
            if (inpc == null)
            {
                return;
            }

            PropertyChangedEventManager.AddHandler(
                inpc, (sender, args) => this.NotifyOfPropertyChange(() => this.Name), string.Empty);
        }
コード例 #14
0
        public ProcessModulesViewModel(IRemoteProcess remoteProcess, IItem processDetails, IEnumerable <IModule> modules)
        {
            Contract.Requires <ArgumentNullException>(remoteProcess != null);
            Contract.Requires <ArgumentNullException>(processDetails != null);
            Contract.Requires <ArgumentNullException>(modules != null);

            this.remoteProcess  = remoteProcess;
            this.processDetails = processDetails;
            this.iconSource     = null;
            this.modules        = new BindableCollection <IModule>(modules);

            var inpc = remoteProcess as INotifyPropertyChanged;

            if (inpc == null)
            {
                return;
            }

            PropertyChangedEventManager.AddHandler(
                inpc, (sender, args) => this.NotifyOfPropertyChange(() => this.Name), string.Empty);
        }
コード例 #15
0
        /// <summary>
        /// Collect usage statistics from agent.
        /// </summary>
        /// <param name="cimvScope">WMI connection.</param>
        /// <returns>Operation result code.</returns>
        private ResultCodes GetUsageStatistics(ManagementScope cimvScope)
        {
            Lib.Logger.TraceEvent(TraceEventType.Error,
                                  0,
                                  "Task Id {0}: Attempting to get usage statistics",
                                  m_taskId);
            ResultCodes resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;

            if (String.IsNullOrEmpty(m_serviceDataPath))
            {
                return(resultCode);
            }

            String        resultPath  = m_serviceDataPath + "result.cvs";
            StringBuilder fileContent = new StringBuilder();

            if (Lib.ValidateFile(m_taskId, resultPath, cimvScope))
            {
                using (IRemoteProcess rp =
                           RemoteProcess.GetRemoteFile(m_taskId, cimvScope, resultPath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher))
                {
                    // Launch the remote process.
                    // This method will block until the entire remote process operation completes.
                    resultCode = rp.Launch();
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                          m_taskId,
                                          resultCode.ToString());
                    fileContent.Append(rp.Stdout);
                }
                string[] lines = fileContent.ToString().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                m_resultFileContents = String.Join(BdnaDelimiters.DELIMITER_TAG, lines);

                resultCode = ResultCodes.RC_SUCCESS;
            }

            return(resultCode);
        }
コード例 #16
0
        public async Task <IRemoteProcessPip> CreateAndStartAsync(RemoteProcessInfo processInfo, CancellationToken cancellationToken)
        {
            Contract.Requires(IsInitialized);

            IRemoteProcessFactory factory = (await m_initResultLazy.GetValueAsync()).RemoteProcessFactory;
            var commandInfo = new RemoteCommandExecutionInfo(
                processInfo.Executable,
                processInfo.Args,
                processInfo.WorkingDirectory,
                useLocalEnvironment: false,
                processInfo.Environments.ToList());

            try
            {
                IRemoteProcess remoteCommand = await factory.CreateAndStartAsync(commandInfo, cancellationToken);

                return(new AnyBuildRemoteProcess(remoteCommand));
            }
            catch (Exception e)
            {
                return(new ErrorRemoteProcessPip(e.ToString()));
            }
        }
コード例 #17
0
        private ResultCodes CopyFiles(ManagementScope cimvScope)
        {
            ResultCodes resultCode;
            string      localPath = Directory.GetCurrentDirectory() + s_localServicePath;

            using (IRemoteProcess rp =
                       RemoteProcess.SendFile(m_taskId, cimvScope, localPath + s_executableName, m_pathName + s_executableName,
                                              m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher))
            {
                resultCode = rp.Launch();
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Sending of file {1} completed with result code {2}.",
                                      m_taskId,
                                      s_executableName,
                                      resultCode.ToString());
            }
            if (resultCode != ResultCodes.RC_SUCCESS)
            {
                return(resultCode);
            }

            using (IRemoteProcess rp =
                       RemoteProcess.SendFile(m_taskId, cimvScope, localPath + "ListPrint.xml", m_logPathName + "ListPrint.xml",
                                              m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher))
            {
                resultCode = rp.Launch();
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Sending of file {1} completed with result code {2}.",
                                      m_taskId,
                                      "ListPrint.xml",
                                      resultCode.ToString());
            }
            return(resultCode);
        }
コード例 #18
0
        /// <summary>
        /// Spawn a remote process to execute the L3 validation
        /// batch file and process the results.
        /// </summary>
        ///
        /// <param name="scope">WMI connection to target host.</param>
        /// <param name="batchFile">Batch file contents to execute.</param>
        /// <param name="schemaName">Schema name to validate.</param>
        /// <param name="scriptParameters">Script parameters to use (contains temporary directory
        ///     parameter).</param>
        /// <param name="tftpDispatcher">TFTP dispatcher singleton.</param>
        ///
        /// <returns>Operation result code.</returns>
        private ResultCodes ExecuteRemoteProcess(
            ManagementScope scope,
            string batchFile,
            string schemaName,
            IDictionary <string, object> scriptParameters,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            ResultCodes resultCode = ResultCodes.RC_SUCCESS;
            string      stdout     = String.Empty;

            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                  0,
                                  "Task Id {0}: Attempt to establish L3 connection using {1}.",
                                  m_taskId,
                                  schemaName);

            using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile(m_taskId, scope, batchFile, scriptParameters, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) {
                Stopwatch sw = Stopwatch.StartNew();
                resultCode = rp.Launch();
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Remote process operation completed with result code {1}.  Elapsed time {2}.",
                                      m_taskId,
                                      resultCode.ToString(),
                                      sw.Elapsed.ToString());
                stdout = rp.Stdout.ToString();

                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    if (null != stdout && 0 < stdout.Length)
                    {
                        if (stdout.Contains("ORA-01017"))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Oracle L3 credential invalid.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}",
                                                  m_taskId,
                                                  stdout);
                            resultCode = ResultCodes.RC_HOST_CONNECT_FAILED;
                        }
                        else if (stdout.Contains("ERROR-"))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Batch file execution exception.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}",
                                                  m_taskId,
                                                  stdout);
                            resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                        }
                        else if (!stdout.Contains(@"BDNA"))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: SQLPLUS exception, no proper data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}",
                                                  m_taskId,
                                                  stdout);
                            resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                        }
                        else if (!stdout.Contains(@"Execution completed"))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Exception with batch file return data.\nData returned is shorter than expected, possibly due to transfer failure.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                                  m_taskId);
                            resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                        }
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: No data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                              m_taskId);
                        resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                    }
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Remote execution error.\n{1}",
                                          m_taskId,
                                          stdout);
                }
            }

            if (ResultCodes.RC_SUCCESS == resultCode)
            {
                //
                // If we didn't get the output expected from execution
                // of the batch file.  Force the result code to some
                // error value so that we try the next credential set.
                if (0 >= stdout.Length || !s_bdnaRegex.IsMatch(stdout))
                {
                    resultCode = ResultCodes.RC_LOGIN_FAILED; // @todo Did login really fail?  Perhaps this s/b processing exception
                }
            }

            return(resultCode);
        }
コード例 #19
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            string        taskIdString             = taskId.ToString();
            StringBuilder dataRow                  = new StringBuilder();
            StringBuilder resultBuffer             = new StringBuilder();
            IDictionary <string, string> resultDic = new Dictionary <string, string>();
            Stopwatch   executionTimer             = Stopwatch.StartNew();
            ResultCodes resultCode                 = ResultCodes.RC_SUCCESS;
            string      strOracleHome              = null;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsOracleListenerNamesScript.",
                                  taskIdString);

            try {
                // Check ManagementScope CIMV
                ManagementScope cimvScope = null;
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsOracleListenerNamesScript is null.",
                                          taskIdString);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          taskIdString);
                }
                else
                {
                    cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed.",
                                              taskIdString);
                    }
                }

                //Check OracleHome attributes
                if (!scriptParameters.ContainsKey("OracleHome"))
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing OracleHome parameter",
                                          taskIdString);
                }
                else
                {
                    strOracleHome = scriptParameters["OracleHome"].Trim();
                    if (strOracleHome.EndsWith(@"\"))
                    {
                        strOracleHome = strOracleHome.Substring(0, strOracleHome.Length - 1);
                    }
                }

                // Check Remote Process Temp Directory
                if (!connection.ContainsKey(@"TemporaryDirectory"))
                {
                    connection[@"TemporaryDirectory"] = @"%TMP%";
                }
                else
                {
                    if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                    {
                        if (!Lib.ValidateDirectory(taskIdString, connection[@"TemporaryDirectory"].ToString(), cimvScope))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} is not valid.",
                                                  taskIdString,
                                                  connection[@"TemporaryDirectory"].ToString());
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} has been validated.",
                                                  taskIdString,
                                                  connection[@"TemporaryDirectory"].ToString());
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    string strLISTENERORA = strOracleHome.Trim() + @"\NETWORK\ADMIN\listener.ora";
                    if (!Lib.ValidateFile(taskIdString, strLISTENERORA, cimvScope))
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Oracle Home does not contain a server installation.  listener.ora is missing.\nSkipping the rest of the validation.",
                                              taskIdString);
                    }
                    else
                    {
                        string        commandLine = @"cmd /q /e:off /C " + @"type " + strOracleHome.Trim() + @"\NETWORK\ADMIN\listener.ora";
                        StringBuilder stdoutData  = new StringBuilder();
                        using (IRemoteProcess rp = RemoteProcess.NewRemoteProcess(
                                   taskIdString,                    // Task Id to log against.
                                   cimvScope,                       // assuming Remote process uses cimv2 management scope
                                   commandLine,                     // script supplied command line.
                                   null,                            // Optional working directory
                                   StdioRedirection.STDOUT,         // Flags for what stdio files you want
                                   null,                            // Data to pass for stdin.
                                   connection,                      // Script parameters passed to all collection script by WinCs
                                   tftpPath,
                                   tftpPath_login,
                                   tftpPath_password,
                                   tftpDispatcher)) {
                            //This method will block until the entire remote process operation completes.
                            resultCode = rp.Launch();
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Remote process operation completed with result code {1}.",
                                                  taskIdString,
                                                  resultCode.ToString());

                            if (resultCode == ResultCodes.RC_SUCCESS)
                            {
                                stdoutData.Append(rp.Stdout.ToString());
                                if (rp.Stdout == null || rp.Stdout.Length <= 0)
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: No data returned from remote process execution.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                                          taskIdString);
                                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                                }
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Remote process execution failed.  Result code {1}.\n{2}",
                                                      taskIdString,
                                                      resultCode.ToString(),
                                                      rp.Stdout.ToString());
                            }
                        }

                        if (stdoutData != null && stdoutData.Length > 0)
                        {
                            StringBuilder sb          = new StringBuilder();
                            string[]      arrOutput   = stdoutData.ToString().Split("\r\n".ToCharArray());
                            string        strListener = null;
                            bool          matched     = false;
                            foreach (string line in arrOutput)
                            {
                                if (s_listenerName.IsMatch(line))
                                {
                                    if (!s_listenerNoName.IsMatch(line))
                                    {
                                        Match m = s_listenerName.Match(line);
                                        strListener = m.Groups[1].Value;
                                        sb.AppendLine(strListener);
                                        resultDic[strListener] = strListener;
                                    }
                                }
                            }
                            if (0 < sb.Length)
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: Listener matched:\n{1}",
                                                      taskIdString,
                                                      sb.ToString());
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: No Listener services matched.",
                                                      taskIdString);
                            }
                            foreach (KeyValuePair <string, string> kvp in resultDic)
                            {
                                if (resultBuffer.Length > 0)
                                {
                                    resultBuffer.Append(BdnaDelimiters.DELIMITER_TAG);
                                }
                                resultBuffer.Append(kvp.Value);
                            }

                            if (!attributes.ContainsKey("listenerNames"))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Attribute \"listenerNames\" missing from attributeSet.",
                                                      taskIdString);
                            }
                            else if (0 == resultBuffer.Length)
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: Script completed sucessfully with no data to return.",
                                                      taskIdString);
                            }
                            else
                            {
                                dataRow.Append(elementId).Append(',')
                                .Append(attributes["listenerNames"]).Append(',')
                                .Append(scriptParameters["CollectorId"]).Append(',')
                                .Append(taskId).Append(',')
                                .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',')
                                .Append("listenerNames").Append(',')
                                .Append(BdnaDelimiters.BEGIN_TAG).Append(resultBuffer.ToString()).Append(BdnaDelimiters.END_TAG);
                            }
                        }
                    }
                }
            }
            catch (Exception ex) {
                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsOracleListenerNamesScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          taskIdString,
                                          executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsOracleListenerNamesScript.  Elapsed time {1}.\n{2}",
                                          taskIdString,
                                          executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsOracleListenerNamesScript.  Elapsed time {1}.  Result code {2}.",
                                  taskIdString,
                                  executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString()));
        }
コード例 #20
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            m_executionTimer    = Stopwatch.StartNew();
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASProfileFootprintScript.",
                                  m_taskId);
            try {
                ManagementScope cimvScope    = null;
                ManagementScope defaultScope = null;

                // Check ManagementScope CIMV
                if (null == connection)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsWASProfileFootprintScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey(@"cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey(@"default"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for Default namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope    = connection[@"cimv2"] as ManagementScope;
                    defaultScope = connection[@"default"] as ManagementScope;

                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed.",
                                              m_taskId);
                    }
                    else if (!defaultScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to Default namespace failed.",
                                              m_taskId);
                    }
                }

                //Check WAS Installation Path attribute
                if (resultCode.Equals(ResultCodes.RC_SUCCESS))
                {
                    if (scriptParameters.ContainsKey("profilePath"))
                    {
                        m_profileHome = scriptParameters[@"profilePath"];
                    }
                    else
                    {
                        resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Missing parameter WAS Profile Path parameter.",
                                              m_taskId);
                    }
                }

                // Check Remote Process Temp Directory
                if (resultCode.Equals(ResultCodes.RC_SUCCESS))
                {
                    if (!connection.ContainsKey(@"TemporaryDirectory"))
                    {
                        connection[@"TemporaryDirectory"] = @"%TMP%";
                    }
                    else
                    {
                        if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                        {
                            if (!Lib.ValidateDirectory(m_taskId, connection[@"TemporaryDirectory"].ToString(), cimvScope))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Temporary directory {1} is not valid.",
                                                      m_taskId,
                                                      connection[@"TemporaryDirectory"].ToString());
                                resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: User specified temp directory has been validated.",
                                                      m_taskId);
                            }
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Attempting to retrieve file {1}.",
                                          m_taskId,
                                          m_profileHome);
                    StringBuilder fileContent = new StringBuilder();
                    StringBuilder setupCmd    = new StringBuilder();
                    setupCmd.Append((string)m_profileHome).Append(@"\bin\setupCmdLine.bat");

                    if (Lib.ValidateFile(m_taskId, setupCmd.ToString(), cimvScope))
                    {
                        using (IRemoteProcess rp =
                                   RemoteProcess.GetRemoteFile(m_taskId, cimvScope, setupCmd.ToString(), connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher))
                        {
                            //
                            // Launch the remote process.
                            // This method will block until the entire remote process operation completes.
                            resultCode = rp.Launch();
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                                  m_taskId,
                                                  resultCode.ToString());
                            fileContent.Append(rp.Stdout);
                        }
                        // Parse file content
                        resultCode = parseCmdlineFile(fileContent.ToString());
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: WAS setupCmdline file: {1} does not exist.",
                                              m_taskId,
                                              m_profileHome);
                        resultCode = ResultCodes.RC_SUCCESS;
                    }
                }
            } catch (Exception ex) {
                Lib.LogException(m_taskId,
                                 m_executionTimer,
                                 "Unhandled exception in WindowsWASProfileFootprintScript",
                                 ex);
                resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
            }

            CollectionScriptResults result = new CollectionScriptResults(resultCode,
                                                                         0,
                                                                         null,
                                                                         null,
                                                                         null,
                                                                         false,
                                                                         m_dataRow.ToString());

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASProfileFootprintScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }
コード例 #21
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch     executionTimer = Stopwatch.StartNew();
            string        taskIdString = taskId.ToString();
            StringBuilder dataRow = new StringBuilder();
            string        strListenerName = null, strOracleHome = null;
            ResultCodes   resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsOracleListenerStaticScript.",
                                  taskIdString);

            try {
                // Check ManagementScope CIMV
                ManagementScope cimvScope = null;
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsOracleListenerStaticScript is null.",
                                          taskIdString);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          taskIdString);
                }
                else
                {
                    cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed.",
                                              taskIdString);
                    }
                }

                //Check OracleHome attributes
                if (!scriptParameters.ContainsKey("OracleHome"))
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing OracleHome script parameter.",
                                          taskIdString);
                }
                else
                {
                    strOracleHome = scriptParameters["OracleHome"].Trim();
                    if (strOracleHome.EndsWith(@"\"))
                    {
                        strOracleHome = strOracleHome.Substring(0, strOracleHome.Length - 1);
                    }
                }

                //Check Listener Name attribute
                if (!scriptParameters.ContainsKey("name"))
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing Listener Name script parameter.",
                                          taskIdString);
                }
                else
                {
                    strListenerName = scriptParameters["name"];
                }

                // Check Remote Process Temp Directory
                if (!connection.ContainsKey(@"TemporaryDirectory"))
                {
                    connection[@"TemporaryDirectory"] = @"%TMP%";
                }
                else
                {
                    if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                    {
                        if (!Lib.ValidateDirectory(taskIdString, connection[@"TemporaryDirectory"].ToString(), cimvScope))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} is not valid.",
                                                  taskIdString,
                                                  connection[@"TemporaryDirectory"].ToString());
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} has been validated.",
                                                  taskIdString,
                                                  connection[@"TemporaryDirectory"].ToString());
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    string        commandLine = @"cmd /q /e:off /C " + strOracleHome.Trim() + @"\BIN\LSNRCTL.EXE status " + strListenerName;
                    StringBuilder stdoutData  = new StringBuilder();
                    using (IRemoteProcess rp =
                               RemoteProcess.NewRemoteProcess(taskIdString, cimvScope, commandLine,
                                                              null, StdioRedirection.STDOUT, null, connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) {
                        //This method will block until the entire remote process operation completes.
                        resultCode = rp.Launch();
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: Remote process operation completed with result code {1}.",
                                              taskIdString,
                                              resultCode.ToString());

                        if (resultCode == ResultCodes.RC_SUCCESS)
                        {
                            stdoutData.Append(rp.Stdout);
                            if (rp.Stdout != null && rp.Stdout.Length > 0)
                            {
                                if (!rp.Stdout.ToString().ToUpper().Contains(@"PARAMETER FILE"))
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: SQLPLUS exception, no proper data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}",
                                                          taskIdString,
                                                          rp.Stdout.ToString());
                                    //resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                                }
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: No data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                                      taskIdString);
                                resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                            }
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Remote execution error.\n{1}",
                                                  taskIdString,
                                                  rp.Stdout.ToString());
                        }
                    }

                    if (resultCode == ResultCodes.RC_SUCCESS && stdoutData.Length > 0)
                    {
                        string[] arrOutputLine = stdoutData.ToString().Split("\r\n".ToCharArray());
                        string   strListenerAddress = "", strParameterFile = "", strInstances = "", strPort = "";

                        for (int i = 0; i < arrOutputLine.Length; i++)
                        {
                            string output = arrOutputLine[i];

                            if (s_connectingRegex_en.IsMatch(output))
                            {
                                MatchCollection mtc = s_connectingRegex_en.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strListenerAddress = "" + m.Groups["addr"].Value;
                                }
                            }
                            else if (s_connectingRegex_fr.IsMatch(output))
                            {
                                MatchCollection mtc = s_connectingRegex_fr.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strListenerAddress = "" + m.Groups["addr"].Value;
                                }
                            }
                            else if (s_connectingRegex_de.IsMatch(output))
                            {
                                MatchCollection mtc = s_connectingRegex_de.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strListenerAddress = "" + m.Groups["addr"].Value;
                                }
                            }
                            else if (s_connectingRegex_it.IsMatch(output))
                            {
                                MatchCollection mtc = s_connectingRegex_it.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strListenerAddress = "" + m.Groups["addr"].Value;
                                }
                            }

                            if (s_listenerRegex_en.IsMatch(output))
                            {
                                MatchCollection mtc = s_listenerRegex_en.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strParameterFile += "" + m.Groups["parameterFile"].Value;
                                }
                            }
                            else if (s_listenerRegex_fr.IsMatch(output))
                            {
                                MatchCollection mtc = s_listenerRegex_fr.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strParameterFile += "" + m.Groups["parameterFile"].Value;
                                }
                            }
                            else if (s_listenerRegex_de.IsMatch(output))
                            {
                                MatchCollection mtc = s_listenerRegex_de.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strParameterFile += "" + m.Groups["parameterFile"].Value;
                                }
                            }
                            else if (s_listenerRegex_it.IsMatch(output))
                            {
                                MatchCollection mtc = s_listenerRegex_it.Matches(output);
                                foreach (Match m in mtc)
                                {
                                    strParameterFile += "" + m.Groups["parameterFile"].Value;
                                }
                            }

                            if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_en.IsMatch(output))
                            {
                                int j = 0;
                                for (j = i; j < arrOutputLine.Length; j++)
                                {
                                    string ucaseOutput = arrOutputLine[j].ToUpper();

                                    if (!s_keyExtProcRegex_en.IsMatch(ucaseOutput))
                                    {
                                        if (s_descriptionRegex_en.IsMatch(ucaseOutput))
                                        {
                                            MatchCollection mtc = s_descriptionRegex_en.Matches(ucaseOutput);
                                            foreach (Match m in mtc)
                                            {
                                                strListenerAddress = m.Groups["addr"].Value;
                                            }
                                            break;
                                        }
                                    }
                                    i = j;
                                }
                            }
                            else if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_fr.IsMatch(output))
                            {
                                int j = 0;
                                for (j = i; j < arrOutputLine.Length; j++)
                                {
                                    string ucaseOutput = arrOutputLine[j].ToUpper();

                                    if (!s_keyExtProcRegex_fr.IsMatch(ucaseOutput))
                                    {
                                        if (s_descriptionRegex_fr.IsMatch(ucaseOutput))
                                        {
                                            MatchCollection mtc = s_descriptionRegex_fr.Matches(ucaseOutput);
                                            foreach (Match m in mtc)
                                            {
                                                strListenerAddress = m.Groups["addr"].Value;
                                            }
                                            break;
                                        }
                                    }
                                    i = j;
                                }
                            }
                            else if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_de.IsMatch(output))
                            {
                                int j = 0;
                                for (j = i; j < arrOutputLine.Length; j++)
                                {
                                    string ucaseOutput = arrOutputLine[j].ToUpper();

                                    if (!s_keyExtProcRegex_de.IsMatch(ucaseOutput))
                                    {
                                        if (s_descriptionRegex_de.IsMatch(ucaseOutput))
                                        {
                                            MatchCollection mtc = s_descriptionRegex_de.Matches(ucaseOutput);
                                            foreach (Match m in mtc)
                                            {
                                                strListenerAddress = m.Groups["addr"].Value;
                                            }
                                            break;
                                        }
                                    }
                                    i = j;
                                }
                            }
                            else if (!String.IsNullOrEmpty(strListenerAddress) && s_listeningRegex_it.IsMatch(output))
                            {
                                int j = 0;
                                for (j = i; j < arrOutputLine.Length; j++)
                                {
                                    string ucaseOutput = arrOutputLine[j].ToUpper();

                                    if (!s_keyExtProcRegex_it.IsMatch(ucaseOutput))
                                    {
                                        if (s_descriptionRegex_it.IsMatch(ucaseOutput))
                                        {
                                            MatchCollection mtc = s_descriptionRegex_it.Matches(ucaseOutput);
                                            foreach (Match m in mtc)
                                            {
                                                strListenerAddress = m.Groups["addr"].Value;
                                            }
                                            break;
                                        }
                                    }
                                    i = j;
                                }
                            }

                            if (s_portRegex_en.IsMatch(strListenerAddress))
                            {
                                Match m0 = s_portRegex_en.Match(strListenerAddress);
                                strPort = m0.Groups[1].Value;
                            }
                            else if (s_portRegex_fr.IsMatch(strListenerAddress))
                            {
                                Match m0 = s_portRegex_fr.Match(strListenerAddress);
                                strPort = m0.Groups[1].Value;
                            }
                            else if (s_portRegex_de.IsMatch(strListenerAddress))
                            {
                                Match m0 = s_portRegex_de.Match(strListenerAddress);
                                strPort = m0.Groups[1].Value;
                            }
                            else if (s_portRegex_it.IsMatch(strListenerAddress))
                            {
                                Match m0 = s_portRegex_it.Match(strListenerAddress);
                                strPort = m0.Groups[1].Value;
                            }

                            if (s_instancesRegex_en.IsMatch(output))
                            {
                                Match  m0          = s_instancesRegex_en.Match(output);
                                string strinstance = m0.Groups[1].Value;
                                if (!String.IsNullOrEmpty(strInstances))
                                {
                                    if (!strInstances.Contains(strinstance))
                                    {
                                        strInstances += " " + strinstance;
                                    }
                                }
                                else
                                {
                                    strInstances = strinstance;
                                }
                            }
                        }

                        dataRow.Append(elementId).Append(',')
                        .Append(attributes["listenerAddress"]).Append(',')
                        .Append(scriptParameters["CollectorId"]).Append(',')
                        .Append(taskId).Append(',')
                        .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',')
                        .Append("listenerAddress").Append(',')
                        .Append(BdnaDelimiters.BEGIN_TAG).Append(strListenerAddress).Append(BdnaDelimiters.END_TAG);

                        dataRow.Append(elementId).Append(',')
                        .Append(attributes["parameterFilePath"]).Append(',')
                        .Append(scriptParameters["CollectorId"]).Append(',')
                        .Append(taskId).Append(',')
                        .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',')
                        .Append("parameterFilePath").Append(',')
                        .Append(BdnaDelimiters.BEGIN_TAG).Append(strParameterFile).Append(BdnaDelimiters.END_TAG);

                        dataRow.Append(elementId).Append(',')
                        .Append(attributes["port"]).Append(',')
                        .Append(scriptParameters["CollectorId"]).Append(',')
                        .Append(taskId).Append(',')
                        .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',')
                        .Append("port").Append(',')
                        .Append(BdnaDelimiters.BEGIN_TAG).Append(strPort).Append(BdnaDelimiters.END_TAG);

                        dataRow.Append(elementId).Append(',')
                        .Append(attributes["associateInstances"]).Append(',')
                        .Append(scriptParameters["CollectorId"]).Append(',')
                        .Append(taskId).Append(',')
                        .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',')
                        .Append("associateInstances").Append(',')
                        .Append(BdnaDelimiters.BEGIN_TAG).Append(strInstances).Append(BdnaDelimiters.END_TAG);
                    }
                }
            } catch (Exception ex) {
                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsOracleListenerStaticScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          taskIdString,
                                          executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsOracleListenerStaticScript.  Elapsed time {1}.\n{2}",
                                          taskIdString,
                                          executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsOracleListenerStaticScript.  Elapsed time {1}.  Result code {2}.",
                                  taskIdString,
                                  executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString()));
        }
コード例 #22
0
 public void Add(IRemoteProcess entity)
 {
     this.processRepository.Add(entity);
 }
コード例 #23
0
        public string ReadString(IRemoteProcess remoteProcess, MemoryMap memoryMap, int? length = null)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);
            Contract.Requires<ArgumentNullException>(memoryMap != null);
            Contract.Requires<ArgumentOutOfRangeException>(length == null || length >= 0);

            throw new NotImplementedException();
        }
コード例 #24
0
        private IntPtr GetAddress(IRemoteProcess remoteProcess, MemoryMap memoryMap)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);
            Contract.Requires<ArgumentNullException>(memoryMap != null);
            var module =
                remoteProcess.Modules.FirstOrDefault(
                    m => string.Equals(m.Name, memoryMap.DllName, StringComparison.OrdinalIgnoreCase));
            if (module == null)
            {
                return IntPtr.Zero;
            }

            return memoryMap.Offsets.Skip(1)
                            .Aggregate(
                                module.BaseAddress + memoryMap.Offsets.First(), 
                                (current, offset) =>
                                (IntPtr)(this.readProcessMemory.ReadInt32(remoteProcess.Handle, current) + offset));
        }
コード例 #25
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp, long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters, IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher)
        {
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;
            m_tftpDispatcher    = tftpDispatcher;
            m_tftpPath          = tftpPath;
            m_tftpPath_login    = tftpPath_login;
            m_tftpPath_password = tftpPath_password;
            m_connection        = connection;
            m_executionTimer    = Stopwatch.StartNew();

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WinFileContentScript.",
                                  m_taskId);
            try {
                // Check ManagementScope CIMV
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to VMWareVMXConfigFileContentScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    m_cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!m_cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed",
                                              m_taskId);
                    }
                }



                string filePath = string.Empty;

                foreach (KeyValuePair <string, string> kvp in scriptParameters)
                {
                    string key = kvp.Key;
                    if (key.Contains(":"))
                    {
                        int i = key.IndexOf(':');
                        key = key.Substring(i + 1);
                    }

                    if (key == @"filePath")
                    {
                        filePath = kvp.Value;
                    }
                }

                if (string.IsNullOrEmpty(filePath))
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task id {0}: Missing file path parameter.",
                                          m_taskId);
                }


                // Check Remote Process Temp Directory
                if (!m_connection.ContainsKey(@"TemporaryDirectory"))
                {
                    m_connection[@"TemporaryDirectory"] = @"%TMP%";
                }
                else
                {
                    if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                    {
                        if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} is not valid.",
                                                  m_taskId,
                                                  m_connection[@"TemporaryDirectory"].ToString());
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: User specified temp directory has been validated.",
                                                  m_taskId);
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Attempting to retrieve file {1}.",
                                          m_taskId,
                                          m_FilePath);
                    StringBuilder fileContent = new StringBuilder();

                    if (Lib.ValidateFile(m_taskId, filePath, m_cimvScope))
                    {
                        using (IRemoteProcess rp =
                                   RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, filePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) {
                            //
                            // Launch the remote process.
                            // This method will block until the entire remote process operation completes.
                            resultCode = rp.Launch();
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                                  m_taskId,
                                                  resultCode.ToString());
                            fileContent.Append(rp.Stdout);
                        }
                        this.BuildDataRow(@"fileContent", fileContent.ToString());
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: file {1} does not exist.",
                                              m_taskId,
                                              filePath);
                        //resultCode = ResultCodes.RC_SUCCESS;
                    }
                }
            } catch (ManagementException me) {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Insufficient privilege to read file.\nMessage: {1}",
                                      m_taskId,
                                      me.Message);
                if (me.InnerException != null)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Inner Exception Message: {1}.",
                                          m_taskId,
                                          me.InnerException.Message);
                }
                resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE;
            } catch (COMException ce) {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Not enough privilege to access run WMI query.\nMessage: {1}.",
                                      m_taskId,
                                      ce.Message);
                if (ce.InnerException != null)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Inner Exception Message: {1}.",
                                          m_taskId,
                                          ce.InnerException.Message);
                }
                resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_RUN_WMI_QUERY;
            } catch (Exception ex) {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Unhandled exception in WinFileContentScript.  Elapsed time {1}.\n{2}",
                                      m_taskId,
                                      m_executionTimer.Elapsed.ToString(),
                                      ex.ToString());
                resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE;
            }
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script VMWareVMXConfigFileContentScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());

            return(new CollectionScriptResults
                       (resultCode, 0, null, null, null, false, m_dataRow.ToString()));
        }
コード例 #26
0
 public ushort ReadUInt16(IRemoteProcess remoteProcess, MemoryMap memoryMap)
 {
     var address = this.GetAddress(remoteProcess, memoryMap);
     return this.readProcessMemory.ReadUInt16(remoteProcess.Handle, address);
 }
コード例 #27
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            m_taskId = taskId.ToString();
            Stopwatch     executionTimer = Stopwatch.StartNew();
            ResultCodes   resultCode     = ResultCodes.RC_SUCCESS;
            StringBuilder dataRow        = new StringBuilder();

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsSiebelServerDataCollectionScript.",
                                  m_taskId);

            try {
                //
                // Check ManagementScope CIMV
                ManagementScope cimvScope = null;
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsSiebelServerDataCollectionScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed.",
                                              m_taskId);
                    }
                }

                //
                // Check Siebel Credential
                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    string[] connectionVariables = new String[] { @"SiebelUserName",
                                                                  @"SiebelUserPassword",
                                                                  @"TemporaryDirectory",
                                                                  @"siebelSrvrmgrPath" };
                    resultCode = this.ValidateConnectionParameters(connection, connectionVariables);
                }

                //
                // Check Parameter variables.
                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    string[] paramVariables = new String[] { @"installDirectory",
                                                             @"gatewayServerName",
                                                             @"serverName",
                                                             @"enterpriseName",
                                                             @"siebelServerCommand" };
                    resultCode = this.ValidateScriptParameters(scriptParameters, paramVariables);
                }

                //
                // Check Temporary Directory
                string tempDir = connection[@"TemporaryDirectory"].ToString();
                resultCode = this.ValidateTemporaryDirectory(cimvScope, ref tempDir);

                // Execute Siebel Command
                string strBatchFileContent = BuildBatchFile(connection[@"siebelSrvrmgrPath"].ToString(),
                                                            scriptParameters[@"gatewayServerName"],
                                                            scriptParameters[@"serverName"],
                                                            scriptParameters[@"enterpriseName"],
                                                            connection[@"SiebelUserName"].ToString(),
                                                            connection[@"SiebelUserPassword"].ToString(),
                                                            scriptParameters[@"siebelServerCommand"],
                                                            scriptParameters[@"outputDisplayColumns"]);

                string stdout = null;
                using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile
                                               (taskId.ToString(), cimvScope, strBatchFileContent, connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) {
                    //
                    //This method will block until the entire remote process operation completes.
                    resultCode = rp.Launch();
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Remote process operation completed with result code {1}.",
                                          m_taskId,
                                          resultCode.ToString());

                    if (resultCode == ResultCodes.RC_SUCCESS)
                    {
                        if (rp.Stdout != null && rp.Stdout.Length > 0)
                        {
                            stdout = rp.Stdout.ToString();
                            string commandOutput = null;
                            if (!stdout.Contains(@"Execution completed"))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Data returned is shorter than expected, possibly due to transfer failure.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                                      m_taskId);
                                resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                            }
                            else
                            {
                                //
                                // package command output result.
                                if (ResultCodes.RC_SUCCESS == ParseCommandOutput(stdout,
                                                                                 scriptParameters[@"siebelServerCommand"],
                                                                                 scriptParameters[@"outputDisplayColumns"],
                                                                                 out commandOutput))
                                {
                                    if (!attributes.ContainsKey(s_returnAttribute))
                                    {
                                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                                              0,
                                                              "Task Id {0}: Attribute \"{1}\" missing from attributeSet.",
                                                              m_taskId,
                                                              s_returnAttribute);
                                    }
                                    else
                                    {
                                        dataRow.Append(elementId).Append(',')
                                        .Append(attributes[s_returnAttribute]).Append(',')
                                        .Append(scriptParameters[@"CollectorId"]).Append(',')
                                        .Append(taskId).Append(',')
                                        .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds).Append(',')
                                        .Append(s_returnAttribute).Append(',')
                                        .Append(BdnaDelimiters.BEGIN_TAG).Append(commandOutput).Append(BdnaDelimiters.END_TAG);
                                    }
                                }
                            }
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: No data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                                  taskId.ToString());
                            resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                        }
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Remote execution error.\nSTDOUT.STDERR:\n{1}",
                                              m_taskId,
                                              rp.Stdout.ToString());
                    }
                }
                //// post processing??
                //if (resultCode == ResultCodes.RC_SUCCESS && string.IsNullOrEmpty( > 0) {
                //    //foreach (KeyValuePair<string, QueryTableEntry> entry in s_queryTable) {
                //    //    entry.Value.ResultHandler(this, entry.Key, stdoutData.ToString());
                //    //}
                //}
            } catch (Exception ex) {
                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsSiebelServerDataCollectionScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          m_taskId,
                                          executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsSiebelServerDataCollectionScript.  Elapsed time {1}.\n{2}",
                                          m_taskId,
                                          executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsSiebelServerDataCollectionScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString()));
        }
コード例 #28
0
        public void Add(IRemoteProcess remoteProcess)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);

            throw new NotImplementedException();
        }
コード例 #29
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            m_executionTimer    = Stopwatch.StartNew();
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASGetFileScript.",
                                  m_taskId);
            try {
                ManagementScope cimvScope    = null;
                ManagementScope defaultScope = null;

                // Check ManagementScope CIMV
                if (null == connection)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsWASGetFileScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey(@"cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey(@"default"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for Default namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope    = connection[@"cimv2"] as ManagementScope;
                    defaultScope = connection[@"default"] as ManagementScope;

                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed.",
                                              m_taskId);
                    }
                    else if (!defaultScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to Default namespace failed.",
                                              m_taskId);
                    }
                }

                //Check Script Variables
                if (resultCode.Equals(ResultCodes.RC_SUCCESS))
                {
                    //
                    // We have to massage the script parameter set, replace
                    // any keys with a colon by just the part after the colon.
                    // We should probably narrow this to just the registryKey
                    // and registryRoot entries...
                    Dictionary <string, string> d = new Dictionary <string, string>();

                    foreach (KeyValuePair <string, string> kvp in scriptParameters)
                    {
                        string[] sa = kvp.Key.Split(s_collectionParameterSetDelimiter,
                                                    StringSplitOptions.RemoveEmptyEntries);
                        Debug.Assert(sa.Length > 0);
                        d[sa[sa.Length - 1]] = kvp.Value;
                    }

                    scriptParameters = d;
                    if (scriptParameters.ContainsKey("profRegPath"))
                    {
                        m_filePath = scriptParameters[@"profRegPath"];
                    }
                    else if (scriptParameters.ContainsKey("cellPath"))
                    {
                        m_filePath = scriptParameters[@"cellPath"];
                    }
                    else if (scriptParameters.ContainsKey("nodeVarPath"))
                    {
                        m_filePath = scriptParameters[@"nodeVarPath"];
                    }
                    else if (scriptParameters.ContainsKey("rsrcFilePath"))
                    {
                        m_filePath = scriptParameters[@"rsrcFilePath"];
                    }
                    else if (scriptParameters.ContainsKey("svrCfgPath"))
                    {
                        m_filePath = scriptParameters[@"svrCfgPath"];
                    }
                    else if (scriptParameters.ContainsKey("virtHostsFilePath"))
                    {
                        m_filePath = scriptParameters[@"virtHostsFilePath"];
                    }
                    else
                    {
                        resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Missing parameter WAS Script parameter.",
                                              m_taskId);
                    }
                }

                // Check Remote Process Temp Directory
                if (resultCode.Equals(ResultCodes.RC_SUCCESS))
                {
                    if (!connection.ContainsKey(@"TemporaryDirectory"))
                    {
                        connection[@"TemporaryDirectory"] = @"%TMP%";
                    }
                    else
                    {
                        if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                        {
                            if (!Lib.ValidateDirectory(m_taskId, connection[@"TemporaryDirectory"].ToString(), cimvScope))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Temporary directory {1} is not valid.",
                                                      m_taskId,
                                                      connection[@"TemporaryDirectory"].ToString());
                                resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: User specified temp directory has been validated.",
                                                      m_taskId);
                            }
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    StringBuilder fileContent = new StringBuilder();
                    StringBuilder fileName    = new StringBuilder();
                    string[]      fileData    = m_filePath.Split('=');
                    fileName.Append(fileData[0]);

                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Attempting to retrieve file {1}.",
                                          m_taskId,
                                          fileName.ToString());

                    if (Lib.ValidateFile(m_taskId, fileName.ToString(), cimvScope))
                    {
                        using (IRemoteProcess rp =
                                   RemoteProcess.GetRemoteFile(m_taskId, cimvScope, fileName.ToString(), connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) {
                            // Launch the remote process.
                            // This method will block until the entire remote process operation completes.
                            resultCode = rp.Launch();
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                                  m_taskId,
                                                  resultCode.ToString());
                            fileContent.Append(rp.Stdout);
                        }

                        m_dataRow.Append(m_elementId).Append(',')
                        .Append(m_attributes[fileData[1]]).Append(',')
                        .Append(m_scriptParameters[@"CollectorId"]).Append(',')
                        .Append(m_taskId).Append(',')
                        .Append(m_databaseTimestamp + m_executionTimer.ElapsedMilliseconds).Append(',')
                        .Append(fileData[1]).Append(',')
                        .Append(BdnaDelimiters.BEGIN_TAG).Append(fileContent).Append(BdnaDelimiters.END_TAG);
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: WAS Config file: {1} does not exist.",
                                              m_taskId,
                                              fileName.ToString());

                        resultCode = ResultCodes.RC_SUCCESS;
                    }
                }
            } catch (Exception ex) {
                Lib.LogException(m_taskId,
                                 m_executionTimer,
                                 "Unhandled exception in WindowsWASGetFileScript",
                                 ex);
                resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE;
            }

            CollectionScriptResults result = new CollectionScriptResults(resultCode,
                                                                         0,
                                                                         null,
                                                                         null,
                                                                         null,
                                                                         false,
                                                                         m_dataRow.ToString());

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASGetFileScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  result.ResultCode.ToString());
            return(result);
        }
コード例 #30
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            m_executionTimer    = Stopwatch.StartNew();
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASIsInstanceRunningScript.",
                                  m_taskId);

            try  {
                // Check ManagementScope CIMV
                ManagementScope cimvScope = null;
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsWASIsInstanceRunningScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed.",
                                              m_taskId);
                    }
                }

                //Check WAS Profile path attribute
                if (!scriptParameters.ContainsKey("installDirectory"))
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing Profile Path Script parameter.",
                                          m_taskId);
                }
                else
                {
                    m_installHome = scriptParameters[@"installDirectory"];
                }

                //Check Server Name attribute
                if (!scriptParameters.ContainsKey("appsrv_Name"))
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing Server Name script parameter.",
                                          m_taskId);
                }
                else
                {
                    m_server = scriptParameters[@"appsrv_Name"];
                }

                // Check Remote Process Temp Directory
                if (!connection.ContainsKey(@"TemporaryDirectory"))
                {
                    connection[@"TemporaryDirectory"] = @"%TMP%";
                }
                else
                {
                    if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                    {
                        if (!Lib.ValidateDirectory(m_taskId, connection[@"TemporaryDirectory"].ToString(), cimvScope))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} is not valid.",
                                                  m_taskId,
                                                  connection[@"TemporaryDirectory"].ToString());
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} has been validated.",
                                                  m_taskId,
                                                  connection[@"TemporaryDirectory"].ToString());
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    // EXTRA code for wsadmin
                    string strTempDir = connection["TemporaryDirectory"].ToString().Trim();
                    if (strTempDir.EndsWith(@"\"))
                    {
                        strTempDir = strTempDir.Substring(0, strTempDir.Length - 1);
                    }

                    string running = "False";
                    //string batchFile =  m_profilePath.Trim() + @"\bin\serverStatus.bat " + m_server + @" -user bdna -password bdna";
                    string s1        = m_installHome.Trim();
                    string s2        = s1.Replace(" ", "^ ");
                    string batchFile = s2 + @"\bin\serverStatus.bat " + m_server;
                    //Console.WriteLine(batchFile);
                    using (IRemoteProcess rp =
                               RemoteProcess.ExecuteBatchFile(m_taskId, cimvScope, batchFile.ToString(),
                                                              connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) {
                        //This method will block until the entire remote process operation completes.
                        resultCode = rp.Launch();


                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: Remote process operation completed with result code {1}.",
                                              m_taskId,
                                              resultCode.ToString());

                        string[] arrOutputLine = rp.Stdout.ToString().Split("\r\n".ToCharArray());
                        for (int i = 0; i < arrOutputLine.Length; i++)
                        {
                            string output = arrOutputLine[i];
                            if (s_instanceRegex.IsMatch(output))
                            {
                                Match  match = s_instanceRegex.Match(output);
                                string name  = match.Groups["server"].ToString();
                                if (string.Equals(m_server, name))
                                {
                                    running = "True";
                                }
                            }
                        }
                    }

                    //Console.WriteLine(running);
                    m_dataRow.Append(m_elementId).Append(',')
                    .Append(m_attributes["appSrv_isRunning"]).Append(',')
                    .Append(m_scriptParameters["CollectorId"]).Append(',')
                    .Append(m_taskId).Append(',')
                    .Append(m_databaseTimestamp + m_executionTimer.ElapsedMilliseconds).Append(',')
                    .Append("appSrv_isRunning").Append(',')
                    .Append(BdnaDelimiters.BEGIN_TAG).Append(running).Append(BdnaDelimiters.END_TAG);
                }
            } catch (Exception ex) {
                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsWASIsInstanceRunningScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsWASIsInstanceRunningScript.  Elapsed time {1}.\n{2}",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASIsInstanceRunningScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString()));
        }
コード例 #31
0
 public long ReadInt64(IRemoteProcess remoteProcess, MemoryMap memoryMap)
 {
     var address = this.GetAddress(remoteProcess, memoryMap);
     return this.readProcessMemory.ReadInt64(remoteProcess.Handle, address);
 }
コード例 #32
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp,
                                                   long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters,
                                                   IDictionary <string, object> connection, string tftpPath, string tftpPath_login,
                                                   string tftpPath_password, ITftpDispatcher tftpDispatcher)
        {
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;
            m_tftpDispatcher    = tftpDispatcher;
            m_tftpPath          = tftpPath;
            m_tftpPath_login    = tftpPath_login;
            m_tftpPath_password = tftpPath_password;
            m_connection        = connection;
            m_executionTimer    = Stopwatch.StartNew();

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script MSVirtualServerVMConfigFileContentScript.",
                                  m_taskId);
            try
            {
                // Check ManagementScope CIMV
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to MSVirtualServerVMConfigFileContentScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    m_cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!m_cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed",
                                              m_taskId);
                    }
                }

                //Check VM Config File Path attribute
                if (scriptParameters.ContainsKey("vmcFile"))
                {
                    m_vmcFilePath = scriptParameters[@"vmcFile"];
                }
                else
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing parameter VM Config File Path attribute.",
                                          m_taskId);
                }

                // Check Remote Process Temp Directory
                if (!m_connection.ContainsKey(@"TemporaryDirectory"))
                {
                    m_connection[@"TemporaryDirectory"] = @"%TMP%";
                }
                else
                {
                    if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                    {
                        if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} is not valid.",
                                                  m_taskId,
                                                  m_connection[@"TemporaryDirectory"].ToString());
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: User specified temp directory has been validated.",
                                                  m_taskId);
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Attempting to retrieve file {1}.",
                                          m_taskId,
                                          m_vmcFilePath);
                    StringBuilder fileContent = new StringBuilder();

                    if (Lib.ValidateFile(m_taskId, m_vmcFilePath, m_cimvScope))
                    {
                        using (IRemoteProcess rp =
                                   RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, m_vmcFilePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher))
                        {
                            //
                            // Launch the remote process.
                            // This method will block until the entire remote process operation completes.
                            rp.Encoding = Encoding.Unicode;
                            resultCode  = rp.Launch();
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                                  m_taskId,
                                                  resultCode.ToString());
                            fileContent.Append(rp.Stdout);
                        }
                        //Console.WriteLine(fileContent.ToString());
                        string        formattedFile = fileContent.ToString().Substring(1);
                        StringBuilder fileData      = getVMData(formattedFile);
                        this.BuildDataRow(@"vmcFileData", fileData.ToString());
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: VM Config file {1} does not exist.",
                                              m_taskId,
                                              m_vmcFilePath);

                        resultCode = ResultCodes.RC_SUCCESS; //@TODO: change to RC_REMOTE_FILE_NOT_EXISTED
                        //resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;  //@TODO: change to RC_REMOTE_FILE_NOT_EXISTED
                    }
                }
            }
            catch (Exception ex)
            {
                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in MSVirtualServerVMConfigFileContentScript.  Elapsed time {1}.\n{2}Result code changed to RC_PROCESSING_EXECEPTION.",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in MSVirtualServerVMConfigFileContentScript.  Elapsed time {1}.\n{2}",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script MSVirtualServerVMConfigFileContentScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults
                       (resultCode, 0, null, null, null, false, m_dataRow.ToString()));
        }
コード例 #33
0
 public byte[] Read(IRemoteProcess remoteProcess, MemoryMap memoryMap, int size)
 {
     var address = this.GetAddress(remoteProcess, memoryMap);
     return this.readProcessMemory.Read(remoteProcess.Handle, address, size);
 }
コード例 #34
0
 public string ReadString(IRemoteProcess remoteProcess, MemoryMap memoryMap, int? length = null)
 {
     var address = this.GetAddress(remoteProcess, memoryMap);
     return this.readProcessMemory.ReadString(remoteProcess.Handle, address, length);
 }
コード例 #35
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;
            m_connection        = connection;
            string strOracleHome = null, strSchemaName = null, strSchemaPassword = null;

            m_executionTimer = Stopwatch.StartNew();
            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsOracleInstanceLMSOptions3StaticScript.",
                                  m_taskId);

            try {
                // Check ManagementScope CIMV
                ManagementScope cimvScope = null;
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsOracleInstanceLMSOptions3StaticScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed",
                                              m_taskId);
                    }
                }
                if (!scriptParameters.ContainsKey("version"))
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing script parameter \"version\".",
                                          m_taskId);
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                }
                else
                {
                    m_strVersion = scriptParameters["version"].Trim();
                }

                if (!scriptParameters.ContainsKey("OracleHome"))
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing script parameter \"OracleHome\".",
                                          m_taskId);
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                }
                else
                {
                    strOracleHome = scriptParameters["OracleHome"].Trim();
                    if (strOracleHome.EndsWith(@"\"))
                    {
                        strOracleHome = strOracleHome.Substring(0, strOracleHome.Length - 1);
                    }
                }

                if (!connection.ContainsKey("schemaName"))
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing script parameter \"schemaName\".",
                                          m_taskId);
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                }
                else
                {
                    strSchemaName = connection["schemaName"].ToString().Trim();
                }

                if (!connection.ContainsKey("schemaPassword"))
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing script parameter \"schemaPassword\".",
                                          m_taskId);
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                }
                else
                {
                    strSchemaPassword = connection["schemaPassword"].ToString().Trim();
                }


                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    // Check Remote Process Temp Directory
                    if (!connection.ContainsKey("TemporaryDirectory"))
                    {
                        connection["TemporaryDirectory"] = @"%TMP%";
                    }
                    else
                    {
                        if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                        {
                            if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), cimvScope))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Temporary directory {1} is not valid.",
                                                      m_taskId,
                                                      connection[@"TemporaryDirectory"].ToString());
                                resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                      0,
                                                      "Task Id {0}: Temporary directory {1} has been validated.",
                                                      m_taskId,
                                                      connection[@"TemporaryDirectory"].ToString());
                            }
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    string strTempDir = connection["TemporaryDirectory"].ToString().Trim();
                    if (strTempDir.EndsWith(@"\"))
                    {
                        strTempDir = strTempDir.Substring(0, strTempDir.Length - 1);
                    }
                    string        strBatchFileContent = buildBatchFile(strTempDir, strOracleHome, strSchemaName, strSchemaPassword);
                    StringBuilder stdoutData          = new StringBuilder();
                    using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile
                                                   (m_taskId, cimvScope, strBatchFileContent, connection, tftpPath, tftpPath_login, tftpPath_password, tftpDispatcher)) {
                        //This method will block until the entire remote process operation completes.
                        resultCode = rp.Launch();
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: Remote process operation completed with result code {1}.",
                                              m_taskId,
                                              resultCode.ToString());

                        if (resultCode == ResultCodes.RC_SUCCESS)
                        {
                            stdoutData.Append(rp.Stdout);
                            if (rp.Stdout != null && rp.Stdout.Length > 0)
                            {
                                if (rp.Stdout.ToString().Contains("ORA-01017"))
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: Oracle L3 credential is invalid.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}",
                                                          m_taskId,
                                                          rp.Stdout.ToString());
                                    resultCode = ResultCodes.RC_HOST_CONNECT_FAILED;
                                }
                                else if (rp.Stdout.ToString().Contains("ERROR-"))
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: Batch file execution exception.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}",
                                                          m_taskId,
                                                          rp.Stdout.ToString());
                                    resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                                }
                                else if (!rp.Stdout.ToString().Contains(@"BDNA"))
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: SQLPLUS exception, no proper data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.\nSTDOUT/STDERR:\n{1}",
                                                          m_taskId,
                                                          rp.Stdout.ToString());
                                    resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                                }
                                else if (!rp.Stdout.ToString().Contains(@"Execution completed"))
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: Exception with batch return data.\nData returned is shorter than expected, possibly due to transfer failure.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                                          m_taskId);
                                    resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                                }
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: No data returned.\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                                      m_taskId);
                                resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                            }
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Remote execution error.\nSTDOUT.STDERR:\n{1}",
                                                  m_taskId,
                                                  rp.Stdout.ToString());
                        }
                    }
                    if (resultCode == ResultCodes.RC_SUCCESS && stdoutData.Length > 0)
                    {
                        foreach (KeyValuePair <string, QueryTableEntry> entry in s_queryTable)
                        {
                            entry.Value.ResultHandler(this, entry.Key, stdoutData.ToString());
                        }
                        this.processLabelSecurityCollectedData();
                        if (!ver8_pattern.IsMatch(m_strVersion))
                        {
                            this.processDatabaseVaultCollectedData();
                            this.processAuditVaultCollectedData();
                        }
                        foreach (KeyValuePair <string, string> kvp in m_collectedData)
                        {
                            this.BuildDataRow(kvp.Key, kvp.Value);
                        }
                    }
                }
            } catch (Exception ex) {
                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsOracleInstanceLMSOptions3StaticScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in WindowsOracleInstanceLMSOptions3StaticScript.  Elapsed time {1}.\n{2}",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsOracleInstanceLMSOptions3StaticScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString()));
        }
コード例 #36
0
        /// <summary>
        /// Execute command
        /// (Note that file path must be absolute path)
        /// </summary>
        /// <param name="filePath">File Path</param>
        /// <param name="collectedData">Collected Result.</param>
        /// <returns></returns>
        private ResultCodes ExecuteCommand(string userCommandLine, out string collectedData)
        {
            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            collectedData = string.Empty;
            if (!m_connection.ContainsKey(@"TemporaryDirectory"))
            {
                m_connection[@"TemporaryDirectory"] = @"%TMP%";
            }
            else
            {
                if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                {
                    if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope))
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Temporary directory {1} is not valid.",
                                              m_taskId,
                                              m_connection[@"TemporaryDirectory"].ToString());
                        resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: Temporary directory {1} has been validated.",
                                              m_taskId,
                                              m_connection[@"TemporaryDirectory"].ToString());
                    }
                }
            }

            if (resultCode == ResultCodes.RC_SUCCESS)
            {
                string strTempDir = m_connection["TemporaryDirectory"].ToString().Trim();
                if (strTempDir.EndsWith(@"\"))
                {
                    strTempDir = strTempDir.Substring(0, strTempDir.Length - 1);
                }
                string        strBatchFileContent = buildBatchFile(userCommandLine);
                StringBuilder stdoutData          = new StringBuilder();
                using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile
                                               (m_taskId, m_cimvScope, strBatchFileContent, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) {
                    //This method will block until the entire remote process operation completes.
                    resultCode = rp.Launch();

                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Remote process operation completed with result code {1}.",
                                          m_taskId,
                                          resultCode.ToString());

                    if (rp != null && rp.Stdout != null && resultCode == ResultCodes.RC_SUCCESS)
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: Remote processExec completed with result <{1}>.",
                                              m_taskId,
                                              rp.Stdout.ToString());

                        collectedData = rp.Stdout.ToString();
                        //string output = rp.Stdout.ToString();
                        //if (output.IndexOf(s_endTag) != -1) {
                        //    collectedData = output.Substring(0, output.Length - s_endTag.Length - 2);
                        //} else {
                        //    resultCode = ResultCodes.RC_PROCESS_EXEC_FAILED;
                        //    Lib.Logger.TraceEvent(TraceEventType.Error,
                        //                          0,
                        //                          "Task Id {0}: Remote execution error.\nSTDOUT.STDERR:\n{1}",
                        //                          m_taskId,
                        //                          rp.Stdout.ToString());
                        //}
                    }
                    else
                    {
                        resultCode = ResultCodes.RC_PROCESS_EXEC_FAILED;
                    }
                }
            }
            return(resultCode);
        }
コード例 #37
0
 public void Delete(IRemoteProcess entity)
 {
     this.processRepository.Delete(entity);
 }
コード例 #38
0
        /// <summary>
        /// Get File Content
        /// (Note that file path must be absolute path)
        /// (Note that file path should not have double quote in general, but it has escaped the double quote to be convenient).
        /// </summary>
        /// <param name="filePath">File Path</param>
        /// <param name="collectedData">Collected Result.</param>
        /// <returns></returns>
        private ResultCodes GetFileContent(string filePath, out string collectedData)
        {
            collectedData = string.Empty;
            ResultCodes resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_ACCESS_FILE_PROPERTY;

            if (!m_connection.ContainsKey(@"TemporaryDirectory"))
            {
                m_connection[@"TemporaryDirectory"] = @"%TMP%";
            }
            else
            {
                if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                {
                    if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope))
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Temporary directory {1} is not valid.",
                                              m_taskId,
                                              m_connection[@"TemporaryDirectory"].ToString());
                        resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: User specified temp directory has been validated.",
                                              m_taskId);
                    }
                }
            }

            if (filePath.EndsWith("\"") && filePath.StartsWith("\""))
            {
                filePath = filePath.Substring(1, filePath.Length - 2);
            }
            if (Lib.ValidateFile(m_taskId, filePath, m_cimvScope))
            {
                using (IRemoteProcess rp =
                           RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, filePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) {
                    //
                    // Launch the remote process.
                    // This method will block until the entire remote process operation completes.
                    resultCode = rp.Launch();
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                          m_taskId,
                                          resultCode.ToString());
                    collectedData = rp.Stdout.ToString();
                }
            }
            else
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: filepath: {1} does not exist.",
                                      m_taskId,
                                      filePath);
            }

            return(resultCode);
        }
コード例 #39
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        ///
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            Stopwatch     executionTimer    = Stopwatch.StartNew();
            string        taskIdString      = taskId.ToString();
            StringBuilder dataRow           = new StringBuilder();
            StringBuilder parsedIniFileData = new StringBuilder();
            ResultCodes   resultCode        = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script CollectWindowsCPAINIFile.",
                                  taskIdString);

            Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Hash Dump = {1}", taskIdString, scriptParameters.ToString());
            string        remoteFileName  = scriptParameters[@"CPAWindowsIniFilePath"];
            StringBuilder collectedCPAttr = new StringBuilder();
            string        logData         = null;

            Lib.Logger.TraceEvent(TraceEventType.Information,
                                  0,
                                  "Passed file name into the script : {0}",
                                  remoteFileName);

            Lib.Logger.TraceEvent(TraceEventType.Information,
                                  0,
                                  "Task Id {0}: Running TFTP to collect the contents of CPA INI file on a remote system",
                                  taskIdString);


            MemoryStream ms = new MemoryStream(4096);

            using (TraceListener tl = new TextWriterTraceListener(ms)) {
                tl.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ProcessId | TraceOptions.ThreadId;

                try {
                    Lib.Logger.Listeners.Add(tl);
                    //
                    // Create a remote process object to manage the
                    // transfer of the remote file contents to our
                    // script.
                    //
                    // Many of these values are passed to the script from
                    // WinCs to give the Remote Process library access to
                    // Facilities outside the script sandbox.  The script
                    // need not care what these values are, just pass them
                    // through.
                    //
                    // Wrap the RemoteProcess in a using clause so that resources
                    // are automatically released when the remote process
                    // operation completes.

                    ManagementScope cimvScope = connection[@"cimv2"] as ManagementScope;

                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed",
                                              taskIdString);
                        return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString()));
                    }
                    connection[@"TemporaryDirectory"] = @"c:\";

                    // collect data from multiple files
                    if (remoteFileName.Contains(","))
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Information,
                                              0,
                                              "CPAIniFilePath has multiple INI files path (" + remoteFileName + ")",
                                              taskIdString);
                        string[] iniFiles = remoteFileName.Split(',');
                        for (int fileCount = 0; fileCount < iniFiles.Length; fileCount++)
                        {
                            String fileName = iniFiles[fileCount];
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "CPA file path is " + fileName,
                                                  taskIdString);
                            using (IRemoteProcess rp =
                                       RemoteProcess.GetRemoteFile(taskIdString, // Task Id to log against.
                                                                   cimvScope,    // WMI connection, passed to collection script from WinCs
                                                                   fileName,     // Name of remote file to retrieve.
                                                                   connection,   // credential hash passed to all collection/connection scripts
                                                                   tftpPath,
                                                                   tftpPath_login,
                                                                   tftpPath_password,
                                                                   tftpDispatcher)) { // TFTP listener, passed to script from WinCs
                                //
                                // Launch the remote process.  This method will
                                // block until the entire remote process operation
                                // completes.
                                ResultCodes rc = rp.Launch();

                                //
                                // Once you get control back, there are properties that
                                // can be checked to information about the outcome of the
                                // operation, obtain log data, and retrieve collection results.
                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Remote process operation completed with result code" + rc.ToString(),
                                                      taskIdString);

                                if (null != collectedCPAttr)
                                {
                                    collectedCPAttr.Append(rp.Stdout);
                                }
                            }
                        }
                        if (null != collectedCPAttr)
                        {
                            int MIN_SECTIONS = 1;
                            // string collectedCPAttr = sb.ToString();
                            // System.Console.WriteLine(collectedCPAttr);

                            string[] cpAttrSections = new Regex(@"\[").Split(collectedCPAttr.ToString());
                            // System.Console.WriteLine("{0} sections in text:", cpAttrSections.Length);
                            if (cpAttrSections.Length > 0)
                            {
                                for (int secCtr = 0; secCtr < cpAttrSections.Length; secCtr++)
                                {
                                    // System.Console.WriteLine("This Section");
                                    // System.Console.WriteLine(cpAttrSections[secCtr]);
                                    string[] secEntries = cpAttrSections[secCtr].Split('\n');
                                    if (secEntries.Length == 1)
                                    {
                                        continue;
                                    }


                                    for (int entryCtr = 0; entryCtr < secEntries.Length; entryCtr++)
                                    {
                                        string tEntry = secEntries[entryCtr].Trim();
                                        if (tEntry.Length > 0)
                                        {
                                            if (tEntry.EndsWith("]"))
                                            {
                                                if (secCtr > MIN_SECTIONS)
                                                {
                                                    parsedIniFileData.Append("<BDNA,>");
                                                }
                                                parsedIniFileData.Append("Section=");
                                                parsedIniFileData.Append(tEntry.TrimEnd(']'));
                                            }
                                            else
                                            {
                                                if (secEntries[entryCtr - 1].Trim().EndsWith("]"))
                                                {
                                                    parsedIniFileData.Append("<BDNA,1>");
                                                }
                                                else
                                                {
                                                    parsedIniFileData.Append("<BDNA,2>");
                                                }
                                                parsedIniFileData.Append(tEntry);
                                            }
                                        }
                                    }
                                }
                            }

                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Parsing Succeeded. Parsed INI File Data is : " + parsedIniFileData.ToString(),
                                                  parsedIniFileData.ToString());

                            if (ResultCodes.RC_SUCCESS == resultCode)
                            {
                                dataRow.Append(elementId).Append(',')
                                .Append(attributes[@"collectedCPAttr"])
                                .Append(',')
                                .Append(scriptParameters[@"CollectorId"]).Append(',')
                                .Append(taskId).Append(',')
                                .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds)
                                .Append(',')
                                .Append(@"collectedCPAttr")
                                .Append(',')
                                .Append(BdnaDelimiters.BEGIN_TAG)
                                .Append(collectedCPAttr)
                                .Append(BdnaDelimiters.END_TAG);

                                dataRow.Append(elementId).Append(',')
                                .Append(attributes[@"parsedCPAttr"])
                                .Append(',')
                                .Append(scriptParameters[@"CollectorId"]).Append(',')
                                .Append(taskId).Append(',')
                                .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds)
                                .Append(',')
                                .Append(@"parsedCPAttr")
                                .Append(',')
                                .Append(BdnaDelimiters.BEGIN_TAG)
                                .Append(parsedIniFileData)
                                .Append(BdnaDelimiters.END_TAG);
                            }
                        }
                    }
                    else
                    {
                        using (IRemoteProcess rp =
                                   RemoteProcess.GetRemoteFile(taskIdString,   // Task Id to log against.
                                                               cimvScope,      // WMI connection, passed to collection script from WinCs
                                                               remoteFileName, // Name of remote file to retrieve.
                                                               connection,     // credential hash passed to all collection/connection scripts
                                                               tftpPath,
                                                               tftpPath_login,
                                                               tftpPath_password,
                                                               tftpDispatcher)) {   // TFTP listener, passed to script from WinCs
                            //
                            // Launch the remote process.  This method will
                            // block until the entire remote process operation
                            // completes.
                            ResultCodes rc = rp.Launch();

                            //
                            // Once you get control back, there are properties that
                            // can be checked to information about the outcome of the
                            // operation, obtain log data, and retrieve collection results.
                            Lib.Logger.TraceEvent(TraceEventType.Information,
                                                  0,
                                                  "Remote process operation completed with result code" + rc.ToString(),
                                                  taskIdString);

                            if (null != collectedCPAttr)
                            {
                                collectedCPAttr.Append(rp.Stdout);
                                int MIN_SECTIONS = 1;
                                // string collectedCPAttr = sb.ToString();
                                // System.Console.WriteLine(collectedCPAttr);

                                string[] cpAttrSections = new Regex(@"\[").Split(collectedCPAttr.ToString());
                                // System.Console.WriteLine("{0} sections in text:", cpAttrSections.Length);
                                if (cpAttrSections.Length > 0)
                                {
                                    for (int secCtr = 0; secCtr < cpAttrSections.Length; secCtr++)
                                    {
                                        // System.Console.WriteLine("This Section");
                                        // System.Console.WriteLine(cpAttrSections[secCtr]);
                                        string[] secEntries = cpAttrSections[secCtr].Split('\n');
                                        if (secEntries.Length == 1)
                                        {
                                            continue;
                                        }


                                        for (int entryCtr = 0; entryCtr < secEntries.Length; entryCtr++)
                                        {
                                            string tEntry = secEntries[entryCtr].Trim();
                                            if (tEntry.Length > 0)
                                            {
                                                if (tEntry.EndsWith("]"))
                                                {
                                                    if (secCtr > MIN_SECTIONS)
                                                    {
                                                        parsedIniFileData.Append("<BDNA,>");
                                                    }
                                                    parsedIniFileData.Append("Section=");
                                                    parsedIniFileData.Append(tEntry.TrimEnd(']'));
                                                }
                                                else
                                                {
                                                    if (secEntries[entryCtr - 1].Trim().EndsWith("]"))
                                                    {
                                                        parsedIniFileData.Append("<BDNA,1>");
                                                    }
                                                    else
                                                    {
                                                        parsedIniFileData.Append("<BDNA,2>");
                                                    }
                                                    parsedIniFileData.Append(tEntry);
                                                }
                                            }
                                        }
                                    }
                                }

                                Lib.Logger.TraceEvent(TraceEventType.Information,
                                                      0,
                                                      "Parsing Succeeded. Parsed INI File Data is : " + parsedIniFileData.ToString(),
                                                      parsedIniFileData.ToString());

                                if (ResultCodes.RC_SUCCESS == resultCode)
                                {
                                    dataRow.Append(elementId).Append(',')
                                    .Append(attributes[@"collectedCPAttr"])
                                    .Append(',')
                                    .Append(scriptParameters[@"CollectorId"]).Append(',')
                                    .Append(taskId).Append(',')
                                    .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds)
                                    .Append(',')
                                    .Append(@"collectedCPAttr")
                                    .Append(',')
                                    .Append(BdnaDelimiters.BEGIN_TAG)
                                    .Append(collectedCPAttr)
                                    .Append(BdnaDelimiters.END_TAG);

                                    dataRow.Append(elementId).Append(',')
                                    .Append(attributes[@"parsedCPAttr"])
                                    .Append(',')
                                    .Append(scriptParameters[@"CollectorId"]).Append(',')
                                    .Append(taskId).Append(',')
                                    .Append(databaseTimestamp + executionTimer.ElapsedMilliseconds)
                                    .Append(',')
                                    .Append(@"parsedCPAttr")
                                    .Append(',')
                                    .Append(BdnaDelimiters.BEGIN_TAG)
                                    .Append(parsedIniFileData)
                                    .Append(BdnaDelimiters.END_TAG);
                                }
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "CPA INI File not found on target machine.",
                                                      taskIdString);
                                resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                            }
                        }
                    }
                } finally {
                    tl.Flush();
                    Lib.Logger.Listeners.Remove(tl);
                }

                logData = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            }

            Lib.Logger.TraceEvent(TraceEventType.Information,
                                  0,
                                  "CPA INI File data returned: ",
                                  taskIdString);
            Lib.Logger.TraceEvent(TraceEventType.Information,
                                  0,
                                  collectedCPAttr.ToString(),
                                  taskIdString);
            Lib.Logger.TraceEvent(TraceEventType.Information,
                                  0,
                                  "Log data returned: ",
                                  taskIdString);
            Lib.Logger.TraceEvent(TraceEventType.Information,
                                  0,
                                  logData,
                                  taskIdString);

            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, dataRow.ToString()));
        }
コード例 #40
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp,
                                                   long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters,
                                                   IDictionary <string, object> connection, string tftpPath, string tftpPath_login,
                                                   string tftpPath_password, ITftpDispatcher tftpDispatcher)
        {
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;
            m_tftpPath          = tftpPath;
            m_tftpPath_login    = tftpPath_login;
            m_tftpPath_password = tftpPath_password;
            m_tftpDispatcher    = tftpDispatcher;
            m_connection        = connection;
            m_executionTimer    = Stopwatch.StartNew();

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script VMwareVMLSConfigFileContentScript.",
                                  m_taskId);
            try {
                // Check ManagementScope CIMV
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to VMwareVMLSConfigFileContentScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    m_cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!m_cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed.",
                                              m_taskId);
                    }
                }

                //Check VMLSFilePath attribute
                if (scriptParameters.ContainsKey("VMLSFilePath"))
                {
                    m_vmlsFilePath = scriptParameters[@"VMLSFilePath"];
                }
                else
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing parameter VMLSFilePath attribute.",
                                          m_taskId);
                }

                // Check Remote Process Temp Directory
                if (!m_connection.ContainsKey(@"TemporaryDirectory"))
                {
                    m_connection[@"TemporaryDirectory"] = @"%TMP%";
                }
                else
                {
                    if (!m_connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                    {
                        if (!Lib.ValidateDirectory(m_taskId, m_connection[@"TemporaryDirectory"].ToString(), m_cimvScope))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} is not valid.",
                                                  m_taskId,
                                                  m_connection[@"TemporaryDirectory"].ToString());
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;  //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: User specified temp directory has been validated.",
                                                  m_taskId);
                        }
                    }
                }

                // DEBUG-- to be removed
                #region DEBUG
                StringBuilder sb = new StringBuilder();
                foreach (KeyValuePair <string, string> kvp in m_attributes)
                {
                    sb.Append(@"Attribute[").Append((string)kvp.Key).Append(@"]=").AppendLine((string)kvp.Value);
                }
                Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                      0,
                                      "Task Id {0}: Attribute dictionary contents:\n{1}",
                                      m_taskId,
                                      sb.ToString());
                #endregion
                // DEBUG

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                          0,
                                          "Task Id {0}: Attempting to retrieve file {1}.",
                                          m_taskId,
                                          m_vmlsFilePath);
                    StringBuilder fileContent = new StringBuilder();

                    if (Lib.ValidateFile(m_taskId, m_vmlsFilePath, m_cimvScope))
                    {
                        using (IRemoteProcess rp =
                                   RemoteProcess.GetRemoteFile(m_taskId, m_cimvScope, m_vmlsFilePath, m_connection, m_tftpPath, m_tftpPath_login, m_tftpPath_password, m_tftpDispatcher)) {
                            //
                            // Launch the remote process.
                            // This method will block until the entire remote process operation completes.
                            resultCode = rp.Launch();
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Remote file retrieval operation completed with result code {1}.",
                                                  m_taskId,
                                                  resultCode.ToString());
                            fileContent.Append(rp.Stdout);
                        }
                        // Format file content to format: name=value
                        string strFormattedString = this.formatFileContent(fileContent.ToString());
                        this.BuildDataRow(@"VMLSFileContent", strFormattedString);
                    }
                    else
                    {
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: VMLS file {1} does not exist.",
                                              m_taskId,
                                              m_vmlsFilePath);
                        resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE;
                    }
                }
            }
            catch (Exception ex) {
                if (ResultCodes.RC_SUCCESS == resultCode)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in VMwareVMLSConfigFileContentScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REMOTE_FILE;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in VMwareVMLSConfigFileContentScript.  Elapsed time {1}.\n{2}",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script VMwareVMLSConfigFileContentScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults
                       (resultCode, 0, null, null, null, false, m_dataRow.ToString()));
        }
コード例 #41
0
 public void Add(IRemoteProcess remoteProcess)
 {
     this.remoteProcesses.Add(remoteProcess);
 }
コード例 #42
0
 public void Add(IRemoteProcess remoteProcess)
 {
     this.remoteProcesses.Add(remoteProcess);
 }
コード例 #43
0
        /// <summary>
        /// Execute nslookup command remotely.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            m_executionTimer    = Stopwatch.StartNew();
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASHostsLookupScript.",
                                  m_taskId);
            try
            {
                // Check ManagementScope CIMV
                ManagementScope cimvScope = null;
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to WindowsWASHostsLookupScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed",
                                              m_taskId);
                    }
                }

                //Check script parameter
                if (!scriptParameters.ContainsKey("hostsToLookup"))
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing parameter hostsToLookup.",
                                          m_taskId);
                }
                else
                {
                    m_hostsToLookup = scriptParameters[@"hostsToLookup"];
                }

                // Check Remote Process Temp Directory
                if (!connection.ContainsKey(@"TemporaryDirectory"))
                {
                    connection[@"TemporaryDirectory"] = @"%TMP%";
                }
                else
                {
                    if (!connection[@"TemporaryDirectory"].Equals(@"%TMP%"))
                    {
                        if (!Lib.ValidateDirectory(m_taskId, connection[@"TemporaryDirectory"].ToString(), cimvScope))
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} is not valid.",
                                                  m_taskId,
                                                  connection[@"TemporaryDirectory"].ToString());
                            resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;   //@TODO: change to RC_TEMP_DIRECTORY_NOT_EXIST
                        }
                        else
                        {
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Temporary directory {1} has been validated.",
                                                  m_taskId,
                                                  connection[@"TemporaryDirectory"].ToString());
                        }
                    }
                }

                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    StringBuilder val   = new StringBuilder();
                    String[]      hosts = m_hostsToLookup.Split(',');
                    foreach (string host in hosts)
                    {
                        StringBuilder commandLine = new StringBuilder();
                        if (val.ToString().Length != 0)
                        {
                            val.Append(@"<BDNA,>");
                        }
                        val.Append(host).Append(@"<BDNA,1>");
                        commandLine.Append(@"nslookup ").Append(host);
                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: Attempting to retrieve command output {1}.",
                                              m_taskId,
                                              commandLine);
                        String collectedData = "";
                        using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile(
                                   m_taskId,                               // Task Id to log against.
                                   cimvScope,                              // assuming Remote process uses cimv2 management scope
                                   commandLine.ToString(),                 // batch file
                                   connection,                             // connection dictionary.
                                   tftpPath,
                                   tftpPath_login,
                                   tftpPath_password,
                                   tftpDispatcher))
                        {
                            //This method will block until the entire remote process operation completes.
                            resultCode = rp.Launch();

                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Batch file executed completed with result code {1}.",
                                                  m_taskId,
                                                  resultCode.ToString());

                            collectedData = rp.Stdout.ToString();

                            if (string.IsNullOrEmpty(collectedData))
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Script completed sucessfully with no data to return.",
                                                      m_taskId);
                                resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                            }
                            else
                            {
                                string[] collectedDataArr = collectedData.Split("\r\n".ToCharArray());
                                bool     flag             = false;
                                for (int i = 0; i < collectedDataArr.Length; i++)
                                {
                                    string output = collectedDataArr[i];
                                    if (s_nameRegex.IsMatch(output))
                                    {
                                        Match  match = s_nameRegex.Match(output);
                                        string name  = match.Groups["name"].ToString();
                                        val.Append(@"DBHost_DNSHostName=").Append(name);
                                        flag = true;
                                    }
                                    if ((s_addrRegex.IsMatch(output)) && (flag))
                                    {
                                        Match  match = s_addrRegex.Match(output);
                                        string addr  = match.Groups["address"].ToString();
                                        val.Append(@"<BDNA,1>DBHost_IPAddr=").Append(addr);
                                    }
                                }
                            }
                        }
                    }

                    m_dataRow.Append(m_elementId).Append(',')
                    .Append(m_attributes["lookedUpHosts"]).Append(',')
                    .Append(m_scriptParameters["CollectorId"]).Append(',')
                    .Append(m_taskId).Append(',')
                    .Append(m_databaseTimestamp + m_executionTimer.ElapsedMilliseconds).Append(',')
                    .Append("lookedUpHosts").Append(',')
                    .Append(BdnaDelimiters.BEGIN_TAG).Append(val).Append(BdnaDelimiters.END_TAG);
                }
            }
            catch (Exception ex)
            {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Unhandled exception in WindowsWASHostsLookupScript.  Elapsed time {1}.\n{2}",
                                      m_taskId,
                                      m_executionTimer.Elapsed.ToString(),
                                      ex.ToString());
            }
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script WindowsWASHostsLookupScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode);
            return(new CollectionScriptResults
                       (resultCode, 0, null, null, null, false, m_dataRow.ToString()));
        }
コード例 #44
0
 public float ReadSingle(IRemoteProcess remoteProcess, MemoryMap memoryMap)
 {
     var address = this.GetAddress(remoteProcess, memoryMap);
     return this.readProcessMemory.ReadSingle(remoteProcess.Handle, address);
 }
コード例 #45
0
        /// <summary>
        /// Execute an arbitrary command remotely.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(
            long taskId,
            long cleId,
            long elementId,
            long databaseTimestamp,
            long localTimestamp,
            IDictionary <string, string> attributes,
            IDictionary <string, string> scriptParameters,
            IDictionary <string, object> connection,
            string tftpPath,
            string tftpPath_login,
            string tftpPath_password,
            ITftpDispatcher tftpDispatcher)
        {
            m_taskId         = taskId.ToString();
            m_executionTimer = Stopwatch.StartNew();
            string commandLine = string.Empty;

            //string returnAttribute = null;
            string returnAttribute = string.Empty;

            ResultCodes resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script.",
                                  m_taskId);
            try {
                // Check ManagementScope CIMV
                ManagementScope cimvScope = null;
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("cimv2"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for CIMV namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    cimvScope = connection[@"cimv2"] as ManagementScope;
                    if (!cimvScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to CIMV namespace failed",
                                              m_taskId);
                    }

                    // We have to massage the script parameter set, replace
                    // any keys with a colon by just the part after the colon.
                    Dictionary <string, string> d = new Dictionary <string, string>();

                    foreach (KeyValuePair <string, string> kvp in scriptParameters)
                    {
                        string[] sa = kvp.Key.Split(s_collectionParameterSetDelimiter,
                                                    StringSplitOptions.RemoveEmptyEntries);
                        Debug.Assert(sa.Length > 0);
                        d[sa[sa.Length - 1]] = kvp.Value;
                    }

                    scriptParameters = d;

                    //Check input parameter and set what output attribute to return
                    if (scriptParameters.ContainsKey("qmDisplayData_commandLine"))
                    {
                        commandLine     = scriptParameters[@"qmDisplayData_commandLine"];
                        returnAttribute = "qmDisplayData";
                    }
                    else if (scriptParameters.ContainsKey("channelsStatus_commandLine"))
                    {
                        commandLine     = scriptParameters[@"channelsStatus_commandLine"];
                        returnAttribute = "channelsStatus";
                    }
                    else if (scriptParameters.ContainsKey("channelsDisplayData_commandLine"))
                    {
                        commandLine     = scriptParameters[@"channelsDisplayData_commandLine"];
                        returnAttribute = "channelsDisplayData";
                    }
                    else if (scriptParameters.ContainsKey("queuesDisplayData_commandLine"))
                    {
                        commandLine     = scriptParameters[@"queuesDisplayData_commandLine"];
                        returnAttribute = "queuesDisplayData";
                    }
                    else if (scriptParameters.ContainsKey("channelDetailDisplayData_commandLine"))
                    {
                        commandLine     = scriptParameters[@"channelDetailDisplayData_commandLine"];
                        returnAttribute = "channelDetailDisplayData";
                    }
                    else if (scriptParameters.ContainsKey("queueDetailDisplayData_commandLine"))
                    {
                        commandLine     = scriptParameters[@"queueDetailDisplayData_commandLine"];
                        returnAttribute = "queueDetailDisplayData";
                    }
                    else
                    {
                        resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Missing script parameter.",
                                              m_taskId);
                    }

                    //Check commandLine parameter
                    //if (!scriptParameters.ContainsKey("commandLine"))
                    if (string.IsNullOrEmpty(commandLine))
                    {
                        resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Missing command Line parameter.",
                                              m_taskId);
                    }
                    else
                    {
                        // Both Working directory and temporary need to be collected as part of Windows Credential.
                        // BUG 14064 has been filed to track this problem.
                        // Check working and temporary directory parameter
                        if (!connection.ContainsKey(@"WorkingDirectory") || string.IsNullOrEmpty(connection[@"WorkingDirectory"].ToString()))
                        {
                            connection[@"WorkingDirectory"] = @"%TMP%";
                        }
                        if (!connection.ContainsKey(@"TemporaryDirectory") || string.IsNullOrEmpty(connection[@"TemporaryDirectory"].ToString()))
                        {
                            connection[@"TemporaryDirectory"] = @"%TMP%";
                        }


                        Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                              0,
                                              "Task Id {0}: Attempting to retrieve command output {1}.",
                                              m_taskId,
                                              commandLine);

                        String batchFileContent = this.BuildBatchFile(connection[@"WorkingDirectory"].ToString(),
                                                                      commandLine);
                        String collectedData = "";
                        using (IRemoteProcess rp = RemoteProcess.ExecuteBatchFile(
                                   m_taskId,                            // Task Id to log against.
                                   cimvScope,                           // assuming Remote process uses cimv2 management scope
                                   batchFileContent,                    // batch file
                                   connection,                          // connection dictionary.
                                   tftpPath,
                                   tftpPath_login,
                                   tftpPath_password,
                                   tftpDispatcher)) {
                            //This method will block until the entire remote process operation completes.
                            resultCode = rp.Launch();
                            Lib.Logger.TraceEvent(TraceEventType.Verbose,
                                                  0,
                                                  "Task Id {0}: Batch file executed completed with result code {1}.",
                                                  m_taskId,
                                                  resultCode.ToString());

                            if (resultCode == ResultCodes.RC_SUCCESS)
                            {
                                collectedData = rp.Stdout.ToString();
                                if (string.IsNullOrEmpty(collectedData))
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: Script completed sucessfully with no data to return.",
                                                          m_taskId);
                                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                                }
                                else if (!collectedData.Contains(@"Execution completed"))
                                {
                                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                                          0,
                                                          "Task Id {0}: Exception with batch file return data.\nData returned is shorter than expected, possibly due to transfer failure.\nResult code changed to RC_PROCESSING_EXCEPTION. Partial result: {1}",
                                                          m_taskId,
                                                          collectedData);
                                    resultCode = ResultCodes.RC_REMOTE_COMMAND_EXECUTION_ERROR;
                                }
                                else
                                {
                                    collectedData = collectedData.Substring(0, collectedData.Length - @"Execution completed.\r\n".Length);
                                    string strFormattedString = this.formatCommandResult(collectedData.ToString());

                                    m_outputData.Append(elementId).Append(',')
                                    //.Append(attributes[@"commandResult"]).Append(',')
                                    .Append(attributes[returnAttribute]).Append(',')
                                    .Append(scriptParameters[@"CollectorId"]).Append(',')
                                    .Append(m_taskId).Append(',')
                                    .Append(databaseTimestamp + m_executionTimer.ElapsedMilliseconds).Append(',')
                                    .Append(returnAttribute).Append(',')
                                    //.Append(BdnaDelimiters.BEGIN_TAG).Append(collectedData).Append(BdnaDelimiters.END_TAG);
                                    .Append(BdnaDelimiters.BEGIN_TAG).Append(strFormattedString
                                                                             ).Append(BdnaDelimiters.END_TAG);
                                }
                            }
                            else
                            {
                                Lib.Logger.TraceEvent(TraceEventType.Error,
                                                      0,
                                                      "Task Id {0}: Error during command execution. Elapsed time {1}.  Result code {2}.",
                                                      m_taskId,
                                                      m_executionTimer.Elapsed.ToString(),
                                                      resultCode);
                            }
                        }
                    }
                }
            }
            catch (Exception ex) {
                Lib.Logger.TraceEvent(TraceEventType.Error,
                                      0,
                                      "Task Id {0}: Unhandled exception in Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script.  Elapsed time {1}.\n{2}",
                                      m_taskId,
                                      m_executionTimer.Elapsed.ToString(),
                                      ex.ToString());
            }
            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script Extend_IBM_WindowsWebSphereMQ_Server_QueueManagerStatic_script.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode);
            return(new CollectionScriptResults
                       (resultCode, 0, null, null, null, false, m_outputData.ToString()));
        }
コード例 #46
0
        public void AttachToProcess(IRemoteProcess remoteProcess)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);

            if (remoteProcess.IsAttached)
            {
                return;
            }

            this.remoteProcessCommandService.AttachClientToRemoteProcess(
                new AttachClientToRemoteProcessCommand(remoteProcess.Id));
            this.TryClose();
        }