라이브러리/개발
원격 시스템의 프로세스 쥑이기....
눌프
2011. 6. 3. 11:29
C#을 통해서 원격이나 로컬 시스템의 프로세스를 쥑여 버릴 수 있다. 뭐 아래 내용은 아주 심플하다. 대상시스템의 WMI객체에 접속해서 쿼리를 던지고, 해당 결과를 받아서 InvokeMethod를 통해서 각 프로세스를 쥑인다.
1. 도메인 인증 등을 통해 인증이 되어 있는 경우
/// <summary>
/// Terminate process on local or remote system
/// </summary>
/// <param name="serverName">Server name on local or remote</param>
/// <param name="processName">Process name</param>
private static void KillProcess(string serverName, string processName)
{
try
{
if (processName.IndexOf(".exe") > 0)
{
processName = processName.Substring(0, processName.IndexOf(".exe") - 1);
}
// ManagementScope
ManagementScope scope = new ManagementScope("\\\\" + serverName + "\\root\\cimv2");
// Query
ObjectQuery query = new ObjectQuery("select * from Win32_Process where Name = '" + processName + ".exe'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
// Get object
ManagementObjectCollection objCollection = searcher.Get();
foreach (ManagementObject obj in objCollection)
{
obj.InvokeMethod("Terminate", null);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
2. 인증이 되지 않아서 접속정보를 넣어야 하는 경우.
/// <summary>
/// Terminate process on local or remote system
/// </summary>
/// <param name="serverName">Server name on local or remote</param>
/// <param name="processName">Process name</param>
/// <param name="userName">user name for remote system</param>
/// <param name="userPasswd">Password for user</param>
private static void KillProcess(string serverName, string processName, string userName, string userPasswd)
{
try
{
if (processName.IndexOf(".exe") > 0)
{
processName = processName.Substring(0, processName.IndexOf(".exe") - 1);
}
ConnectionOptions opts = new ConnectionOptions();
opts.Username = userName;
opts.Password = userPasswd;
// ManagementScope
ManagementScope scope = new ManagementScope("\\\\" + serverName + "\\root\\cimv2", opts);
scope.Connect();
// Query
ObjectQuery query = new ObjectQuery("select * from Win32_Process where Name = '" + processName + ".exe'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
// Get object
ManagementObjectCollection objCollection = searcher.Get();
foreach (ManagementObject obj in objCollection)
{
obj.InvokeMethod("Terminate", null);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}