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

时间:2013-04-16 17:47:00

标签: php ssh pipe stdin popen

我尝试通过ssh和pipe通信两台机器,以便从一台机器到另一台机器之间收到消息。 第二个使用sdtin从第一台机器读取消息并在文本文件中写入。

我有一台机器,我有这个程序,但它不起作用......

$message = "Hello Boy";
$action = ('ssh root@machineTwo script.php'); 
$handle = popen($action, 'w');

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

在另一台机器上,机器我有:

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

3 个答案:

答案 0 :(得分: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侦听stdin,你可以read() / write()或使用enablePTY()

答案 1 :(得分:0)

此解决方案正在运行:

MACHINE ONE

在使用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);
}

MACHINE TWO

我用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);    
}

答案 2 :(得分:-1)

Popen主要用于使用&#34;管道文件&#34;进行两个本地程序通信。

要实现您的目标,您应该尝试使用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?