Socket遠端執行命令並結果回傳(客戶端)

2021-06-01 02:32:37 字數 1848 閱讀 8954

/*

*客戶端,執行命令,回傳執行結果

*by rekken

*/#include

#include

#include

#include

#include

#include in.h>

#include

#include <

string

.h>

#define serverport 3490

#define backlog 10

#define max_connected_no 10

#define maxdatasize 120

int main(

)printf(

"socket success!,sockfd=%d\n"

,sockfd);/

/set relevant parameters in the socketr_in struct

server_sockaddr.sin_family=af_inet;

server_sockaddr.sin_port=htons(serverport)

;server_sockaddr.sin_addr.s_addr=inaddr_any;

bzero(

&(server_sockaddr.sin_zero)

,8);

//bind the sockfd and port

if(bind(sockfd,

(struct sockaddr *

)&server_sockaddr,sizeof(struct sockaddr))=

=-1)

printf(

"bind success!\n");

//begin to listen

if(listen(sockfd,backlog)==

-1)printf(

"listening....\n");

//call the accept(

),wait for the peer's connectingif(

(client_fd=accept(sockfd,

(struct sockaddr *

)&client_sockaddr,

&sin_size))=

=-1)

//receive the data from the peerif(

(recvbytes=recv(client_fd,buf,sizeof(buf)

,0))==

-1)/

/do the received commandif(

(pp = popen(buf,

"r"))=

=null

)while

(fgets(output, 255, pp)

)printf(

"send data length:%d\n"

,sendbytes);}

pclose(pp)

;close(sockfd)

;return 1;}/

**講命令執行部分封裝*/

int do_command(

int sockfd,char *command,char *output)

//sockfd套接字用於結果回傳,command為待執行命令,output存放執行結果

while

(!feof(pp))if

((send(sockfd,output,count_byte,0))=

=-1)

pclose(pp)

;return count_byte;

//返回值為傳送位元組數}

遠端執行cmd命令並得到結果

handlehread,hwrite sa.nlength sizeof security attributes sa.lpsecuritydescriptor null 使用系統預設的安全描述符 sa.binherithandle true 建立的程序繼承控制代碼 if createpipe hr...

socket 基於tcp實現遠端執行命令

server.py socket 基於tcp實現遠端執行命令 from socket import import subprocess ip port 127.0.0.1 8080 back log 5buffer size 1024tcp server socket af inet,sock st...

C語言執行cmd命令並獲取執行結果

優點 跨平台 缺點 windows下呼叫時會閃出控制台視窗 include include brief 使用popen呼叫終端並獲取執行結果 param in cmd 命令內容 param out result 儲存結果的位址 return 0或1 執行狀態,失敗或成功 int exec cmd c...