【问题标题】:Run "ping" command when link button is clicked单击链接按钮时运行“ping”命令
【发布时间】:2015-12-08 16:19:35
【问题描述】:

我试图在单击链接按钮时弹出 Windows 命令提示并运行 ping 命令。链接按钮看起来像:

<asp:LinkButton runat="server" ID="lbFTPIP" OnCommand="lbFTPIP_OnCommand" CommandArgumnet="1.2.3.4" Text="1.2.3.4"/>

我在 OnCommand 上试过这个:

protected void lbFTPIP_OnCommand(object sender, CommandEventArgs e)
{
    string sFTPIP = e.CommandArgument.ToString();
    string sCmdText = @"ping -a " + sFTPIP;
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.Arguments = sCmdText; 
    p.StartInfo.RedirectStandardOutput = false;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = false;
    p.Start();
}

当我单击链接时,它会打开命令提示符但不显示或执行命令,它只显示当前目录。不确定我在这里缺少什么。

它是网页的一部分,如果这有影响的话。

【问题讨论】:

  • 关于cmd 命令:您需要将/C(或/K)作为第一个参数(在ping 之前)以表示您要运行命令。跨度>
  • 就是这样!谢谢你。我错过了/ C。有没有办法让用户关闭窗口?现在它在显示对 ping 命令的响应后关闭> 我尝试了 p.WaitForExit() 但它并不好。

标签: c# asp.net command-line


【解决方案1】:

要打开控制台并立即运行命令,您需要使用/C/K 开关:

// Will run the command and then close the console.
string sCmdText = @"/C ping -a " + sFTPIP;

// Will run the command and keep the console open.
string sCmdText = @"/K ping -a " + sFTPIP;

如果您想设置“按任意键”,可以添加PAUSE

// Will run the command, wait for the user press a key, and then close the console.
string sCmdText = @"/C ping -a " + sFTPIP + " & PAUSE";

编辑:

最好重定向您的输出,然后单独显示结果:

Process p = new Process();
// No need to use the CMD processor - just call ping directly.
p.StartInfo.FileName = "ping.exe";
p.StartInfo.Arguments = "-a " + sFTPIP; 
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();

var output = p.StandardOutput.ReadToEnd();

// Do something the output.

【讨论】:

  • 谢谢。 /K 完美。当我在服务器上尝试这个时,它工作得很好。当我使用 IE 或 Chrome 从我的工作站发布站点并运行它时,不显示命令提示符窗口。我在不同的机器上试过,得到了同样的东西。
  • @NoBullMan - 由于浏览器的保护级别,您可能无法从最终用户计算机启动。如果浏览器可以在您的计算机上打开控制台并运行命令,那将是一个巨大的安全风险。这种类型的行为(为什么它在您的服务器上起作用)将更多用于“控制面板”类型的应用程序。如果要查看输出,则应重定向输出。我会用这个更新答案。
  • 谢谢。我会尝试寻找其他方式让用户知道他的 ping 测试是否有效;可能在静默模式下运行命令,而不打开命令提示符窗口,并获取结果并在 Ajax 弹出控件中将其显示给用户。它是一个内网应用程序。如果我不指定 /C 或 /K 是否会阻止命令提示符打开?
  • 当我重定向输出时在服务器中工作正常。
  • @NoBullMan - 抱歉,我触发了等待和捕获命令。答案已更新。上面的命令应该在服务器上运行,所以只要应用程序池能够运行 shell 命令,那么 output 变量应该包含 ping 的结果,您可以将其显示给用户。
【解决方案2】:

不需要执行cmd.exe,直接执行ping.exe即可。

string sCmdText = @"-a " + sFTPIP;
Process p = new Process();
p.StartInfo.FileName = "ping.exe";
p.StartInfo.Arguments = sCmdText;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = false;
p.Start();

另外,除非您打算重定向输出,否则不要设置 UseShellExecute = false,我很惊讶您没有这样做。

【讨论】:

  • 用户希望能够单击 IP 地址链接并确保其响应。但是,如果我想重定向输出,我该怎么做呢?
【解决方案3】:

首先你有一些奇怪的东西CommandArgumnet="1.2.3.4" 拼错了。另一件事是 /C 和 ping 之前的空格。

【讨论】:

  • 这只是一个示例。实际IP地址为真实地址。
  • 我的意思是你有CommandArgumnet而不是CommandArgument
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
相关资源
最近更新 更多