开发者

How to remotely log off a user?

How can I programatically log off a user remotely (from another machine) with C#? All I know is their username. This is done in an Active Directory environment where the account executing this would be an Administrator (Domain Admin). I assume that security would be handled. Would want to avoid having to install an application on the machine.

There 开发者_StackOverflow中文版does seem to be an API although I do not know what it uses, as "logoff.exe" provided with windows provides for this capability. In the end I can use this, but would prefer to avoid a Process.Start call and relying on it (plus it doesn't take the username, just the session id).


This is more terminal server side of user management but I really like using Cassia


Another option is do this

System.Diagnostics.Process.Start("shutdown.exe", String.Format(@"/l /f /m \\{1}", remoteComputerName));

/l is logoff. /f is force. /m \\computername is the name of the remote computer to do the operation on. If you are not on a domain and the user running the app does not have domain admin rights I can not guarantee the above command will work.


Third option: get PsExec then run the shutdown command with it on the remote computer(shutdown.exe /l /f)


Take a look at this ServerRemoteControl.


WMI class win32_operatingsystem wmi might be useful, more specifically win32shutdown method (has logoff flag too).


I believe you can do so through WMI. Here is a site with a regular script to do it: http://www.waynezim.com/2009/04/remote-shutdown-logoff-script-using-wmi/

And this link ( http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/59dd345d-df85-4128-8641-f01f01583194 )

gives more information that is specific to C# plus a hint on how to make it work when the user is disconnected, but still logged in.


This is my very simple solution. This will remotely logoff the user that is currently logged in. If you want to logoff specific users, query the session id's first, and change 'console' in the session id.

private void runRemoteApp(string[] processToRun, string machineName)
{
    var connection = new ConnectionOptions();
    var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", machineName), connection);
    var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
    wmiProcess.InvokeMethod("Create", processToRun);
}

private void logoffMachine(string machineName)
{
    var processToRun = new[] { "logoff.exe console" };
    runRemoteApp(processToRun, machineName);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜