2011-09-02 108 views
0

我想从Windows操作系统与PHP站点连接到Solaris服务器,以在Solaris服务器上执行一些shell脚本。该网站只是挂在那里,什么也没做。尝试从PHP站点连接到远程Solaris服务器

<?php 

exec('ssh [email protected]'); 
echo exec('cd Desktop'); 
echo exec('./chong.sh'); 

?> 
+0

一个叫Chong的脚本只是挂在那里,什么都不做?可以[通过设计](http://en.wikipedia.org/wiki/Cheech_%26_Chong)。 –

+0

当您在本地运行脚本时会发生什么?即从Solaris机器上的终端? – DaveRandom

+0

将不会ssh需要一些用户输入,如密码?另外,你确定'ssh'在你的Windows路径中吗? – Andy

回答

0

我猜这里的问题在于你通过ssh连接到Solaris Box而没有对该进程做任何事情。

当您致电ssh [email protected]时,您将启动一个ssh会话与Solaris机箱。这个过程会等待你告诉它该怎么做:

  • 如果你没有设置证书,它可能会要求你输入密码。
  • 即使不是,它会挂起在等待命令的远程盒子上的提示,就像任何普通的终端一样。

即使是这样,你正试图在本地计算机上执行其他命令,与后续调用exec()。为了在远程机器上执行任何操作,您需要将命令传递到您创建的ssh进程中。

尝试proc_open()代替:

$descriptorspec = array(
    0 => array("pipe", "r"), // stdin is a pipe that the child will read from 
    1 => array("pipe", "w"), // stdout is a pipe that the child will write to 
    2 => array("file", "errors.txt", "a") // stderr is a file to write to 
); 

$process = proc_open('ssh [email protected]', $descriptorspec, $pipes); 

if (is_resource($process)) { 
    // $pipes now looks like this: 
    // 0 => writeable handle connected to child stdin 
    // 1 => readable handle connected to child stdout 
    // Any error output will be appended to errors.txt 

    // Clear the input buffer before we send anything - you may need to parse 
    // this to determine when to send the data 
    while (!fgets($pipes[1])) continue; 

    // You may need to send a password 
    // fwrite($pipes[0],"password\n"); 
    // while (!fgets($pipes[1])) continue; 

    // Send the first command and wait for a prompt 
    fwrite($pipes[0],"cd Desktop\n"); 
    while (!fgets($pipes[1])) continue; 

    // Send the next command 
    fwrite($pipes[0],"./chong.sh\n"); 

    // Close the STDIN stream 
    fclose($pipes[0]); 

    // Fetch the result, output it and close the STDOUT stream 
    echo stream_get_contents($pipes[1]); 
    fclose($pipes[1]); 

    // Kill the ssh process and output the return value 
    $return_value = proc_close($process); 
    echo "\ncommand returned $return_value\n"; 

} 

编辑关于它的思考,如果这是一个本地机器,你不必担心安全,你可能会发现更容易通过telnet连接,而不是ssh,因为如果你这样做的话,你可以简单地使用fsockopen()而不是搞乱多个IO流,因为你需要使用proc_open()。