最近在一个项目中用到了win32的管道编程,需要在cmd框中读取ping命令的返回值。以下是管道编程的代码。希望大家可以多提意见,共同学习、共同进步。谢谢!
.386
.model flat,stdcall
option casemap:none
include windows.inc
include user32.inc
include kernel32.inc
include masm32.inc
include shlwapi.inc
includelib user32.lib
includelib kernel32.lib
includelib masm32.lib
includelib shlwapi.lib
_StringCmp proto :DWORD
.data
szCmdFile db "c:\\windows\\system32\\ping.exe",0
szCmdPa db " www.16333.com",0
szFmt1 db "没有ping到地址",0
szFmt2 db "ping到地址",0
szLossFmt db "100% loss",0
bytesRead dd 0
.data?
hReadPipe dd ?
hWritePipe dd ?
hPipeHandle dd ?
stStartup STARTUPINFO <?>
stProcInfo PROCESS_INFORMATION <?>
stSecurity SECURITY_ATTRIBUTES <?>
szBuffer db 2048 dup (?)
szFullBuffer db 4096 dup (?) .code
;对cmd中的ping命令返回值做比较
_StringCmp proc lpString:DWORD
local @flag:DWORD
pushad
mov esi,lpString
lea edi,szFullBuffer
mov al,BYTE ptr [edi]
cmp al,0
jz Done
loc_1:
mov eax,DWORD ptr [esi]
mov ebx,DWORD ptr [edi]
cmp eax,ebx
jz @F
inc edi
mov al,BYTE ptr [edi]
cmp al,0
jz Done
jmp loc_1
@@:
add esi,4
add edi,4
mov eax,DWORD ptr [esi]
mov ebx,DWORD ptr [edi]
cmp eax,ebx
jz @F
inc edi
mov al,BYTE ptr [edi]
cmp al,0
jz Done
mov esi,lpString
jmp loc_1
@@:
mov eax,1
mov @flag,eax
popad
mov eax,@flag
ret
Done:
xor eax,eax
mov @flag,eax
popad
mov eax,@flag
ret
_StringCmp endp
start:
xor eax,eax
push eax
;对stSecurity结构体参数初始化
mov eax,sizeof SECURITY_ATTRIBUTES
mov stSecurity.nLength,eax
pop eax
mov stSecurity.lpSecurityDescriptor,eax
inc eax
mov stSecurity.bInheritHandle,eax
;创建一个匿名管道
invoke CreatePipe,addr hReadPipe,addr hWritePipe,addr stSecurity,0
mov hPipeHandle,eax ;保存管道句柄
mov eax,sizeof STARTUPINFO
mov stStartup.cb,eax
invoke GetStartupInfo,addr stStartup
mov eax,hWritePipe
mov stStartup.hStdError,eax
mov stStartup.hStdOutput,eax
xor eax,eax
mov ax,SW_HIDE
mov stStartup.wShowWindow,ax
mov eax,STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES
mov stStartup.dwFlags,eax
;创建进程
invoke CreateProcess,addr szCmdFile,addr szCmdPa,NULL,NULL,TRUE,CREATE_SUSPENDED or NORMAL_PRIORITY_CLASS,NULL,NULL,offset stStartup,offset stProcInfo
;运行主线程
invoke ResumeThread,stProcInfo.hThread
invoke CloseHandle,hWritePipe
.while TRUE
;读取管道信息,如果没有字节读出就退出循环
invoke ReadFile,hReadPipe,offset szBuffer,2048,offset bytesRead,NULL
.if !bytesRead
.break
.endif
invoke lstrcat,offset szFullBuffer,addr szBuffer
invoke StdOut,offset szFullBuffer
invoke Sleep,400
.endw
invoke _StringCmp,addr szLossFmt
;根据条件加入对应代码
.if eax
invoke MessageBox,NULL,offset szFmt1,NULL,MB_OK
;......
.else
invoke MessageBox,NULL,offset szFmt2,NULL,MB_OK
;......
.endif
;关闭管道
invoke CloseHandle,hReadPipe
invoke ExitProcess,0
end start
读取cmd返回值保存在数组中。
[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)
上传的附件: