2013-04-16 92 views
0

我嘗試通過ssh和pipe傳輸兩臺機器以獲取從一個到另一個的消息。 第二個從sdtin中讀取第一臺機器的消息並寫入文本文件。使用popen,fgets和ssh在兩臺遠程服務器之間發送數據

我有一臺機器在那裏我有這個計劃,但它不工作...

$message = "Hello Boy"; 
$action = ('ssh [email protected] script.php'); 
$handle = popen($action, 'w'); 

if($handle){ 
    echo $message; 
    pclose($handle); 
} 

在其他計算機上,machineTwo我有:

$filename = "test.txt";  
    if(!$fd = fopen($filename, "w"); 
    echo "error"; 
     } 
    else { 
      $action = fgets(STDIN); 
      fwrite($fd, $action); 
    /*On ferme le fichier*/ 
    fclose($fd);} 

回答

0

將該溶液工作:

MACHINE ONE

我將消息發送到所述機二被連接到機二使用ssh後。我用popenfwrite

//MACHINE ONE 
$message = "Hello Boy"; 
$action = ('ssh [email protected] script.php'); //conection by ssh-rsa 
$handle = popen($action, 'w'); //pipe open between machineOne & two 

if($handle){ 
    fwrite($handle, $message); //write in machineTwo 
    pclose($handle); 
} 

機兩臺

我打開與fopen文件,並得到機一與fgets(STDIN)的消息;。我在打開的文件中寫入消息。

//MACHINETWO 
$filename = "test.txt";  
if(!$fd = fopen($filename, "w"); 
    echo "error"; 
} 

else 
{ 
    $message = fgets(STDIN); 
    fwrite($fd, $message); //text.txt have now Hello World ! 
    /*we close the file*/ 
    fclose($fd);  
} 
-1

POPEN主要是用來有兩個本地程序使用「管道文件」進行通信。

達到你想要什麼,你應該嘗試SSH2 PHP庫(一個有趣的鏈接http://kvz.io/blog/2007/07/24/make-ssh-connections-with-php/

在你的情況,你會做這樣的事情對你的PHP腳本上machineOne:

if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist"); 
if (!($con = ssh2_connect("machineTwo", 22))) { 
    echo "fail: unable to establish connection\n"; 
} else { 
    if (!ssh2_auth_password($con, "root", "yourpass")) { 
     echo "fail: unable to authenticate\n"; 
    } else { 
     echo "okay: logged in...\n"; 

     if (!($stream = ssh2_exec($con, "php script.php"))) { //execute php script on machineTwo 
       echo "fail executing command\n"; 
      } else { 
       // collect returning data from command 
       stream_set_blocking($stream, true); 
       $data = ""; 
       while ($buf = fread($stream,4096)) { 
        $data .= $buf; 
       } 
       fclose($stream); 
       echo $data; //text returned by your script.php 
      } 
    } 
} 

我假設你有一個很好的理由來做到這一點,但爲什麼使用PHP?

2

這裏做到這一點(使用phpseclib, a pure PHP SSH2 implementation)最簡單的方法:

<?php 
include('Net/SSH2.php'); 

$ssh = new Net_SSH2('www.domain.tld'); 
if (!$ssh->login('username', 'password')) { 
    exit('Login Failed'); 
} 

echo $ssh->exec('php script.php'); 
?> 

隨着RSA私鑰:

<?php 
include('Net/SSH2.php'); 

$ssh = new Net_SSH2('www.domain.tld'); 
$key = new Crypt_RSA(); 
$key->loadKey(file_get_contents('privatekey')); 
if (!$ssh->login('username', $key)) { 
    exit('Login Failed'); 
} 

echo $ssh->exec('php script.php'); 
?> 

如果script.php的偵聽標準輸入你也許可以做到read()/write()或使用enablePTY()

相關問題