我有一个 ASP.NET 的MVC4网站,我正在尝试在服务器上执行一个进程。 代码如下:
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = ExeLocation,
Arguments = string.Format(""{0}"{1}", ScriptLocation, Arguments),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = AppDir,
CreateNoWindow = true,
UserName = ExeUsername,
Password = ExePassword,
Domain = ExeDomain
};
using (Process process = Process.Start(startInfo))
{
using (StreamReader reader = process.StandardOutput)
{
output = reader.ReadToEnd();
}
using (StreamReader reader = process.StandardError)
{
error = reader.ReadToEnd();
}
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception(string.IsNullOrEmpty(output) ? error : output);
}
}
这在Visual Studio中的本地计算机上工作正常,但是当我部署到服务器(W2K12(时,我收到以下错误:
Access is denied
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
我在服务器上的管理员组和IIS_IUSRS组中都有ExeUsername
引用的帐户。
应用程序池作为不同的帐户运行(因此需要分配特定帐户来运行进程(,该帐户也是服务器上管理员和IIS_IUSRS的成员。
当我登录到服务器并ExeUsername
运行命令提示符时,我能够执行该过程,因此问题必须与从IIS执行有关。
还有什么可能阻止此访问?
- 右键单击应用程序池
- 点击高级设置
- 身份
- 自定义帐户
- 设置用户名和密码
如果您有域,请小心使用域\用户名作为用户名
以及访问部署文件夹。
我会尝试不同的方法。首先模拟自定义用户(有权运行命令的用户(,然后在模拟用户的上下文中启动进程:
SafeAccessTokenHandle safeAccessTokenHandle;
bool returnValue = LogonUser(ExeUsername, ExeDomain, ExePassword,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeAccessTokenHandle);
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
{
var startInfo = new ProcessStartInfo()
{
FileName = ExeLocation,
Arguments = string.Format(""{0}"{1}", ScriptLocation, Arguments),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = AppDir,
CreateNoWindow = true,
UserName = ExeUsername,
Password = ExePassword,
Domain = ExeDomain
};
using (Process process = Process.Start(startInfo))
{
using (StreamReader reader = process.StandardOutput)
{
output = reader.ReadToEnd();
}
using (StreamReader reader = process.StandardError)
{
error = reader.ReadToEnd();
}
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception(string.IsNullOrEmpty(output) ? error : output);
}
}
);
LogonUser 方法如下所示:
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain,
String lpszPassword, int dwLogonType, int dwLogonProvider,
out SafeAccessTokenHandle phToken);
有关在 .NET 中模拟的详细信息,请参阅:https://learn.microsoft.com/en-gb/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=netframework-4.7.2
也许使用它可以帮助你。
ProcessStartInfo startInfo = new ProcessStartInfo()
{
//...
UseShellExecute = true,
Verb = "runas"
};
如果遇到错误,也可以检查一下。