如何从C++代码在另一台计算机上运行程序?
我想让PC上的C++程序在PC2上启动另一个PC2上的程序。我现在不想过分复杂,所以我们假设程序在PC2上的可执行文件的搜索路径中。根据我的理解,这可以通过ssh以某种方式完成?假设(为了进一步简化),我在PC1和PC2上都有一个帐户,这样,如果我在PC1上登录(没有任何需要我提供用户名和密码的交互),ssh会连接到我,我将如何去做这个? https://www.libssh.org/会帮助简化事情吗?如何从C++代码在另一台计算机上运行程序?
构建命令行以使用ssh
执行远程命令。然后使用system()
执行该命令。
std::string pc2_hostname;
std::string cmd = "ssh " + pc2_hostname + " command_to_execute";
system(cmd.c_str());
我明白了。如果我使用这个解决方案会发生什么,但事实证明我必须提供用户名/密码?我可以以某种方式检查在程序调用system()之后ssh是否试图与用户交互?我知道我明确表示这在OP中不需要,所以这是一个额外的问题。 – TheMountainThatCodes
您应该配置无密码SSH。如果确实需要密码,它会提示用户。 – Barmar
如果SSH需要密码,有没有办法让程序打印出错? – TheMountainThatCodes
您可以通过这个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 "add".
srv.bind("system", [](char const * command) {
return system(command);
});
现在在客户端你做:
auto result = client.call("system", "ls").as<int>();
显然,你需要考虑安全性,如果你想使用这样的库。这可以在受信任的局域网环境下很好地工作。在像互联网这样的公共网络中,这可能不是一个好主意。
你知道如何从CLI手动完成吗?只需在'system()'调用中执行相同的命令即可执行shell命令。 – Barmar