http://download.csdn.net/download/lai444132348/9730266

using System;
using System.Runtime.InteropServices; namespace murrayju.ProcessExtensions
{
public static class ProcessExtensions
{
#region Win32 Constants private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
private const int CREATE_NO_WINDOW = 0x08000000; private const int CREATE_NEW_CONSOLE = 0x00000010; private const uint INVALID_SESSION_ID = 0xFFFFFFFF;
private static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; #endregion #region DllImports [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
private static extern bool CreateProcessAsUser(
IntPtr hToken,
String lpApplicationName,
String lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandle,
uint dwCreationFlags,
IntPtr lpEnvironment,
String lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation); [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
private static extern bool DuplicateTokenEx(
IntPtr ExistingTokenHandle,
uint dwDesiredAccess,
IntPtr lpThreadAttributes,
int TokenType,
int ImpersonationLevel,
ref IntPtr DuplicateTokenHandle); [DllImport("userenv.dll", SetLastError = true)]
private static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit); [DllImport("userenv.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment); [DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hSnapshot); [DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId(); [DllImport("Wtsapi32.dll")]
private static extern uint WTSQueryUserToken(uint SessionId, ref IntPtr phToken); [DllImport("wtsapi32.dll", SetLastError = true)]
private static extern int WTSEnumerateSessions(
IntPtr hServer,
int Reserved,
int Version,
ref IntPtr ppSessionInfo,
ref int pCount); #endregion #region Win32 Structs private enum SW
{
SW_HIDE = ,
SW_SHOWNORMAL = ,
SW_NORMAL = ,
SW_SHOWMINIMIZED = ,
SW_SHOWMAXIMIZED = ,
SW_MAXIMIZE = ,
SW_SHOWNOACTIVATE = ,
SW_SHOW = ,
SW_MINIMIZE = ,
SW_SHOWMINNOACTIVE = ,
SW_SHOWNA = ,
SW_RESTORE = ,
SW_SHOWDEFAULT = ,
SW_MAX =
} private enum WTS_CONNECTSTATE_CLASS
{
WTSActive,
WTSConnected,
WTSConnectQuery,
WTSShadow,
WTSDisconnected,
WTSIdle,
WTSListen,
WTSReset,
WTSDown,
WTSInit
} [StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
} private enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous = ,
SecurityIdentification = ,
SecurityImpersonation = ,
SecurityDelegation = ,
} [StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
} private enum TOKEN_TYPE
{
TokenPrimary = ,
TokenImpersonation =
} [StructLayout(LayoutKind.Sequential)]
private struct WTS_SESSION_INFO
{
public readonly UInt32 SessionID; [MarshalAs(UnmanagedType.LPStr)]
public readonly String pWinStationName; public readonly WTS_CONNECTSTATE_CLASS State;
} #endregion // Gets the user token from the currently active session
private static bool GetSessionUserToken(ref IntPtr phUserToken)
{
var bResult = false;
var hImpersonationToken = IntPtr.Zero;
var activeSessionId = INVALID_SESSION_ID;
var pSessionInfo = IntPtr.Zero;
var sessionCount = ; // Get a handle to the user access token for the current active session.
if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, , , ref pSessionInfo, ref sessionCount) != )
{
var arrayElementSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
var current = pSessionInfo; for (var i = ; i < sessionCount; i++)
{
var si = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO));
current += arrayElementSize; if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive)
{
activeSessionId = si.SessionID;
}
}
} // If enumerating did not work, fall back to the old method
if (activeSessionId == INVALID_SESSION_ID)
{
activeSessionId = WTSGetActiveConsoleSessionId();
} //If the function succeeds, the return value is a nonzero value, and the phToken parameter points to the primary token of the user. //To call this function successfully, the calling application must be running within the context of the LocalSystem account and have the SE_TCB_NAME privilege. if (WTSQueryUserToken(activeSessionId, ref hImpersonationToken) != )
{
// Convert the impersonation token to a primary token
bResult = DuplicateTokenEx( hImpersonationToken, //hExistingToken
,
IntPtr.Zero, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, //ImpersonationLevel (int)TOKEN_TYPE.TokenPrimary, //TokenType ref phUserToken); //phNewToken [out] CloseHandle(hImpersonationToken);
} return bResult;
} public static bool StartProcessAsCurrentUser(string appPath, string cmdLine = null, string workDir = null, bool visible = true)
{ var hUserToken = IntPtr.Zero;
var startInfo = new STARTUPINFO();
var procInfo = new PROCESS_INFORMATION();
var pEnv = IntPtr.Zero;
int iResultOfCreateProcessAsUser; startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO)); try
{
if (!GetSessionUserToken(ref hUserToken))
{ int errCode = Marshal.GetLastWin32Error(); throw new Exception("GetSessionUserToken failed. ERROR Code:" + errCode.ToString());
} uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW);
startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE);
startInfo.lpDesktop = "winsta0\\default"; if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false))
{
throw new Exception("CreateEnvironmentBlock failed.");
} if (!CreateProcessAsUser(
hUserToken,
appPath,
cmdLine,
IntPtr.Zero,
IntPtr.Zero,
false,
dwCreationFlags,
pEnv,
workDir,
ref startInfo,
out procInfo))
{ //iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error(); throw new Exception("CreateProcessAsUser failed.");
} }
finally
{
CloseHandle(hUserToken);
if (pEnv != IntPtr.Zero)
{
DestroyEnvironmentBlock(pEnv);
}
CloseHandle(procInfo.hThread);
CloseHandle(procInfo.hProcess);
} return true;
} }
}

在SYSTEM权限下以当前用户权限运行程序的更多相关文章

  1. Linux 下以其他用户身份运行程序—— su、sudo、runuser

      本文综合分析了Linux系统下,如何使用runuser命令.su命令和sudo命令以其他用户身份来运行程序,以及这三个命令的运行效率比较. 一.su 命令临时切换用户身份 SU:( Switch ...

  2. linux普通用户权限设置为超级用户权限方法、sudo不用登陆密码

    以用户zato为例 普通用户权限设置为超级用户权限 进入有超级用户权限的账号 添加文件可写(w)权限 sudo chmod u+x /etc/sudoers 编辑/etc/sudoers文件 添加语句 ...

  3. 以不同用户身份运行程序,/savecred只需要输入一次密码(GetTokenByName取得EXPLORER.EXE的令牌,然后调用CreateProcessAsUser,而且使用LoadUserProfile解决另存文件的问题)good

    http://blog.sina.com.cn/s/blog_65977dde0100s7tm.html ----------------------------------------------- ...

  4. Windows服务System权限下在当前用户桌面创建快捷方式C#实例程序

    Windows服务一般运行在System权限下,这样权限比较高,方便执行一些高权限的操作. 但是,Environment.GetFolderPath等函数获取的也是System用户下的,而不是当前用户 ...

  5. 解决将/etc/passwd文件中1000改为0后只能guest进入系统的问题 ||ubuntu下将普通用户权限升级为root用户权限的方法;

    其实我现在才知道linux系统对于用户权限管理比较严,在ubuntu下系统不允许root权限的用户进入图像界面系统.由于之前没弄过权限这个东西瞬间掉坑了了. 我是想修改一下root下的nginx.co ...

  6. centos7新增用户并授权root权限、非root用户启动tomcat程序

    一.centos7新增用户并授权root权限 cat /etc/redhat-release查看centos版本号 1.禁用root账户登录 vim /etc/ssh/sshd_config 找到这一 ...

  7. sudo命令: 在其他用户下操作root用户权限

    一. 场景: 在某个远程服务器 A 上,用 账户1 登陆, 想要在root用户的目录下创建一个 .sh文件,  如果直接 用 touch test.sh 创建,会提示权限不足 此时可以用sudo命令: ...

  8. linux系统下,在用户空间应用程序中模拟发送系统键盘事件

    Linux 有自己的 input 子系统,可以统一管理鼠标和键盘事件. 如果想模拟键盘事件,但是系统没有键盘设备该如何是好? 基于输入子系统实现的 input 可以方便的在用户空间模拟鼠标和键盘事件. ...

  9. Debug模式下加载文件,运行程序异常的慢

    今天在进行单元测试的时候,debug模式下加载速度很慢,但是run模式下速度很快. 原因:在debug模式下,断点位置不当,解决办法 移除编译器中的所有断点.

随机推荐

  1. 80. Domino Internet Password

    Internet口令保存在Domino文件夹的个人文档的HTTPPassword域中,和文档中的username一起用于藉各种Internet协议訪问Dominoserver时的校验,最经常使用的就是 ...

  2. win32命令行小程序获取指定文件夹或者目录下面的所有文件大小,文件数量,目录数量

    #include <Windows.h> #include <stdio.h> #include <tchar.h> LARGE_INTEGER       lgA ...

  3. Cordova app 检查更新 ----JS进行调用(二)

    原文:Cordova app 检查更新 ----JS进行调用(二) 1.获取版本号 需要添加 插件 cordova plugin add https://github.com/whiteoctober ...

  4. H∞一般控制问题的鲁棒叙述性说明

    Robust Control System:反馈控制有承受一定类不确定能力的影响,这一直保持在这种不确定的条件(制)稳定.动态特性(灵敏度)和稳态特性(逐步调整)的能力. 非结构不确定性(Unstru ...

  5. 从Client应用场景介绍IdentityServer4(四)

    原文:从Client应用场景介绍IdentityServer4(四) 上节以对话形式,大概说了几种客户端授权模式的原理,这节重点介绍Hybrid模式在MVC下的使用.且为实现IdentityServe ...

  6. DELPHI高性能大容量SOCKET并发(八):断点续传(上传也可以续传)

    断点续传 断点续传主要是用在上传或下载文件,一般做法是开始上传的时候,服务器返回上次已经上传的大小,如果上传完成,则返回-1:下载开始的时候,由客户端上报本地已经下载大小,服务器根据位置信息下发数据, ...

  7. 深刻认识OpenStack

    OpenStack 1 OpenStack简单介绍                                                          Openstack archite ...

  8. SQL Server 2017 正式发布:同时支持 Windows 和 Linux(现在看下来,当年那德拉的“云优先,移动优先”是有远见的,而且是有一系列的措施和产品相配合的,只是需要一点时间而已。真是佩服!!)

    微软在去年 3 月首次对外宣布了 Linux 版的 SQL Server,并于今年 7 月发布了首个公开 RC 版.前几日在美国奥兰多召开的微软 Ignite 2017 大会上,微软宣布 SQL Se ...

  9. JS中常用函数总结

    //LTrim(string):去除左边的空格 function LTrim(str) { var whitespace = new String(" \t\n\r"); var ...

  10. WPF中样式和行为和触发器

    原文:WPF中样式和行为和触发器 样式简介:样式(style)是组织和重用格式化选项的重要工具,不是使用重复的标记填充XAML,以便设置外边距.内边距.颜色以及字体等细节.而是创建一系列封装所有这些细 ...