esac
esac

Reputation: 24685

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 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).

Upvotes: 5

Views: 8537

Answers (5)

Mitchell
Mitchell

Reputation: 7087

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);
}

Upvotes: 0

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

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)

Upvotes: 1

ChrisLively
ChrisLively

Reputation: 88064

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.

Upvotes: 0

NekoIme
NekoIme

Reputation: 36

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

Upvotes: 0

goenning
goenning

Reputation: 6654

Take a look at this ServerRemoteControl.

Upvotes: 0

Related Questions