php - 如何使用PHP分别运行2个SSH命令?

标签 php ssh

我正在尝试通过PHP使用SSH连接来运行Bash脚本。

我编写了一个脚本来为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);
        }
    }
}
?>

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

最佳答案

问题是,当您执行cd时,“状态”将立即丢失。 phpseclib文档详细说明:

http://phpseclib.sourceforge.net/ssh/examples.html#chdir

如果您希望能够CD到一个目录,然后在该目录中执行操作,则可以将内容链接起来。例如。 $ssh->exec('cd directory; mkdir directiry2');

关于php - 如何使用PHP分别运行2个SSH命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31345564/

相关文章:

php - MYSQL 自动填充字段

php - 使用 Laravel 4 发现 404 错误

git 产生 Gtk-WARNING : cannot open display

bash - 当尝试登录它生成的 ssh session 时如何预期超时?

python - 通过 Python 子进程的 SSH 密码

成功登录后 SSH 连接卡住(有时)

ssh - telnet/SSH 连接到底发生了什么?

php - "Connection Refused"或 "No Such File or Directory"

php - 在 PHP-CS-Fixer 中使用制表符缩进

php - 类的动态加载无法解决命名空间/使用