Tuesday, December 4, 2012

Remotely Log Off Remote Desktop Users


I frequently use Remote Desktop to access various PCs here at work and nothing annoys me more than seeing this message box:

This is caused when “The terminal server has exceeded the maximum number of allowed connections.”, right? Basically, this happens because Windows by default only allows two simultaneous terminal services connections to the same machine. If you see this message, then there is already that number of people logged in, and you cannot connect until one of the sessions logs off.

Usually what happens is that people don’t explicitly log out of machines when they disconnect from remote desktop which causes their “rogue” sessions to remain active. You could just nicely ask everyone if they would please “log off” before disconnecting their sessions, but is there something else we can do?

To perform the commands I am about to show you, you need to be an administrator on the target machine. If you aren’t you can’t perform these commands. However, in most development and test environments, hopefully this won’t be an issue.

How to query for users on a machine

First, how can we query to find out what users have a session on a remote machine? Windows provides the qwinsta.exe command which we can use to query for the sessions that are running The format is as follows:

qwinsta /server:<serverName>

Here is an example running this command against one of my local machines. Notice it shows the username, state, and the ID of the session.
You can also use quser.exe:
quser /server:<serverName>
Here is the same example above but notice it also when they logged in and how long they were idle.
How to log a user off of a machine
Now that we know what users are on a machine, how can we force one to disconnect? Again, there is a handy little command called logoff.exe that we can use to force a user to log off of a machine based off of their session ID. The format is as follows:
logoff <sessionId> /server:<serverName>
Here is an example running this command against one of my local machines. Notice that I used the session ID that I found from the quser.exe command above.

Warning: If you remotely log off a user, their log session goes away which could mean that the unsaved data is lost, or if the user is in the middle of an activity, they may come down to your office to chew you out.


No comments:

Post a Comment