使用popen、fgets和ssh在两个远程服务器之间发送数据


Send data between two remote servers with popen, fgets and ssh

我尝试通过ssh和管道与两台机器通信,以从一台机器到另一台机器获取消息。第二个从第一台机器读取消息,并在文本文件中写入sdtin。

我有一台机器,我有这个程序,但是它不工作…

$message = "Hello Boy";
$action = ('ssh root@machineTwo 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);}

这是最简单的方法(使用phpseclib,一个纯PHP SSH2实现):

<?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监听stdin,你可以使用read()/write()或者使用enablePTY()

这个解决方案是有效的:

机一个

在用ssh连接到MACHINE TWO后,我向MACHINE TWO发送一条消息。我使用popenfwrite
//MACHINE ONE
$message = "Hello Boy";
$action = ('ssh root@machineTwo 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);得到MACHINE ONE的消息。我把消息写在打开的文件中。

//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);    
}

Popen主要用于让两个本地程序通过"管道文件"进行通信。

要实现您想要的,您应该尝试SSH2 PHP库(一个有趣的链接http://kvz.io/blog/2007/07/24/make-ssh-connections-with-php/)

在你的情况下,你可以在machineOne上为你的php脚本这样做:

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呢?