如何从c++代码在另一台计算机上运行程序

How to run a program on another computer from c++ code?

本文关键字:一台 计算机 程序 运行 c++ 代码      更新时间:2023-10-16

我想让我的c++程序在PC1上启动PC2上的另一个程序,给定PC2的主机名。我现在不想把事情弄得太复杂,所以让我们假设这个程序在PC2上的可执行文件的搜索路径上。据我所知,这可以通过ssh完成吗?假设(为了进一步简化)我在PC1和PC2上都有一个帐户,这样当我在PC1上登录时,ssh就会连接我(没有任何需要我提供用户名和密码的交互),我该怎么做呢?https://www.libssh.org/是否有助于简化事情?

您可能对这个c++ RPC库感兴趣:

http://szelei.me/introducing-rpclib

从自己的例子中,在远程计算机上:

#include <iostream>
#include "rpc/server.h"
void foo() {
    std::cout << "foo was called!" << std::endl;
}
int main(int argc, char *argv[]) {
    // Creating a server that listens on port 8080
    rpc::server srv(8080);
    // Binding the name "foo" to free function foo.
    // note: the signature is automatically captured
    srv.bind("foo", &foo);
    // Binding a lambda function to the name "add".
    srv.bind("add", [](int a, int b) {
        return a + b;
    });
    // Run the server loop.
    srv.run();
    return 0;
}

在本地:

#include <iostream>
#include "rpc/client.h"
int main() {
    // Creating a client that connects to the localhost on port 8080
    rpc::client client("127.0.0.1", 8080);
    // Calling a function with paramters and converting the result to int
    auto result = client.call("add", 2, 3).as<int>();
    std::cout << "The result is: " << result << std::endl;
    return 0;
}

要执行任何事情,你可以有一个"系统";在远程计算机上调用。所以在服务器端输入:

    // Binding a lambda function to the name "system".
    srv.bind("system", [](char const * command) {
        return system(command);
    });

现在在客户端你做:

    auto result = client.call("system", "ls").as<int>();

显然,如果您想使用这样的库,您需要考虑安全性。这将在可信的局域网环境中很好地工作。在Internet这样的公共网络中,这可能不是一个好主意。

构造一个命令行,使用ssh执行远程命令。然后使用system()执行该命令。

std::string pc2_hostname;
std::string cmd = "ssh " + pc2_hostname + " command_to_execute";
system(cmd.c_str());