Delphi执行DOS命令并返回结果CMD远控等等常用命令

作者:湖北诺贝特科技有限公司  来源:www.nbt158.com未知  发布时间:2017-09-12 16:33:43
Delphi执行DOS命令并返回结果CMD远控等等常用命令



unit UnitCmdShell;

interface

uses
Windows,SysUtils,Classes;
//K8执行DOS并返回结果
function RunDosCommand(Command: string): string;

implementation

//================================================================
//K8执行DOS并返回结果
function RunDosCommand(Command: string): string;
var
hReadPipe: THandle;
hWritePipe: THandle;
SI: TStartUpInfo;
PI: TProcessInformation;
SA: TSecurityAttributes;
//
SD : TSecurityDescriptor;
BytesRead: DWORD;
Dest: array[0..1023] of char;
CmdLine: array[0..512] of char;
TmpList: TStringList;
Avail, ExitCode, wrResult: DWORD;
osVer: TOSVERSIONINFO;
tmpstr: AnsiString;
begin
osVer.dwOSVersionInfoSize := Sizeof(TOSVERSIONINFO);
GetVersionEX(osVer);
if osVer.dwPlatformId = VER_PLATFORM_WIN32_NT then
begin
//
InitializeSecurityDescriptor(@SD, SECURITY_DESCRIPTOR_REVISION);
//
SetSecurityDescriptorDacl(@SD, True, nil, False);
SA.nLength := SizeOf(SA);
SA.lpSecurityDescriptor := nil; //@SD;
SA.bInheritHandle := True;
CreatePipe(hReadPipe, hWritePipe, @SA, 0);
end
else
CreatePipe(hReadPipe, hWritePipe, nil, 1024);
try
FillChar(SI, SizeOf(SI), 0);
SI.cb := SizeOf(TStartUpInfo);
SI.wShowWindow := SW_HIDE;
SI.dwFlags := STARTF_USESHOWWINDOW;
SI.dwFlags := SI.dwFlags or STARTF_USESTDHANDLES;
SI.hStdOutput := hWritePipe;
SI.hStdError := hWritePipe;
StrPCopy(CmdLine, Command);
if CreateProcess(nil, CmdLine, nil, nil, True, NORMAL_PRIORITY_CLASS, nil, nil, SI, PI) then
begin
ExitCode := 0;
while ExitCode = 0 do
begin
wrResult := WaitForSingleObject(PI.hProcess, 500);
//
if PeekNamedPipe(hReadPipe, nil, 0, nil, @Avail, nil) then
if PeekNamedPipe(hReadPipe, @Dest[0], 1024, @Avail, nil, nil) then
begin
if Avail > 0 then
begin
TmpList := TStringList.Create;
try
FillChar(Dest, SizeOf(Dest), 0);
ReadFile(hReadPipe, Dest[0], Avail, BytesRead, nil);
TmpStr := Copy(Dest, 0, BytesRead - 1);
TmpList.Text := TmpStr;
Result := tmpstr;
finally
TmpList.Free;
end;
end;
end;
if wrResult <> WAIT_TIMEOUT then ExitCode := 1;
end;
GetExitCodeProcess(PI.hProcess, ExitCode);
CloseHandle(PI.hProcess);
CloseHandle(PI.hThread);
end;
finally
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
end;
end;

//=================================================================

end.

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:武汉网站设计公司 https://www.feimao666.com


上一篇:PHP面向对象之旅:类的属性
下一篇:最后一页