我有一个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)
我在服务器上的Administrators和IIS_IUSRS组中都有ExeUsername
引用的帐户。
应用程序池作为另一个帐户运行(因此需要分配特定帐户来运行该进程),该帐户也是服务器上Administrators和IIS_IUSRS的成员。
当我登录服务器并以ExeUsername
运行命令提示符时,我能够执行该过程,因此该问题必须与从IIS执行相关。
还有什么可以阻止这种访问?
如果您有域名,请小心使用domain \ username作为用户名 并且还可以访问部署文件夹。
我会尝试不同的方法。首先模拟自定义用户(具有运行命令权限的用户),然后在模拟用户的上下文中启动进程:
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://docs.microsoft.com/en-gb/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=netframework-4.7.2
也许使用它可以帮助你。
ProcessStartInfo startInfo = new ProcessStartInfo()
{
//...
UseShellExecute = true,
Verb = "runas"
};
如果您收到错误,也可以查看this。