在服务器上执行命令,然后将结果发送到Windows中的客户端

Execute a command on the server and send the result to the client in Windows

本文关键字:Windows 客户端 结果 服务器 执行 命令 然后      更新时间:2023-10-16

我正在编写一个简单的服务器程序,该程序执行命令并将结果发送给客户端。我阅读了无数涉及使用popen()pipe()dup2()fork()等的示例,但是它们都不对我有用,它们并没有很好地解释代码。我也试图自己做,但没有成功。您能为我提供一个有据可查的例子吗?

这是从客户端接收命令/消息的代码:

void server_receive() {
    struct sockaddr_in from;
    int from_len, recv_len;
    char buf[BUFLEN], path[256]; // BUFLEN = 1024
    // Getting the path for the command to execute
    strcpy(path, getenv("SYSTEMDRIVE"));
    strcat(path, "\WINDOWS\System32\tasklist.exe");
    from_len = sizeof(from);
    memset(buf, '', BUFLEN);
    // Receiving the command
    // I'll add some if-else statements to handle various commands, but for
    // now I just need to see if I can even get one to work.
    if((recv_len = recvfrom(sockt, buf, BUFLEN, 0, (struct sockaddr*) &from, &from_len)) == SOCKET_ERROR) {
        printf("[ERROR] recvfrom() failed: %d.nn", WSAGetLastError());
    } else {
        printf("Packet received from %s:%dn", inet_ntoa(from.sin_addr), ntohs(from.sin_port));
        printf("Data: %snn", buf);
        // Code to execute tasklist (I used _popen())
        // and send everything back to the client (I used TransmitFile())
    }
}

这是将命令/消息发送到服务器的代码:

void client_send(char server[], unsigned short port) {
    struct sockaddr_in to;
    int s, to_len = sizeof(to);
    char buf[BUFLEN]; // BUFLEN = 1024
    char message[BUFLEN];
    memset((char*) &to, 0, sizeof(to));
    to.sin_family = AF_INET;
    to.sin_port = htons(port);
    to.sin_addr.S_un.S_addr = inet_addr(server);
    while(true) {
        printf("Enter message: ");
        gets(message);
        if (sendto(sockt, message, strlen(message), 0, (struct sockaddr*) &to, to_len) == SOCKET_ERROR) {
            printf("[ERROR] sendto() failed: %d.nn" , WSAGetLastError());
        }
        memset(buf, '', BUFLEN);
        if (recvfrom(sockt, buf, BUFLEN, 0, (struct sockaddr*) &to, &to_len) == SOCKET_ERROR) {
            printf("[ERROR] recvfrom() failed: %d.nn", WSAGetLastError());
        } else {
            printf("Server's response: %snn", buf); /* The result of tasklist
            should be outputted by this line of code, however I'm concerned about the
            relatively small receive length (BUFLEN = 1024).*/
        }
    }
}

不必说这两个功能只是我代码的一部分。

您提到的是_popen(带有领先的下划线)和TransmitFile表示您在Windows上,该Windows没有forkpipe或相关功能。

在Windows中执行命令有许多替代方案。正如您已经提到的那样,它是通过_popen(但是您没有说该方法出了什么问题)。其他包括"经典" system CRT功能。当然,Windows本机CreateProcess功能。如果要打开"文档",则有ShellExecute函数。

知道可用的功能将帮助您搜索示例。将术语windows添加到您的搜索中将有助于找到特定于Windows的示例和教程。并添加术语msdn将有助于在Microsoft开发人员网络上找到主题。