views:

853

answers:

3

How can I programmatically tell if the terminal services service is running and is healthy? I'm creating a .net console application that will check if terminal services are running on a list of computers.

I can check the remote registry entry to see if it's enabled, but that doesn't mean it's running. I was thinking of making a socket connection to port 3389, but it doesn't have to be listening on that port either.

Is there an elegant way to check for this?

Regards,

A: 

Never done anything with it, but WMI is probably the way to go to check processes on remote computers, etc.

flq
+1  A: 

If you (or, specifically, the user the application runs as) has permission to do so, you could remotely query the SCM of the target machine to determine if the TS service is running.

You should be able to use System.ServiceProcess.ServiceController.GetServices(string machineName) to get a list of all the services on the computer, iterate the result to find the Terminal Services service and query its status.

Jason Musgrove
Worked like a charm, thanks!
Dave
A: 

You can use the WinStationServerPing (undocumented) API like the Terminal Server Ping Tool does. 2 Examples of checking if the Service is running (delphi unmanaged code but shouldn't be hard to translate):

// This is the way WTSApi32.dll checks if Terminal Service is running
function IsTerminalServiceRunning: boolean;
var hSCM: HANDLE;
  hService: HANDLE;
  ServiceStatus: SERVICE_STATUS;
begin
  Result := False;
  // Open handle to Service Control Manager
  hSCM := OpenSCManager(nil, SERVICES_ACTIVE_DATABASE, GENERIC_READ);
  if hSCM > 0 then
  begin
    // Open handle to Terminal Server Service
    hService := OpenService(hSCM, 'TermService', GENERIC_READ);
    if hService > 0 then
    begin
      // Check if the service is running
      QueryServiceStatus(hService, ServiceStatus);
      Result := ServiceStatus.dwCurrentState = SERVICE_RUNNING;
      // Close the handle
      CloseServiceHandle(hService);
    end;
    // Close the handle
    CloseServiceHandle(hSCM);
  end;
end;

// This the way QWinsta.exe checks if Terminal Services is active:
function AreWeRunningTerminalServices: Boolean;
var VersionInfo: TOSVersionInfoEx;
  dwlConditionMask: Int64;
begin
  // Zero Memory and set structure size
  ZeroMemory(@VersionInfo, SizeOf(VersionInfo));
  VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);

  // We are either Terminal Server or Personal Terminal Server
  VersionInfo.wSuiteMask := VER_SUITE_TERMINAL or VER_SUITE_SINGLEUSERTS;
  dwlConditionMask := VerSetConditionMask(0, VER_SUITENAME, VER_OR);

  // Test it
  Result := VerifyVersionInfo(VersionInfo, VER_SUITENAME, dwlConditionMask);
end;

Please note that on Windows 7 the Terminal Service service is not running by default.

Remko