Guest User

Untitled

a guest
Dec 14th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.21 KB | None | 0 0
  1. public string GetProcessOwner(int processId)
  2. {
  3. string query = "Select * From Win32_Process Where ProcessID = " + processId;
  4. ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
  5. ManagementObjectCollection processList = searcher.Get();
  6.  
  7. foreach (ManagementObject obj in processList)
  8. {
  9. string[] argList = new string[] { string.Empty, string.Empty };
  10. int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
  11. if (returnVal == 0)
  12. {
  13. // return DOMAINuser
  14. return argList[1] + "\" + argList[0];
  15. }
  16. }
  17.  
  18. return "NO OWNER";
  19. }
  20.  
  21. public string GetProcessOwner(string processName)
  22. {
  23. string query = "Select * from Win32_Process Where Name = "" + processName + """;
  24. ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
  25. ManagementObjectCollection processList = searcher.Get();
  26.  
  27. foreach (ManagementObject obj in processList)
  28. {
  29. string[] argList = new string[] { string.Empty, string.Empty };
  30. int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
  31. if (returnVal == 0)
  32. {
  33. // return DOMAINuser
  34. string owner = argList[1] + "\" + argList[0];
  35. return owner;
  36. }
  37. }
  38.  
  39. return "NO OWNER";
  40. }
  41.  
  42. List<string> sp = new List<string>
  43. {
  44. "svchost", "csrss", "System", "wininit",
  45. "irstrtsv","scrncap","lsass","System",
  46. "wininit","taskmgr","dwm","spoolsv","smss",
  47. "SearchIndexer","lsm","taskhost","svchost","explorer",
  48. "winlogon","services","conhost"
  49. };
  50.  
  51. using System;
  52. using System.Collections.Generic;
  53. using System.ComponentModel;
  54. using System.Runtime.InteropServices;
  55. using System.Text;
  56. using System.Diagnostics;
  57. using System.Windows.Forms;
  58.  
  59. namespace WindowsFormsTest1
  60. {
  61. public partial class Form1 : Form
  62. {
  63.  
  64. [DllImport("Rstrtmgr.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
  65. public static extern UInt32 RmStartSession(out UInt32 pSessionHandle, UInt32 dwSessionFlags,
  66. string strSessionKey);
  67.  
  68. [DllImport("Rstrtmgr.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
  69. public static extern UInt32 RmRegisterResources(UInt32 dwSessionHandle,
  70. UInt32 nFiles, string[] rgsFilenames, UInt32 nApplications,
  71. ref RM_UNIQUE_PROCESS rgApplications, UInt32 nServices, string[] rgsServiceNames);
  72.  
  73. [DllImport("Rstrtmgr.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
  74. public static extern UInt32 RmGetList(UInt32 dwSessionHandle, out UInt32 pnProcInfoNeeded,
  75. ref UInt32 pnProcInfo, [In, Out] RM_PROCESS_INFO[] rgAffectedApps, ref UInt32 lpdwRebootReasons);
  76.  
  77. [DllImport("Rstrtmgr.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
  78. public static extern UInt32 RmEndSession(UInt32 dwSessionHandle);
  79.  
  80. public const UInt32 RmRebootReasonNone = 0x0;
  81. public const int ERROR_MORE_DATA = 234;
  82.  
  83. /// <summary>
  84. /// Преобразование DateTime в структуру FILETIME
  85. /// </summary>
  86. public static System.Runtime.InteropServices.ComTypes.FILETIME FileTimeFromDateTime(DateTime date)
  87. {
  88. long ftime = date.ToFileTime();
  89. System.Runtime.InteropServices.ComTypes.FILETIME ft = new System.Runtime.InteropServices.ComTypes.FILETIME();
  90. ft.dwHighDateTime = (int)(ftime >> 32);
  91. ft.dwLowDateTime = (int)ftime;
  92. return ft;
  93. }
  94.  
  95. /// <summary>
  96. /// Получение типа процесса
  97. /// </summary>
  98. public static RM_APP_TYPE GetProcessType(Process proc)
  99. {
  100. uint handle;
  101. string key = Guid.NewGuid().ToString();
  102.  
  103. uint res = RmStartSession(out handle, (uint)0, key);
  104. if (res != 0)
  105. {
  106. throw new ApplicationException("Could not begin restart session. ");
  107. }
  108.  
  109. try
  110. {
  111. uint pnProcInfoNeeded = 0, pnProcInfo = 0,
  112. lpdwRebootReasons = RmRebootReasonNone;
  113.  
  114. RM_UNIQUE_PROCESS uniqueprocess = new RM_UNIQUE_PROCESS();
  115. uniqueprocess.dwProcessId = proc.Id;
  116. System.Runtime.InteropServices.ComTypes.FILETIME ft = FileTimeFromDateTime(proc.StartTime);
  117. uniqueprocess.ProcessStartTime = ft;
  118.  
  119. res = RmRegisterResources(handle, 0, null, 1, ref uniqueprocess, 0, null);
  120.  
  121. if (res != 0)
  122. {
  123. throw new ApplicationException("Could not register resource.");
  124. }
  125.  
  126. res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null,
  127. ref lpdwRebootReasons);
  128. if (res == ERROR_MORE_DATA)
  129. {
  130. RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
  131. pnProcInfo = pnProcInfoNeeded;
  132.  
  133. // Get the list.
  134. res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo,
  135. processInfo, ref lpdwRebootReasons);
  136. if (res == 0)
  137. {
  138. if (pnProcInfo == 0) throw new ApplicationException("Process not found");
  139.  
  140. return processInfo[0].ApplicationType;
  141. }
  142. else
  143. {
  144. throw new ApplicationException("Could not list processes");
  145. }
  146. }
  147. else if (res != 0)
  148. {
  149. throw new ApplicationException("Failed to get size of result.");
  150. }
  151. }
  152. finally
  153. {
  154. RmEndSession(handle);
  155. }
  156. throw new ApplicationException("Process not found");
  157. }
  158.  
  159.  
  160. public Form1()
  161. {
  162. InitializeComponent();
  163. }
  164.  
  165.  
  166. private void button1_Click(object sender, EventArgs e)
  167. {
  168. //пример использования
  169. Process p=Process.GetProcessesByName(textBox1.Text)[0];
  170. MessageBox.Show(GetProcessType(p).ToString());
  171. /*Для системных процессов выведет RmCritical*/
  172. }
  173. }
  174.  
  175. /* Определения структур */
  176.  
  177. [StructLayout(LayoutKind.Sequential)]
  178. public struct RM_UNIQUE_PROCESS
  179. {
  180. // The product identifier (PID).
  181. public int dwProcessId;
  182. // The creation time of the process.
  183. public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
  184. }
  185.  
  186. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  187. public struct RM_PROCESS_INFO
  188. {
  189. const int CCH_RM_MAX_APP_NAME = 255;
  190. const int CCH_RM_MAX_SVC_NAME = 63;
  191.  
  192. // Contains an RM_UNIQUE_PROCESS structure that uniquely identifies the
  193. // application by its PID and the time the process began.
  194. public RM_UNIQUE_PROCESS Process;
  195. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
  196. // If the process is a service, this parameter returns the
  197. // long name for the service.
  198. public string strAppName;
  199. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
  200. // If the process is a service, this is the short name for the service.
  201. public string strServiceShortName;
  202. // Contains an RM_APP_TYPE enumeration value.
  203. public RM_APP_TYPE ApplicationType;
  204. // Contains a bit mask that describes the current status of the application.
  205. public uint AppStatus;
  206. // Contains the Terminal Services session ID of the process.
  207. public uint TSSessionId;
  208. // TRUE if the application can be restarted by the
  209. // Restart Manager; otherwise, FALSE.
  210. [MarshalAs(UnmanagedType.Bool)]
  211. public bool bRestartable;
  212. }
  213.  
  214. public enum RM_APP_TYPE
  215. {
  216. // The application cannot be classified as any other type.
  217. RmUnknownApp = 0,
  218. // A Windows application run as a stand-alone process that
  219. // displays a top-level window.
  220. RmMainWindow = 1,
  221. // A Windows application that does not run as a stand-alone
  222. // process and does not display a top-level window.
  223. RmOtherWindow = 2,
  224. // The application is a Windows service.
  225. RmService = 3,
  226. // The application is Windows Explorer.
  227. RmExplorer = 4,
  228. // The application is a stand-alone console application.
  229. RmConsole = 5,
  230. // A system restart is required to complete the installation because
  231. // a process cannot be shut down.
  232. RmCritical = 1000
  233. }
  234. }
  235.  
  236. Process[] processList = Process.GetProcesses();
  237. foreach (Process process in processList)
  238. {
  239. // В process хранится информация о процессе
  240. }
  241.  
  242. public static List<KeyValuePair<int, string>> GetProcessExtraInformation(int processId)
  243. {
  244. // запрос получения всех процессов связанных с переданным идентификатором processId
  245. string query = "Select * From Win32_Process Where ProcessID = " + processId;
  246. ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
  247. ManagementObjectCollection processList = searcher.Get();
  248.  
  249. // здесь будет результат
  250. List<KeyValuePair<int, string>> result = new List<KeyValuePair<int, string>>();
  251.  
  252. foreach (ManagementObject obj in processList)
  253. {
  254. var description = @"Не могу получить информацию о процессе";
  255. // Получим описание процесса, если таковое имеется
  256. if (obj["ExecutablePath"] != null)
  257. {
  258. try
  259. {
  260. FileVersionInfo info = FileVersionInfo.GetVersionInfo(obj["ExecutablePath"].ToString());
  261. description = info.FileDescription;
  262. }
  263. catch { }
  264. }
  265.  
  266. // Получить владельца процесса в argList
  267. var owner = @"Не могу получить владельца процесса";
  268. string[] argList = new string[] { string.Empty, string.Empty };
  269. int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
  270. if (returnVal == 0)
  271. {
  272. owner = argList[1] + "\" + argList[0]; // Домен и владелец
  273. }
  274.  
  275. result.Add(new KeyValuePair<int, string>(processId, string.Format("Description: '{0}'nOwner: '{1}'", description, owner)));
  276. }
  277.  
  278. return result;
  279. }
  280.  
  281. Process[] processList = Process.GetProcesses();
  282. foreach (Process process in processList)
  283. {
  284. // В process хранится информация о процессе
  285. var processInfo = GetProcessExtraInformation(process.Id);
  286.  
  287. foreach (var info in processInfo)
  288. {
  289. Console.WriteLine(string.Format("Id: {0}n{1}", info.Key, info.Value));
  290. }
  291. Console.WriteLine();
  292. }
  293.  
  294. Console.ReadLine();
Add Comment
Please, Sign In to add comment