【问题标题】:Execute cmd command on windows server with web app [duplicate]使用Web应用程序在Windows服务器上执行cmd命令[重复]
【发布时间】:2020-01-13 22:48:40
【问题描述】:

我在装有 windows server 2008 的计算机上的 IIS 上托管了一个 web 应用程序 c#,我通过 C# 在 windows server cmd 上运行了一个命令,但它不起作用,我在我的计算机上本地尝试了它并且命令能用,不知道为什么在有windows server的电脑上不能用,我用这个源码,我放了个log但是没有报错。

        protected void btnReboot_Click(object sender, EventArgs e)
        {
            try
            {

                //StartShutDown("-l");
                StartShutDown("-f -r -t 5");

                Log2("MNS OK");
            }
            catch (Exception ex)
            {
                Log2("MNS ERROR  " + ex.ToString());
            }

        }
        private static void StartShutDown(string param)
        {
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.FileName = "cmd";
            proc.WindowStyle = ProcessWindowStyle.Hidden;
            proc.Arguments = "/C shutdown " + param;
            Process.Start(proc);
        }

【问题讨论】:

  • Change /C in /K 并注释掉 proc.WindowStyle 现在你应该可以看到命令打开的控制台窗口,你可以看看是否有一条错误消息
  • @Steve 它没有打开任何命令窗口
  • 你注释掉隐藏命令窗口的那一行了吗?
  • 您是否能够登录您的服务器并尝试使用启动进程所用的同一帐户打开命令窗口?
  • @Steve 在服务器上如果可以手动打开命令窗口并且我注释掉 proc.WindowStyle 行

标签: c# .net visual-studio iis-7


【解决方案1】:

您实际上可以从redirecting the standard error 启动的进程中捕获错误输出。一个例子是这样的:

private static void StartShutDown(string param)
{
    Process p = new Process();
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true; // You need to set this
    p.StartInfo.UseShellExecute = false; 

    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.Arguments = "/C shutdown " + param;
    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    p.Start();

    string stdoutx = p.StandardOutput.ReadToEnd();         
    string stderrx = p.StandardError.ReadToEnd(); // here is where you get the error output string        
    p.WaitForExit();

    Console.WriteLine("Exit code : {0}", p.ExitCode);
    Console.WriteLine("Stdout : {0}", stdoutx);
    Console.WriteLine("Stderr : {0}", stderrx);
}

一旦你有了 Stderr,你就可以检查它的内容,如果它不为空,那么你就知道发生了错误。

【讨论】:

  • 在 Stderr 行它显示我访问被拒绝
猜你喜欢
  • 1970-01-01
  • 2013-03-10
  • 2012-12-07
  • 1970-01-01
  • 2017-09-26
  • 2012-11-20
  • 2013-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多