2015-07-10 23 views
1

我想通过PHP使用SSH连接来运行Bash脚本。如何使用PHP分别运行2个SSH命令?

我写了一个脚本来进行备份和恢复的MySQL数据库和我还在测试,以实现这一目标。我在尝试 运行两个不同的简单命令时遇到了问题。我的代码是:

<?php 
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist"); 

if(!($con = ssh2_connect("server.hosting.com", 22))){ 
    echo "fail: unable to establish connection\n"; 
} else { 

    if(!ssh2_auth_password($con, "username", "password")) { 
     echo "fail: unable to authenticate\n"; 
    } else { 
     // allright, we're in! 
     echo "okay: logged in...\n"; 




     if (!($stream = ssh2_exec($con, "cd directory "))) { 
      echo "fail: unable to execute command\n"; 
     } else { 
      // collect returning data from command 
      stream_set_blocking($stream, true); 
      $data = ""; 
      while ($buf = fread($stream,4096)) { 
       $data .= $buf; 
      } 
      fclose($stream); 
     } 
if (!($stream = ssh2_exec($con, "mkdir directiry2"))) { 
      echo "fail: unable to execute command\n"; 
     } else { 
      // collect returning data from command 
      stream_set_blocking($stream, true); 
      $data = ""; 
      while ($buf = fread($stream,4096)) { 
       $data .= $buf; 
      } 
      fclose($stream); 
     } 
    } 
} 
?> 

它仍然创建另一个目录,但不在“目录”里面! 请帮忙!!!

+0

为什么不'的mkdir -p目录/ directiry2'?你不需要cd进入一个目录来制作其中的内容。 –

+0

感谢那个马克B,现在我该如何运行这样的东西: 'mysqldump -u ... -p ... mydb t1 t2 t3> mydb_tables.sql' –

+0

[无耻的酒吧]你可能想要一个看https://github.com/tivie/command 它可以让您链shell命令和一个面向对象的方式设定CWD – Tivie

回答