2016-08-23 202 views
-1

我想讓PC上的C++程序在PC2上啓動另一個PC2上的程序。我現在不想過分複雜,所以我們假設程序在PC2上的可執行文件的搜索路徑中。根據我的理解,這可以通過ssh以某種方式完成?假設(爲了進一步簡化),我在PC1和PC2上都有一個帳戶,這樣,如果我在PC1上登錄(沒有任何需要我提供用戶名和密碼的交互),ssh會連接到我,我將如何去做這個? https://www.libssh.org/會幫助簡化事情嗎?如何從C++代碼在另一臺計算機上運行程序?

+0

你知道如何從CLI手動完成嗎?只需在'system()'調用中執行相同的命令即可執行shell命令。 – Barmar

回答

1

構建命令行以使用ssh執行遠程命令。然後使用system()執行該命令。

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

我明白了。如果我使用這個解決方案會發生什麼,但事實證明我必須提供用戶名/密碼?我可以以某種方式檢查在程序調用system()之後ssh是否試圖與用戶交互?我知道我明確表示這在OP中不需要,所以這是一個額外的問題。 – TheMountainThatCodes

+0

您應該配置無密碼SSH。如果確實需要密碼,它會提示用戶。 – Barmar

+0

如果SSH需要密碼,有沒有辦法讓程序打印出錯? – TheMountainThatCodes

3

您可以通過這個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>(); 

顯然,你需要考慮安全性,如果你想使用這樣的庫。這可以在受信任的局域網環境下很好地工作。在像互聯網這樣的公共網絡中,這可能不是一個好主意。

相關問題