Exemplo n.º 1
0
 public override bool ExecuteAsUser(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, string user, SecureString password, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
 {
     if (password == null)
     {
         string c = string.Format("-n -u {0} -s {1} {2}", user, command, arguments);
         return(this.Execute("sudo", c, out process_status, out process_output, out process_error));
     }
     else
     {
         Error("Executing commands as a different operating system user with a required password in a Docker container environment is not currently supported.");
         process_error  = string.Empty;
         process_output = string.Empty;
         process_status = ProcessExecuteStatus.Error;
         return(false);
     }
 }
Exemplo n.º 2
0
 public override bool Execute(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
 {
     process_output = string.Empty;
     process_error  = string.Empty;
     try
     {
         process_output = this.Manager.RunCmd(command, arguments.Split(' ').ToList());
         process_status = ProcessExecuteStatus.Completed;
         return(true);
     }
     catch (Exception e)
     {
         process_error  = e.Message;
         process_status = ProcessExecuteStatus.Error;
         return(false);
     }
 }
Exemplo n.º 3
0
 public override bool Execute(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error,
                              Dictionary <string, string> env = null, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
 {
     this.Debug("Executing command on Windows host {2} {0} {1}...", command, arguments.Replace('\t', ' '), this.ComputerName);
     process_output = string.Empty;
     process_error  = string.Empty;
     try
     {
         process_output = this.Manager.RunCmd(command, arguments.Split('\t'));
         process_status = ProcessExecuteStatus.Completed;
         Debug("Execute command {0} {1} returned {2}.", command, arguments.Replace('\t', ' '), process_output);
         return(true);
     }
     catch (Exception e)
     {
         process_error = e.Message;
         Error(e, "Execute command {0} {1} on Windows host {2} failed", command, arguments.Replace('\t', ' '), this.ComputerName);
         process_status = ProcessExecuteStatus.Error;
         return(false);
     }
 }
Exemplo n.º 4
0
        public bool ExecuteCommand(string command, string arguments, out string output, bool report_errors = true, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation    caller = new CallerInformation(memberName, fileName, lineNumber);
            ProcessExecuteStatus process_status = ProcessExecuteStatus.Unknown;
            string process_output, process_error;
            bool   r = this.Execute(command, arguments, out process_status, out process_output, out process_error);

            if (r)
            {
                output = process_output.Trim();
                Debug(caller, "The command {0} {1} executed successfully. Output: {2}", command, arguments, output);
                return(true);
            }
            else
            {
                output = process_output + process_error;
                if (report_errors && !string.IsNullOrEmpty(output))
                {
                    Error(caller, "The command {0} {1} did not execute successfully. Error: {2}", command, arguments, output);
                }
                return(false);
            }
        }
        public bool LocalExecute(string command, string arguments,
                                 out ProcessExecuteStatus process_status, out string process_output, out string process_error, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            FileInfo         cf = new FileInfo(command);
            int?             process_exit_code = null;
            StringBuilder    process_out_sb    = new StringBuilder();
            StringBuilder    process_err_sb    = new StringBuilder();
            ProcessStartInfo psi = new ProcessStartInfo(command);

            psi.Arguments              = arguments;
            psi.CreateNoWindow         = true;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute        = false;
            if (cf.Exists)
            {
                psi.WorkingDirectory = cf.Directory.FullName;
            }
            Process p = new Process();

            p.EnableRaisingEvents = true;
            p.StartInfo           = psi;
            p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                if (!String.IsNullOrEmpty(e.Data))
                {
                    process_out_sb.AppendLine(e.Data);
                    OutputDataReceived?.Invoke(e.Data);
                }
            };
            p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                if (!String.IsNullOrEmpty(e.Data))
                {
                    process_err_sb.AppendLine(e.Data);
                    OutputErrorReceived?.Invoke(e.Data);
                }
            };
            try
            {
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();
                process_exit_code = p.ExitCode;
                p.Close();
            }
            catch (Win32Exception e)
            {
                if (e.Message == "The system cannot find the file specified")
                {
                    process_status = ProcessExecuteStatus.FileNotFound;
                    process_err_sb.AppendLine(e.Message);
                    return(false);
                }
            }
            finally
            {
                process_output = process_out_sb.ToString();
                process_error  = process_err_sb.ToString();
                p.Dispose();
            }

            if ((process_exit_code.HasValue && process_exit_code.Value != 0))
            {
                process_status = ProcessExecuteStatus.Error;
                return(false);
            }
            else if ((process_exit_code.HasValue && process_exit_code.Value == 0))
            {
                process_status = ProcessExecuteStatus.Completed;
                return(true);
            }
            else
            {
                process_status = ProcessExecuteStatus.Unknown;
                return(false);
            }
        }
Exemplo n.º 6
0
 public override bool ExecuteAsUser(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, string user, SecureString password, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 7
0
        public override bool Execute(string command, string arguments,
                                     out ProcessExecuteStatus process_status, out string process_output, out string process_error, Dictionary <string, string> env = null,
                                     Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller           = new CallerInformation(memberName, fileName, lineNumber);
            FileInfo          cf               = new FileInfo(command);
            int?             process_exit_code = null;
            StringBuilder    process_out_sb    = new StringBuilder();
            StringBuilder    process_err_sb    = new StringBuilder();
            ProcessStartInfo psi               = new ProcessStartInfo(command);

            psi.Arguments              = arguments;
            psi.CreateNoWindow         = true;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            psi.UseShellExecute        = false;
            if (env != null && env.Count > 0)
            {
                foreach (KeyValuePair <string, string> kv in env)
                {
                    psi.EnvironmentVariables.Add(kv.Key, kv.Value);
                }
            }
            if (cf.Exists)
            {
                psi.WorkingDirectory = cf.Directory.FullName;
            }
            Process p = new Process();

            p.EnableRaisingEvents = true;
            p.StartInfo           = psi;
            p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                if (!String.IsNullOrEmpty(e.Data))
                {
                    process_out_sb.AppendLine(e.Data);
                    OutputDataReceived?.Invoke(e.Data);
                }
            };
            p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
            {
                if (!String.IsNullOrEmpty(e.Data))
                {
                    process_err_sb.AppendLine(e.Data);
                    OutputErrorReceived?.Invoke(e.Data);
                }
            };
            try
            {
                Debug("Executing {0} {1}...", command, arguments);
                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                p.WaitForExit();
                process_exit_code = p.ExitCode;
                p.Close();
            }
            catch (Win32Exception e)
            {
                if (e.Message == "The system cannot find the file specified")
                {
                    process_status = ProcessExecuteStatus.FileNotFound;
                    process_err_sb.AppendLine(e.Message);
                    return(false);
                }
                else
                {
                    Debug(caller, "Execute {0} {1} threw exception {2}.", command, arguments, e.Message);
                    process_status = ProcessExecuteStatus.Error;
                    process_error  = e.Message;
                    return(false);
                }
            }
            finally
            {
                process_output = process_out_sb.ToString();
                process_error  = process_err_sb.ToString();
                p.Dispose();
            }

            if ((process_exit_code.HasValue && process_exit_code.Value != 0))
            {
                Debug(caller, "Execute {0} {1} returned exit code {2}.", command, arguments, process_exit_code.Value);
                process_status = ProcessExecuteStatus.Error;
                return(false);
            }
            else if ((process_exit_code.HasValue && process_exit_code.Value == 0))
            {
                Debug(caller, "Execute {0} {1} returned exit code {2}.", command, arguments, process_exit_code.Value);
                process_status = ProcessExecuteStatus.Completed;
                return(true);
            }
            else
            {
                process_status = ProcessExecuteStatus.Unknown;
                return(false);
            }
        }
Exemplo n.º 8
0
        public override bool ExecuteAsUser(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, string user, SecureString password, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);

            if (this.OS.Platform == PlatformID.Win32NT)
            {
                string domain_name = Environment.UserDomainName;
                if (user.Contains("\\"))
                {
                    string[] u = user.Split('\\');
                    domain_name = u[0];
                    user        = u[1];
                }
                FileInfo         cf = new FileInfo(command);
                int?             process_exit_code = null;
                StringBuilder    process_out_sb    = new StringBuilder();
                StringBuilder    process_err_sb    = new StringBuilder();
                ProcessStartInfo psi = new ProcessStartInfo(command);
                psi.UserName               = user;
                psi.Password               = password;
                psi.Domain                 = domain_name;
                psi.Arguments              = arguments;
                psi.CreateNoWindow         = true;
                psi.RedirectStandardError  = true;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardInput  = true;
                psi.UseShellExecute        = false;
                if (cf.Exists)
                {
                    psi.WorkingDirectory = cf.Directory.FullName;
                }
                Process p = new Process();
                p.EnableRaisingEvents = true;
                p.StartInfo           = psi;
                p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        process_out_sb.AppendLine(e.Data);
                        OutputDataReceived?.Invoke(e.Data);
                    }
                };
                p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        process_err_sb.AppendLine(e.Data);
                        OutputErrorReceived?.Invoke(e.Data);
                    }
                };
                try
                {
                    Debug("Executing {0} {1} as user {2}...", command, arguments, user);
                    p.Start();
                    p.BeginErrorReadLine();
                    p.BeginOutputReadLine();
                    p.WaitForExit();
                    process_exit_code = p.ExitCode;
                    p.Close();
                }
                catch (Win32Exception e)
                {
                    if (e.Message == "The system cannot find the file specified")
                    {
                        process_status = ProcessExecuteStatus.FileNotFound;
                        process_err_sb.AppendLine(e.Message);
                        return(false);
                    }
                    else
                    {
                        Debug(caller, "Execute {0} {1} threw exception {2}.", command, arguments, e.Message);
                        process_status = ProcessExecuteStatus.Error;
                        process_error  = e.Message;
                        return(false);
                    }
                }
                finally
                {
                    process_output = process_out_sb.ToString();
                    process_error  = process_err_sb.ToString();
                    p.Dispose();
                }

                if ((process_exit_code.HasValue && process_exit_code.Value != 0))
                {
                    Debug(caller, "Execute {0} {1} returned exit code {2}.", command, arguments, process_exit_code.Value);
                    process_status = ProcessExecuteStatus.Error;
                    return(false);
                }
                else if ((process_exit_code.HasValue && process_exit_code.Value == 0))
                {
                    Debug(caller, "Execute {0} {1} returned exit code {2}.", command, arguments, process_exit_code.Value);
                    process_status = ProcessExecuteStatus.Completed;
                    return(true);
                }
                else
                {
                    process_status = ProcessExecuteStatus.Unknown;
                    return(false);
                }
            }
            else
            {
                if (password == null)
                {
                    string c = string.Format("-n -u {0} -s {1} {2}", user, command, arguments);
                    return(this.Execute("sudo", c, out process_status, out process_output, out process_error));
                }
                else
                {
                    Error("Executing commands as a different operating system user with a required password in the local environment is not suppported on *nix. Use the su or sudo commands to run DevAudit as the required operating system user.");
                    process_error  = string.Empty;
                    process_output = string.Empty;
                    process_status = ProcessExecuteStatus.Error;
                    return(false);

                    /*
                     * string c = string.Format("-n -u {0} -s {1} {2}", user, command, arguments);
                     * return this.Execute("sudo", c, out process_status, out process_output, out process_error);
                     *
                     *  Error("Executing commands as a different operating system user with a required password in the local environment is not suppported on *nix. Use the su or sudo commands to run DevAudit as the required operating system user.");
                     * process_error = string.Empty;
                     * process_output = string.Empty;
                     * process_status = ProcessExecuteStatus.Error;
                     * return false;
                     *
                     *
                     *
                     * //string args = string.Format("-c \"echo CMD_START && {0} {1} && echo CMD_SUCCESS || echo CMD_ERROR\" {2} || echo CMD_ERROR", command, arguments, user);
                     *
                     * string args = string.Format("-S -u {0} -s {1} {2} && echo CMD_SUCCESS || echo CMD_ERROR", user, command, arguments);
                     * ProcessStartInfo psi = new ProcessStartInfo("sudo");
                     * psi.Arguments = args;
                     * psi.CreateNoWindow = true;
                     * psi.RedirectStandardError = true;
                     * psi.RedirectStandardOutput = true;
                     * psi.RedirectStandardInput = true;
                     * psi.UseShellExecute = false;
                     * Process p = new Process();
                     * p.EnableRaisingEvents = false;
                     * p.StartInfo = psi;
                     * Debug("Executing command sudo {0}.", args);
                     * ProcessSpawnable s = new ProcessSpawnable(p);
                     * Session cmd_session = Expect.Spawn(s, this.LineTerminator);
                     * IResult r = cmd_session.Expect.Contains("password for", null);
                     * if (r.IsMatch)
                     * {
                     *  s.Write(ToInsecureString(password) + this.LineTerminator);
                     * }
                     * else
                     * {
                     *  if (!p.HasExited) p.Close();
                     *  p.Dispose();
                     *  process_status = ProcessExecuteStatus.Error;
                     *  process_output = r.Text;
                     *  process_error = string.Empty;
                     *  Error(caller, "Unexpected response from server attempting to execute sudo {0}: {1}", args, process_output);
                     *  return false;
                     * }
                     * List<IResult> cmd_result = cmd_session.Expect.ContainsEither("CMD_SUCCESS", null, "CMD_ERROR", null);
                     * if (!p.HasExited) p.Close();
                     * p.Dispose();
                     * if (cmd_result.First().IsMatch)
                     * {
                     *  process_status = ProcessExecuteStatus.Completed;
                     *  string o = (string)cmd_result.First().Result;
                     *  process_output = o.Replace("CMD_START", string.Empty).Replace("CMD_SUCCESS", string.Empty);
                     *  Debug("Execute command sudo {0} returned: {1}", args, process_output);
                     *  process_error = string.Empty;
                     *  return true;
                     * }
                     * else
                     * {
                     *  process_status = ProcessExecuteStatus.Error;
                     *  string o = (string)cmd_result.Last().Result;
                     *  process_error = o.Replace("CMD_ERROR", string.Empty);
                     *  Error("Could not execute command sudo {0}. Error: {1}", args, process_error);
                     *  process_output = string.Empty;
                     *  return false;
                     * }
                     */
                    /*
                     * CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);
                     * List<string> args = arguments.Split('\t').ToList();
                     * string cmd = command;
                     * foreach (string a in args)
                     * {
                     *  cmd += " \"" + a + "\"";
                     * }
                     * cmd = "\"" + cmd + "\"";
                     * string shell_uri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
                     * ICollection<PSObject> result = null;
                     * PSCredential credential = new PSCredential(user, pass);
                     * WSManConnectionInfo ci = new WSManConnectionInfo() { Credential = credential };
                     * using (Runspace r = RunspaceFactory.CreateRunspace(ci))
                     * {
                     *  r.Open();
                     *  using (PowerShell ps = PowerShell.Create())
                     *  {
                     *      ps.Runspace = r;
                     *      ps.AddCommand("cmd.exe");
                     *      ps.AddParameter("/c", cmd);
                     *      result = ps.Invoke();
                     *
                     *  }
                     * }
                     */
                }
            }
        }
Exemplo n.º 9
0
        public override bool ExecuteAsUser(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, string user, SecureString password, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);

            if (!this.IsConnected)
            {
                throw new InvalidOperationException("The SSH session is not connected.");
            }
            process_status = ProcessExecuteStatus.Unknown;
            process_output = "";
            process_error  = "";
            string c;

            if (password == null)
            {
                c = string.Format("-n -u {0} -s {1} {2}", user, command, arguments);
                return(this.Execute("sudo", c, out process_status, out process_output, out process_error));
            }
            StringBuilder shell_data = new StringBuilder();
            ShellStream   stream     = this.SshClient.CreateShellStream("dumb", 0, 0, 800, 600, 1024, new Dictionary <TerminalModes, uint> {
                { TerminalModes.ECHO, 0 }
            });

            stream.DataReceived += (s, d) => shell_data.Append(Encoding.UTF8.GetString(d.Data));
            c = string.Format("PAGER=cat su -c \"echo CMD_START && {0} {1} && echo CMD_SUCCESS || echo CMD_ERROR\" {2} || echo CMD_ERROR", command, arguments, user);
            byte[]    b  = Encoding.UTF8.GetBytes(c + this.LineTerminator);
            Stopwatch cs = new Stopwatch();

            cs.Start();
            IAsyncResult wr = stream.BeginWrite(b, 0, b.Length, new AsyncCallback(SshStreamWriteAsyncCallback), new KeyValuePair <string, ShellStream>(c, stream));

            stream.EndWrite(wr);
            bool got_password_prompt = false;

            ExpectAction[] got_password_prompt_action =
            {
                new ExpectAction("Password:"******"Unexpected response from server attempting to execute {0}: {1}", c, shell_data);
                return(false);
            }
            stream.EndWrite(wr);
            bool   cmd_success = false;
            string cmd_output  = string.Empty;

            ExpectAction[] cmd_actions =
            {
                new ExpectAction("CMD_ERROR",   (o) =>
                {
                    cmd_output  = o.Replace("CMD_ERROR", string.Empty);
                    cmd_success = false;
                }),
                new ExpectAction("CMD_SUCCESS", (o) =>
                {
                    cmd_output  = o.Replace("CMD_SUCCESS", string.Empty).Replace("CMD_START", string.Empty);
                    cmd_success = true;
                }),
            };
            er = stream.BeginExpect(new TimeSpan(0, 0, 5), new AsyncCallback(SshExpectAsyncCallback), new KeyValuePair <string, Stopwatch>(c, cs), cmd_actions);
            stream.EndExpect(er);
            if (!cmd_success)
            {
                process_status = ProcessExecuteStatus.Error;
                Debug(caller, "Execute {0} {1} returned non-zero exit code. Output: {2}.", command, arguments, cmd_output);
                return(false);
            }
            else
            {
                Debug(caller, "Execute {0} {1} returned zero exit code. Output: {2}.", command, arguments, cmd_output);
                process_status = ProcessExecuteStatus.Completed;
                process_output = cmd_output.Trim('\r', '\n');
                return(true);
            }
        }
Exemplo n.º 10
0
        public override bool Execute(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, Dictionary <string, string> env = null,
                                     Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);

            if (!this.IsConnected)
            {
                throw new InvalidOperationException("The SSH session is not connected.");
            }
            process_status = ProcessExecuteStatus.Unknown;
            process_output = "";
            process_error  = "";
            if (env != null && env.Count > 0)
            {
                StringBuilder vars = new StringBuilder();
                foreach (KeyValuePair <string, string> kv in env)
                {
                    vars.AppendFormat("{0}={1} ", kv.Key, kv.Value);
                }
                command = vars.ToString() + command;
            }
            SshCommand cmd = this.SshClient.CreateCommand(command + " " + arguments);

            Debug("Executing command {0} {1}.", command, arguments);
            Stopwatch cs = new Stopwatch();

            cs.Start();
            CommandAsyncResult result;

            try
            {
                result = cmd.BeginExecute(new AsyncCallback(SshCommandAsyncCallback), new KeyValuePair <SshCommand, Stopwatch>(cmd, cs)) as CommandAsyncResult;
                cmd.EndExecute(result);
            }
            catch (SshConnectionException sce)
            {
                Error(caller, sce, "SSH connection error attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (SshOperationTimeoutException te)
            {
                Error(caller, te, "SSH connection timeout attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (SshException se)
            {
                Error(caller, se, "SSH error attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (Exception e)
            {
                Error(caller, e, "Error attempting to execute over SSH {0} {1}.", command, arguments);
                return(false);
            }
            KeyValuePair <SshCommand, Stopwatch> s = (KeyValuePair <SshCommand, Stopwatch>)result.AsyncState;

            process_output = s.Key.Result.Trim();
            process_error  = s.Key.Error.Trim();
            if (s.Value.IsRunning)
            {
                s.Value.Stop();
            }
            process_output = cmd.Result.Trim();
            process_error  = process_output + cmd.Error.Trim();
            if (cmd.ExitStatus == 0)
            {
                Debug(caller, "Execute {0} returned zero exit code. Output: {1}.", command + " " + arguments, process_output);
                process_status = ProcessExecuteStatus.Completed;
                cmd.Dispose();
                return(true);
            }
            else
            {
                process_status = ProcessExecuteStatus.Error;
                Debug(caller, "Execute {0} returned non-zero exit code {2}. Error: {1}.", command + " " + arguments, process_error, cmd.ExitStatus);
                cmd.Dispose();
                return(false);
            }
        }
Exemplo n.º 11
0
 public abstract bool Execute(string command, string arguments,
                              out ProcessExecuteStatus process_status, out string process_output, out string process_error, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0);
Exemplo n.º 12
0
        public override bool ExecuteAsUser(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, string user, SecureString password, Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);

            this.Debug("Executing command {0} {1} on Windows host {2} as user {3}...", command, arguments.Replace('\t', ' '), this.ComputerName, user);
            List <string> args = arguments.Split('\t').ToList();
            string        cmd  = command;

            foreach (string a in args)
            {
                cmd += " \"" + a + "\"";
            }
            //cmd = "\"" + cmd + "\"";
            //string shell_uri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
            ICollection <PSObject> result             = null;
            PSCredential           machine_credential = new PSCredential(this.User, this.Pass);
            WSManConnectionInfo    ci = new WSManConnectionInfo()
            {
                Credential              = machine_credential,
                ComputerName            = this.Manager.IpAddress,
                AuthenticationMechanism = AuthenticationMechanism.Default
            };

            using (Runspace r = RunspaceFactory.CreateRunspace(ci))
            {
                try
                {
                    r.Open();
                }
                catch (Exception e)
                {
                    Error(e, "There was an error connecting to Windows host {0} as user {1}.", ci.ComputerName, user);
                    process_status = ProcessExecuteStatus.Error;
                    process_output = string.Empty;
                    process_error  = e.Message;
                    return(false);
                }
                using (PowerShell ps = PowerShell.Create())
                {
                    ps.Runspace = r;
                    PSCredential program_credential = new PSCredential(user.Contains("\\") ? user : this.ComputerName + "\\" + user, password);
                    r.SessionStateProxy.SetVariable("Credential", program_credential);
                    ps.AddScript("$session = New-PSSession -Credential $Credential -ComputerName localhost" + Environment.NewLine + "Invoke-Command -Session $session -ScriptBlock {&" + cmd + "}");
                    result = ps.Invoke();
                    if (result != null && result.Count > 0)
                    {
                        process_output = (string)result.First().BaseObject;
                        process_error  = string.Empty;
                        process_status = ProcessExecuteStatus.Completed;
                        return(true);
                    }
                    else if (ps.HadErrors)
                    {
                        this.Error("Executing command {0} failed.", cmd);
                        StringBuilder errors = new StringBuilder();
                        foreach (ErrorRecord e in ps.Streams.Error)
                        {
                            if (e.Exception != null)
                            {
                                this.Error(e.Exception);
                                errors.AppendLine(e.Exception.Message);
                            }
                            if (e.ErrorDetails != null)
                            {
                                this.Error(e.ErrorDetails.Message);
                                errors.AppendLine(e.ErrorDetails.Message);
                            }
                        }
                        process_output = string.Empty;
                        process_error  = errors.ToString();
                        process_status = ProcessExecuteStatus.Error;
                        return(false);
                    }
                    else
                    {
                        this.Error("Executing command {0} returned unknown status.", cmd);
                        process_output = result != null && result.Count > 0 ? process_output = (string)result.First().BaseObject : string.Empty;
                        process_error  = string.Empty;
                        process_status = ProcessExecuteStatus.Unknown;
                        return(false);
                    }
                }
            }
        }