注销远程用户(会话)

本文介绍了如何在Delphi和C++中利用WtsApi32库来实现远程服务器上的用户会话注销功能,帮助管理员有效管理远程桌面连接。
摘要由CSDN通过智能技术生成

Delphi实现:

uses

WtsApi32;

//通过会话ID得到会话名称
procedure GetSessionUserName(dwSessionId: dword; var UserName: string);
var
  bRes: boolean;
  dwBufferLen: dword;
  Ptr: Pointer;
begin
  bRes := WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSessionId, WTSUserName, Ptr, dwBufferLen);
  if bRes = false then
  begin  
       UserName := '';  
        exit;
  end;
  UserName := PWideChar(Ptr);
end;
//通过会话名称结束目标会话
procedure ExitByUserName(str: string);
var
  i: integer;
  sessionInfo: PWTS_SESSION_INFOW;
  sessionInfoCount: dword;
  dwSessionId: dword;
  UserName: string;
  CommandLine: string;
begin
  if WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, sessionInfo, sessionInfoCount) then
  begin
    for i := 0 to sessionInfoCount - 1 do
    begin
      //遍历注销状态为“活动”或者“断开”的所有目标会话 
      if (sessionInfo.state = WTSActive) or (sessionInfo.state = WTSDisconnected) then
      begin
        dwSessionId := sessionInfo.SessionId;
        GetSessionUserName(dwSessionId, UserName);
        if UserName = str then
        begin
          CommandLine := Format('LOGOFF %d', [dwSessionId]);
          winexec(PAnsiChar(ansistring(CommandLine)), SW_HIDE);
          Sleep(2500);
        end;
      end;
      inc(sessionInfo);
    end;
  end;
end;


 

 

C++实现:

//在其它session中(如远程桌面的session)运行指定的程序,需要具有system权限,可以在任意的桌面里运行指定程序
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <Tlhelp32.h>
#include <tchar.h>
#include <psapi.h>
#include <stdio.h>
#include <STDLIB.H>
#include <tlhelp32.h>
#include <WtsApi32.h>
#pragma comment(lib, "WtsApi32.lib")
#pragma  comment (lib,"psapi")


// Get us
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值