【发布时间】:2018-04-29 20:59:46
【问题描述】:
我希望能够以其他用户身份从 ASP.NET 应用程序运行 powershell 脚本。我可以成功运行 powershell 命令并查看输出,但我无法弄清楚如何以其他用户身份执行它。 我已遵循本指南:
http://jeffmurr.com/blog/?p=142
这只是一个文本框,我在其中输入我的 powershell-command,输出将显示在另一个文本框中。
我创建了一个新的 IIS 站点和一个以域用户身份运行的应用程序池,并将新站点与该池相关联。我可以看到唯一存在的 w3wp.exe 进程作为我在池中指定的域用户运行。如果我运行命令:
write-output $Env:USERNAME
它返回系统帐户用户名“SERVERNAME$”。 有人知道为什么吗?我错过了什么?有没有其他方法可以达到同样的效果?
代码...
HTML:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr><td> </td><td><h1 align="left">PowerShell Command Harness</h1></td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td>PowerShell Command</td></tr>
<tr><td>
<br />
</td><td>
<asp:TextBox ID="Input" runat="server" TextMode="MultiLine" Width="433px" Height="73px" ></asp:TextBox>
</td></tr>
<tr><td>
</td><td>
<asp:Button ID="ExecuteCode" runat="server" Text="Execute" Width="200" onclick="ExecuteCode_Click" />
</td></tr>
<tr><td> </td><td><h3>Result</h3></td></tr>
<tr><td>
</td><td>
<asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="700" Height="200" runat="server"></asp:TextBox>
</td></tr>
</table>
</div>
</form>
</body>
</html>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;
namespace PowerShellExecution
{
public partial class Default : System.Web.UI.Page
{
public TextBox ResultBox;
public TextBox Input;
protected void Page_Load(object sender, EventArgs e)
{
ResultBox = (TextBox)this.FindControl("ResultBox");
Input = (TextBox)this.FindControl("Input");
}
protected void ExecuteCode_Click(object sender, EventArgs e)
{
// Clean the Result TextBox
ResultBox.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
shell.Commands.AddScript(Input.Text);
// shell.Commands.AddScript("C:\\TestSite\\test.ps1");
// Execute the script
var results = shell.Invoke();
// display results, with BaseObject converted to string
// Note : use |out-string for console-like output
if (results.Count > 0)
{
// We use a string builder ton create our result text
var builder = new StringBuilder();
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
// Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
}
}
}
【问题讨论】:
标签: c# asp.net powershell iis