当前位置:首页 > 行业动态 > 正文

ASPNET下如何使用WScriptShell执行命令及其注意事项?

在ASP.NET中,使用WScriptShell执行命令可以通过以下代码实现:“ csharp,using System.Runtime.InteropServices;public class ExecuteCommand,{, private const string className = "WScript.Shell"; [DllImport("wscript.dll")], static extern IntPtr _CreateObject(string ProgID, IntPtr Unused, IntPtr Context); [DllImport("ole32.dll")], static extern void CoTaskMemFree(IntPtr pv); public static void RunCommand(string command), {, IntPtr shell = _CreateObject(className, IntPtr.Zero, IntPtr.Zero);, if (shell != IntPtr.Zero), {, var shellType = shell.GetTypeFromProgID(className);, dynamic wsh = Activator.CreateInstance(shellType);, wsh.Run(command, 0, false);, CoTaskMemFree(shell);, }, },},

在ASP.NET环境下使用WScript.Shell执行命令,主要可以通过以下两种方式实现:

1、使用Server对象的CreateObject方法

创建ASP.NET页面:创建一个ASP.NET页面,例如Default.aspx,在这个页面中,通过Server对象的CreateObject方法来创建WScript.Shell对象,示例代码如下:

<%@ Page Language="VB" validateRequest="false" aspcompat="true" %>

<script runat="server">

sub runcmd(Src As Object, E As EventArgs)

Dim StrResult As String

Dim CMDShell As Object

CMDShell = Server.CreateObject("WScript.Shell")

StrResult = CMDShell.eXec( CMDPath.Text & " /c " & CMDBox.Text ).stdout.readall

StrResult = Replace(StrResult, "<", "<")

StrResult = Replace(StrResult, ">", ">")

ResultLabel.Text = "<pre>" & StrResult & "</pre>"

end sub

ASPNET下如何使用WScriptShell执行命令及其注意事项?

</script>

<html>

<head><title>WSH.SHell For ASP.NET By lake2</title></head>

<body>

<form runat="server">

"cmd.exe"’s path: <asp:TextBox ID="CMDPath" Width="500" Text="cmd.exe" runat="server" />

<br>

Your Command: <asp:TextBox ID="CMDBox" Width="200" runat="server" />

<asp:Button ID="Button" Text="Run" OnClick="runcmd" runat="server" />

<br>

ASPNET下如何使用WScriptShell执行命令及其注意事项?

<asp:Label ID="ResultLabel" runat="server" />

</form>

</body>

</html>

注意事项:在使用这种方法时,需要确保服务器上已经注册了WScript.Shell组件,不过通常情况下它是系统自带的,所以一般不需要额外注册,要注意ASP.NET与ASP语法上的细微差别,比如在ASP.NET中需要使用runat="server"属性等。

2、将COM组件转化为.NET组件

转换COM组件:利用微软提供的类型库导入器(Type Library Importer),将WScript.Shell组件转换为.NET组件,具体操作是找到WScript.Shell对象所在的文件,通常是%windir%/system32/WSHom.Ocx,然后使用Tlbimp.exe工具进行转换,命令格式为Tlbimp.exe WSHom.Ocx /out:WSHomx.dll,转换完成后,会生成一个WSHomx.dll文件。

配置DLL文件:将生成的WSHomx.dll文件放到Web目录的bin目录下,这样在ASP.NET项目中就可以直接引用该.dll文件来使用WScript.Shell的功能。

编写代码调用:在ASP.NET代码中,通过引用转换后的.dll文件,创建WScript.Shell对象并执行命令,示例代码如下:

<%@ Page Language="VB" validateRequest="false" %>

ASPNET下如何使用WScriptShell执行命令及其注意事项?

<script runat="server">

sub runcmd(Src As Object, E As EventArgs)

Dim StrResult As String

Dim CMDShell As New WSHomx.WshShell

……

end sub

</script>

这两种方式各有优缺点,使用Server对象的CreateObject方法相对简单直接,但可能在某些服务器环境下受到限制;将COM组件转化为.NET组件虽然稍微复杂一些,但可以避免一些潜在的兼容性问题,并且可以更好地与.NET框架集成,在选择使用哪种方式时,需要根据具体的项目需求和服务器环境来决定。