tags:

views:

81

answers:

4

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

A: 

Take a look at this ServerRemoteControl.

Guilherme Oenning
Covers everything except logoff. Plus it uses .net remoting which means I would have to install an app onto the machine just to be able to control it.
esac
A: 

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)

Scott Chamberlain
Already looked at shutdown.exe, it does not support /l and /m together.
esac
Is the computer you are remote logging out a terminal server?
Scott Chamberlain
Closest answer as I ended up using what Cassia uses, WTSLogoffSession.
esac
A: 

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

NekoIme
A: 

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.

Chris Lively
That is where I started, and from what I can tell, this logs off the user who has authenticated, so if I want to log off user2, I would have to authenticate as user2 which would require me knowing his password?
esac
@esac: No. You'll have to get the users session id, then use the logoff tool passing in the ip address of the machine to kick them off of.
Chris Lively